Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

save initial hidden states in sequence tagger #3010

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions flair/models/sequence_tagger_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ def __init__(
self.linear = torch.nn.Linear(hidden_output_dim, len(self.label_dictionary))
else:
self.linear = torch.nn.Linear(embedding_dim, len(self.label_dictionary))
self.train_initial_hidden_state = False

# the loss function is Viterbi if using CRF, else regular Cross Entropy Loss
self.loss_function = (
Expand Down Expand Up @@ -606,6 +607,7 @@ def _get_state_dict(self):
"rnn_type": self.rnn_type,
"reproject_embeddings": self.reproject_embeddings,
"weight_dict": self.weight_dict,
"train_initial_hidden_state": self.train_initial_hidden_state,
}

return model_state
Expand Down Expand Up @@ -635,6 +637,7 @@ def _init_model_with_state_dict(cls, state, **kwargs):
reproject_embeddings=state.get("reproject_embeddings", True),
loss_weights=state.get("weight_dict"),
init_from_state_dict=True,
train_initial_hidden_state=state.get("train_initial_hidden_state", False),
**kwargs,
)

Expand Down
19 changes: 19 additions & 0 deletions tests/models/test_sequence_tagger.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,25 @@ def test_train_load_use_tagger_flair_embeddings(self, results_base_path, corpus,
loaded_model.predict([self.empty_sentence])
del loaded_model

@pytest.mark.integration
def test_train_load_use_tagger_with_trainable_hidden_state(
self, embeddings, results_base_path, corpus, example_sentence
):
tag_dictionary = corpus.make_label_dictionary("ner", add_unk=False)

model = self.build_model(embeddings, tag_dictionary, train_initial_hidden_state=True)
trainer = ModelTrainer(model, corpus)

trainer.train(results_base_path, shuffle=False, **self.training_args)

del trainer, model, tag_dictionary, corpus
loaded_model = self.model_cls.load(results_base_path / "final-model.pt")

loaded_model.predict(example_sentence)
loaded_model.predict([example_sentence, self.empty_sentence])
loaded_model.predict([self.empty_sentence])
del loaded_model

@pytest.mark.integration
def test_train_load_use_tagger_disjunct_tags(
self, results_base_path, tasks_base_path, embeddings, example_sentence
Expand Down