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

[Serialization] add argument to pass shared tensors names to drop when saving #2696

Merged
merged 1 commit into from
Dec 6, 2024

Conversation

hanouticelina
Copy link
Contributor

@hanouticelina hanouticelina commented Dec 5, 2024

Related to transformers#35080.

Currently, when saving a torch state dict with shared tensors, the key to keep is chosen alphabetically which might not be the desired behavior. This PR simply adds an optional state_dict_keys_to_discard argument to both save_torch_state_dict() and save_torch_model() that allows users to specify which keys should be discarded in priority when duplicates are found.
Note : The logic behind choosing which key should be discarded in priority is framework/model-specific and should be handled by the user. For example, for transformers.PreTrainedModel models, this is specified in the _tied_weights_keys attribute, example usage:

model = ... # A model inheriting from PreTrainedModel
save_torch_model(
    model,
    "path/to/folder",
    state_dict_keys_to_discard=model._tied_weights_keys,
)

or with save_torch_state_dict()

model = ... # A model inheriting from PreTrainedModel
save_torch_state_dict(
    model.state_dict(),
    "path/to/folder",
    state_dict_keys_to_discard=model._tied_weights_keys,
)

@HuggingFaceDocBuilderDev

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Copy link
Member

@SunMarc SunMarc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice ! Thanks for adding this !

Copy link
Contributor

@Wauplin Wauplin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you !

@hanouticelina hanouticelina merged commit a3d48a2 into main Dec 6, 2024
17 checks passed
@hanouticelina hanouticelina deleted the fix-discard-shared-tensors branch December 6, 2024 17:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants