Skip to content

Commit

Permalink
[FSMT] Fix non-shared weights (huggingface#26187)
Browse files Browse the repository at this point in the history
* Fix non-shared weights

* Add tests

* Edit tied weights keys
  • Loading branch information
LysandreJik authored and EduardoPach committed Nov 18, 2023
1 parent be10237 commit 1362078
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/transformers/models/fsmt/modeling_fsmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,7 @@ def _get_shape(t):
FSMT_START_DOCSTRING,
)
class FSMTModel(PretrainedFSMTModel):
_tied_weights_keys = ["decoder.embed_tokens.weight"]
_tied_weights_keys = ["decoder.embed_tokens.weight", "decoder.output_projection.weight"]

def __init__(self, config: FSMTConfig):
super().__init__(config)
Expand All @@ -1055,6 +1055,10 @@ def get_encoder(self):
def get_decoder(self):
return self.decoder

def _tie_weights(self):
self._tie_or_clone_weights(self.decoder.embed_tokens, self.get_input_embeddings())
self._tie_or_clone_weights(self.decoder.output_projection, self.get_input_embeddings())

@add_start_docstrings_to_model_forward(FSMT_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
Expand Down Expand Up @@ -1171,7 +1175,7 @@ def set_output_embeddings(self, value):
)
class FSMTForConditionalGeneration(PretrainedFSMTModel):
base_model_prefix = "model"
_tied_weights_keys = ["model.decoder.embed_tokens.weight"]
_tied_weights_keys = ["decoder.embed_tokens.weight", "decoder.output_projection.weight"]

def __init__(self, config: FSMTConfig):
super().__init__(config)
Expand Down
17 changes: 17 additions & 0 deletions tests/models/fsmt/test_modeling_fsmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,23 @@ def test_export_to_onnx(self):
input_names=["input_ids", "attention_mask"],
)

def test_ensure_weights_are_shared(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs()
model = FSMTForConditionalGeneration(config)

# FSMT shares three weights.
# Not an issue to not have these correctly tied for torch.load, but it is an issue for safetensors.
self.assertEqual(
len(
{
model.get_output_embeddings().weight.data_ptr(),
model.get_input_embeddings().weight.data_ptr(),
model.base_model.decoder.output_projection.weight.data_ptr(),
}
),
1,
)

@unittest.skip("can't be implemented for FSMT due to dual vocab.")
def test_resize_tokens_embeddings(self):
pass
Expand Down

0 comments on commit 1362078

Please sign in to comment.