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

fix(save_file): add force_contiguous(default=True) to save_file #530

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 8 additions & 0 deletions bindings/python/py_src/safetensors/torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ def save_file(
tensors: Dict[str, torch.Tensor],
filename: Union[str, os.PathLike],
metadata: Optional[Dict[str, str]] = None,
force_contiguous: Optional[bool] = True,
):
"""
Saves a dictionary of tensors into raw bytes in safetensors format.
Expand All @@ -269,6 +270,11 @@ def save_file(
Optional text only metadata you might want to save in your header.
For instance it can be useful to specify more about the underlying
tensors. This is purely informative and does not affect tensor loading.
force_contiguous (`boolean`, *optional*, defaults to True):
Forcing the state_dict to be saved as contiguous tensors.
This has no effect on the correctness of the model, but it
could potentially change performance if the layout of the tensor
was chosen specifically for that reason.

Returns:
`None`
Expand All @@ -283,6 +289,8 @@ def save_file(
save_file(tensors, "model.safetensors")
```
"""
if force_contiguous:
tensors = {k: v.contiguous() for k, v in tensors.items()}
serialize_file(_flatten(tensors), filename, metadata=metadata)


Expand Down