import os
import sys
from collections import defaultdict
-from typing import Any, Dict, Optional, Union
+from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
from safetensors import deserialize, safe_open, serialize, serialize_file
+def storage_ptr(tensor: torch.Tensor) -> int:
+ try:
+ return tensor.untyped_storage().data_ptr()
+ except Exception:
+ # Fallback for torch==1.10
+ try:
+ return tensor.storage().data_ptr()
+ except NotImplementedError:
+ # Fallback for meta storage
+ return 0
+
+
+def storage_size(tensor: torch.Tensor) -> int:
+ try:
+ return tensor.untyped_storage().nbytes()
+ except AttributeError:
+ # Fallback for torch==1.10
+ try:
+ return tensor.storage().size() * _SIZE[tensor.dtype]
+ except NotImplementedError:
+ # Fallback for meta storage
+ # On torch >=2.0 this is the tensor size
+ return tensor.nelement() * _SIZE[tensor.dtype]
+
+
+def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
+ tensors = defaultdict(set)
+ for k, v in state_dict.items():
+ if v.device != torch.device("meta"):
+ # Need to add device as key because of multiple GPU.
+ tensors[(storage_ptr(v), v.device)].add(k)
+ tensors = list(sorted(tensors.values()))
+ return tensors
+
+
+def _is_complete(tensor: torch.Tensor) -> bool:
+ return tensor.data_ptr() == storage_ptr(tensor) and tensor.nelement() * _SIZE[tensor.dtype] == storage_size(tensor)
+
+
+def _remove_duplicate_names(
+ state_dict: Dict[str, torch.Tensor], preferred_names: List[str] = None
+) -> Dict[str, List[str]]:
+ if preferred_names is None:
+ preferred_names = []
+ preferred_names = set(preferred_names)
+
+ shareds = _find_shared_tensors(state_dict)
+ to_remove = defaultdict(list)
+ for shared in shareds:
+ complete_names = [name for name in shared if _is_complete(state_dict[name])]
+ if not complete_names:
+ raise RuntimeError(
+ f"Error while trying to find names to remove to save state dict, but found no suitable name to keep for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model since you could be storing much more memory than needed. Please refer to https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an issue."
+ )
+
+ preferred = preferred_names.intersection(set(complete_names))
+ # Mecanism to preferentially select keys to keep
+ # coming from the on-disk file to allow\
+ # loading models saved with a different choice
+ # of keep_name
+ if preferred:
+ keep_name = sorted(list(preferred))[0]
+ else:
+ keep_name = sorted(complete_names)[0]
+ for name in sorted(shared):
+ if name != keep_name:
+ to_remove[keep_name].append(name)
+ return to_remove
+
+
+def save_model(
+ model: torch.nn.Module, filename: str, metadata: Optional[Dict[str, str]] = None, force_contiguous: bool = True
+):
+ """
+ Saves a given torch model to specified filename.
+ This method exists specifically to avoid tensor sharing issues which are
+ not allowed in `safetensors`. [More information on tensor sharing](torch_shared_tensors)
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to save on disk.
+ filename (`str`):
+ The filename location to save the file
+ metadata (`Dict[str, str]`, *optional*):
+ Extra information to save along with the file.
+ Some metadata will be added for each dropped tensors.
+ This information will not be enough to recover the entire
+ shared structure but might help understanding things
+ 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.
+ """
+ state_dict = model.state_dict()
+ to_removes = _remove_duplicate_names(state_dict)
+
+ for kept_name, to_remove_group in to_removes.items():
+ for to_remove in to_remove_group:
+ if metadata is None:
+ metadata = {}
+
+ if to_remove not in metadata:
+ # Do not override user data
+ metadata[to_remove] = kept_name
+ del state_dict[to_remove]
+ if force_contiguous:
+ state_dict = {k: v.contiguous() for k, v in state_dict.items()}
+ try:
+ save_file(state_dict, filename, metadata=metadata)
+ except ValueError as e:
+ msg = str(e)
+ msg += " Or use save_model(..., force_contiguous=True), read the docs for potential caveats."
+ raise ValueError(msg)
+
+
+def load_model(model: torch.nn.Module, filename: str, strict=True) -> Tuple[List[str], List[str]]:
+ """
+ Loads a given filename onto a torch model.
+ This method exists specifically to avoid tensor sharing issues which are
+ not allowed in `safetensors`. [More information on tensor sharing](torch_shared_tensors)
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to load onto.
+ filename (`str`):
+ The filename location to load the file from.
+ strict (`bool`, *optional*, defaults to True):
+ Wether to fail if you're missing keys or having unexpected ones
+ When false, the function simply returns missing and unexpected names.
+
+ Returns:
+ `(missing, unexpected): (List[str], List[str])`
+ `missing` are names in the model which were not modified during loading
+ `unexpected` are names that are on the file, but weren't used during
+ the load.
+ """
+ state_dict = load_file(filename)
+ model_state_dict = model.state_dict()
+ to_removes = _remove_duplicate_names(model_state_dict, preferred_names=state_dict.keys())
+ missing, unexpected = model.load_state_dict(state_dict, strict=False)
+ missing = set(missing)
+ for to_remove_group in to_removes.values():
+ for to_remove in to_remove_group:
+ if to_remove not in missing:
+ unexpected.append(to_remove)
+ else:
+ missing.remove(to_remove)
+ if strict and (missing or unexpected):
+ missing_keys = ", ".join([f'"{k}"' for k in sorted(missing)])
+ unexpected_keys = ", ".join([f'"{k}"' for k in sorted(unexpected)])
+ error = f"Error(s) in loading state_dict for {model.__class__.__name__}:"
+ if missing:
+ error += f"\n Missing key(s) in state_dict: {missing_keys}"
+ if unexpected:
+ error += f"\n Unexpected key(s) in state_dict: {unexpected_keys}"
+ raise RuntimeError(error)
+ return missing, unexpected
+
+
def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
"""
Saves a dictionary of tensors into raw bytes in safetensors format.
if failing:
raise RuntimeError(
- f"""Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}"""
+ f"""
+ Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}.
+ A potential way to correctly save your model is to use `save_model`.
+ More information at https://huggingface.co/docs/safetensors/torch_shared_tensors
+ """
)
return {
"huggingface_hub>=0.12.1",
"isort>=5.5.4",
"jax>=0.3.25",
+ "jaxlib>=0.3.25",
"numpy>=1.21.6",
"setuptools_rust>=1.5.2",
"pytest>=7.2.0",
extras["torch"] = deps_list("torch")
extras["numpy"] = deps_list("numpy")
extras["tensorflow"] = deps_list("tensorflow")
-extras["jax"] = deps_list("jax", "flax")
+extras["jax"] = deps_list("jax", "flax", "jaxlib")
extras["paddlepaddle"] = deps_list("paddlepaddle")
extras["quality"] = deps_list("black", "isort", "flake8", "click")
extras["testing"] = (
--- /dev/null
+import copy
+import unittest
+
+import torch
+
+from safetensors import safe_open
+from safetensors.torch import (
+ _find_shared_tensors,
+ _is_complete,
+ _remove_duplicate_names,
+ load_model,
+ save_file,
+ save_model,
+)
+
+
+class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = torch.nn.Linear(100, 100)
+ self.b = self.a
+
+
+class NonContiguousModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = torch.nn.Linear(100, 100)
+ A = torch.zeros((100, 100))
+ A = A.transpose(0, 1)
+ self.a.weight = torch.nn.Parameter(A)
+
+
+class CopyModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = torch.nn.Linear(100, 100)
+ self.b = copy.deepcopy(self.a)
+
+
+class NoSharedModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = torch.nn.Linear(100, 100)
+ self.b = torch.nn.Linear(100, 100)
+
+
+class TorchModelTestCase(unittest.TestCase):
+ def test_is_complete(self):
+ A = torch.zeros((3, 3))
+ self.assertTrue(_is_complete(A))
+
+ B = A[:1, :]
+ self.assertFalse(_is_complete(B))
+
+ # Covers the whole storage but with holes
+ C = A[::2, :]
+ self.assertFalse(_is_complete(C))
+
+ D = torch.zeros((2, 2), device=torch.device("meta"))
+ self.assertTrue(_is_complete(D))
+
+ def test_find_shared_tensors(self):
+ A = torch.zeros((3, 3))
+ B = A[:1, :]
+
+ self.assertEqual(_find_shared_tensors({"A": A, "B": B}), [{"A", "B"}])
+ self.assertEqual(_find_shared_tensors({"A": A}), [{"A"}])
+ self.assertEqual(_find_shared_tensors({"B": B}), [{"B"}])
+
+ C = torch.zeros((2, 2), device=torch.device("meta"))
+ D = C[:1]
+ # Meta device is not shared
+ self.assertEqual(_find_shared_tensors({"C": C, "D": D}), [])
+ self.assertEqual(_find_shared_tensors({"C": C}), [])
+ self.assertEqual(_find_shared_tensors({"D": D}), [])
+
+ def test_remove_duplicate_names(self):
+ A = torch.zeros((3, 3))
+ B = A[:1, :]
+
+ self.assertEqual(_remove_duplicate_names({"A": A, "B": B}), {"A": ["B"]})
+ self.assertEqual(_remove_duplicate_names({"A": A, "B": B, "C": A}), {"A": ["B", "C"]})
+ with self.assertRaises(RuntimeError):
+ self.assertEqual(_remove_duplicate_names({"B": B}), [])
+
+ def test_failure(self):
+ model = Model()
+ with self.assertRaises(RuntimeError):
+ save_file(model.state_dict(), "tmp.safetensors")
+
+ # def test_workaround_refuse(self):
+ # model = Model()
+ # A = torch.zeros((1000, 10))
+ # a = A[:100, :]
+ # model.a.weight = torch.nn.Parameter(a)
+ # with self.assertRaises(RuntimeError) as ctx:
+ # save_model(model, "tmp4.safetensors")
+ # self.assertIn(".Refusing to save/load the model since you could be storing much more memory than needed.", str(ctx.exception))
+
+ def test_workaround(self):
+ model = Model()
+ save_model(model, "tmp.safetensors")
+ with safe_open("tmp.safetensors", framework="pt") as f:
+ self.assertEqual(f.metadata(), {"b.bias": "a.bias", "b.weight": "a.weight"})
+
+ model2 = Model()
+ load_model(model2, "tmp.safetensors")
+
+ state_dict = model.state_dict()
+ for k, v in model2.state_dict().items():
+ torch.testing.assert_close(v, state_dict[k])
+
+ def test_workaround_works_with_different_on_file_names(self):
+ model = Model()
+ state_dict = model.state_dict()
+ state_dict.pop("a.weight")
+ state_dict.pop("a.bias")
+ save_file(state_dict, "tmp.safetensors")
+
+ model2 = Model()
+ load_model(model2, "tmp.safetensors")
+
+ state_dict = model.state_dict()
+ for k, v in model2.state_dict().items():
+ torch.testing.assert_close(v, state_dict[k])
+
+ def test_workaround_non_contiguous(self):
+ model = NonContiguousModel()
+
+ with self.assertRaises(ValueError) as ctx:
+ save_model(model, "tmp_c.safetensors", force_contiguous=False)
+ self.assertIn("use save_model(..., force_contiguous=True)", str(ctx.exception))
+ save_model(model, "tmp_c.safetensors", force_contiguous=True)
+
+ model2 = NonContiguousModel()
+ load_model(model2, "tmp_c.safetensors")
+
+ state_dict = model.state_dict()
+ for k, v in model2.state_dict().items():
+ torch.testing.assert_close(v, state_dict[k])
+
+ def test_workaround_copy(self):
+ model = CopyModel()
+ self.assertEqual(
+ _find_shared_tensors(model.state_dict()), [{"a.weight"}, {"a.bias"}, {"b.weight"}, {"b.bias"}]
+ )
+ save_model(model, "tmp.safetensors")
+
+ model2 = CopyModel()
+ load_model(model2, "tmp.safetensors")
+
+ state_dict = model.state_dict()
+ for k, v in model2.state_dict().items():
+ torch.testing.assert_close(v, state_dict[k])
+
+ def test_difference_with_torch(self):
+ model = Model()
+ torch.save(model.state_dict(), "tmp2.bin")
+
+ model2 = NoSharedModel()
+ # This passes on torch.
+ # The tensors are shared on disk, they are *not* shared within the model
+ # The model happily loads the tensors, and ends up *not* sharing the tensors by.
+ # doing copies
+ self.assertEqual(
+ _find_shared_tensors(model2.state_dict()), [{"a.weight"}, {"a.bias"}, {"b.weight"}, {"b.bias"}]
+ )
+ model2.load_state_dict(torch.load("tmp2.bin"))
+ self.assertEqual(
+ _find_shared_tensors(model2.state_dict()), [{"a.weight"}, {"a.bias"}, {"b.weight"}, {"b.bias"}]
+ )
+
+ # However safetensors cannot save those, so we cannot
+ # reload the saved file with the different model
+ save_model(model, "tmp2.safetensors")
+ with self.assertRaises(RuntimeError) as ctx:
+ load_model(model2, "tmp2.safetensors")
+ self.assertIn("""Missing key(s) in state_dict: "b.bias", "b.weight""", str(ctx.exception))
+
+ def test_difference_torch_odd(self):
+ model = NoSharedModel()
+ a = model.a.weight
+ b = model.b.weight
+ self.assertNotEqual(a.data_ptr(), b.data_ptr())
+ torch.save(model.state_dict(), "tmp3.bin")
+
+ model2 = Model()
+ self.assertEqual(_find_shared_tensors(model2.state_dict()), [{"a.weight", "b.weight"}, {"b.bias", "a.bias"}])
+ # Torch will affect either `b` or `a` to the shared tensor in the `model2`
+ model2.load_state_dict(torch.load("tmp3.bin"))
+
+ # XXX: model2 uses only the B weight not the A weight anymore.
+ self.assertFalse(torch.allclose(model2.a.weight, model.a.weight))
+ torch.testing.assert_close(model2.a.weight, model.b.weight)
+ self.assertEqual(_find_shared_tensors(model2.state_dict()), [{"a.weight", "b.weight"}, {"b.bias", "a.bias"}])
+
+ # Everything is saved as-is
+ save_model(model, "tmp3.safetensors")
+ # safetensors will yell that there were 2 tensors on disk, while
+ # the models expects only 1 tensor since both are shared.
+ with self.assertRaises(RuntimeError) as ctx:
+ load_model(model2, "tmp3.safetensors")
+ # Safetensors properly warns the user that some ke
+ self.assertIn("""Unexpected key(s) in state_dict: "b.bias", "b.weight""", str(ctx.exception))
title: 🤗 Safetensors
- local: speed
title: Speed Comparison
+ - local: torch_shared_tensors
+ title: Tensor Sharing in Pytorch
title: Getting started
- sections:
- local: api/torch
--- /dev/null
+# Torch shared tensors
+
+
+## TL;DR
+
+Using specific functions, which should work in most cases for you.
+This is not without side effects.
+
+```python
+from safetensors.torch load_model, save_model
+
+save_model(model, "model.safetensors")
+# Instead of save_file(model.state_dict(), "model.safetensors")
+
+load_model(model, "model.safetensors")
+# Instead of model.load_state_dict(load_file("model.safetensors"))
+```
+
+## What are shared tensors ?
+
+Pytorch uses shared tensors for some computation.
+This is extremely interesting to reduce memory usage in general.
+
+One very classic use case is in transformers the `embeddings` are shared with
+`lm_head`. By using the same matrix, the model uses less parameters, and gradients
+flow much better to the `embeddings` (which is the start of the model, so they don't
+flow easily there, whereas `lm_head` is at the tail of the model, so gradients are
+extremely good over there, since they are the same tensors, they both benefit)
+
+
+```python
+from torch import nn
+
+class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = nn.Linear(100, 100)
+ self.b = self.a
+
+ def forward(self, x):
+ return self.b(self.a(x))
+
+
+model = Model()
+print(model.state_dict())
+# odict_keys(['a.weight', 'a.bias', 'b.weight', 'b.bias'])
+torch.save(model.state_dict(), "model.bin")
+# This file is now 41k instead of ~80k, because A and B are the same weight hence only 1 is saved on disk with both `a` and `b` pointing to the same buffer
+```
+
+## Why are shared tensors not saved in `safetensors` ?
+
+Multiple reasons for that:
+
+- *Not all frameworks support them* for instance `tensorflow` does not.
+ So if someone saves shared tensors in torch, there is no way to
+ load them in a similar fashion so we could not keep the same `Dict[str, Tensor]`
+ API.
+- *It makes lazy loading very quircky.*
+ Lazy loading is the ability to load only some tensors, or part of tensors for
+ a given file. This is trivial to do without sharing tensors but with tensor sharing
+
+ ```python
+ with safe_open("model.safetensors", framework="pt") as f:
+ a = f.get_tensor("a")
+ b = f.get_tensor("b")
+ ```
+
+ Now it's impossible with this given code to "reshare" buffers after the fact.
+ Once we give the `a` tensor we have no way to give back the same memory when
+ you ask for `b`. (In this particular example we could keep track of given buffers
+ but this is not the case in general, since you could do arbitrary work with `a`
+ like sending it to another device before asking for `b`)
+- *It can lead to much larger file than necessary*.
+ If you are saving a shared tensor which is only a fraction of a larger tensor,
+ then saving it with pytorch leads to saving the entire buffer instead of saving
+ just what is needed.
+
+ ```python
+ a = torch.zeros((100, 100))
+ b = a[:1, :]
+ torch.save({"b": b}, "model.bin")
+ # File is 41k instead of the epected 400 bytes
+ # In practice it could happen that you save several 10GB instead of 1GB.
+ ```
+
+Now with all those reasons being mentionned, nothing is set in stone in there.
+Shared tensors do not cause unsafety, or denial of service potential, so this
+decision could be revisited if current workarounds are not satisfactory.
+
+## How does it work ?
+
+The design is rather simple.
+We're going to look for all shared tensors, then looking for all tensors
+covering the entire buffer (there can be multiple such tensors).
+That gives us multiple names which can be saved, we simply choose the first one
+
+During `load_model`, we are loading a bit like `load_state_dict` does, except
+we're looking into the model itself, to check for shared buffers, and ignoring
+the "missed keys" which were actually covered by virtue of buffer sharing (they
+were properly loaded since there was a buffer that loaded under the hood).
+Every other error is raised as-is
+
+**Caveat**: This means we're dropping some keys within the file. meaning if you're
+checking for the keys saved on disk, you will see some "missing tensors" or if you're
+using `load_state_dict`. Unless we start supporting shared tensors directly in
+the format there's no real way around it.