return 0
+def _end_ptr(tensor: torch.Tensor) -> int:
+ if tensor.nelement():
+ stop = tensor.view(-1)[-1].data_ptr() + _SIZE[tensor.dtype]
+ else:
+ stop = tensor.data_ptr()
+ return stop
+
+
def storage_size(tensor: torch.Tensor) -> int:
try:
return tensor.untyped_storage().nbytes()
return tensor.nelement() * _SIZE[tensor.dtype]
+def _filter_shared_not_shared(tensors: List[Set[str]], state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
+ filtered_tensors = []
+ for shared in tensors:
+
+ if len(shared) < 2:
+ filtered_tensors.append(shared)
+ continue
+
+ areas = []
+ for name in shared:
+ tensor = state_dict[name]
+ areas.append((tensor.data_ptr(), _end_ptr(tensor), name))
+ areas.sort()
+
+ _, last_stop, last_name = areas[0]
+ filtered_tensors.append({last_name})
+ for start, stop, name in areas[1:]:
+ if start >= last_stop:
+ filtered_tensors.append({name})
+ else:
+ filtered_tensors[-1].add(name)
+ last_stop = stop
+
+ return filtered_tensors
+
+
def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
tensors = defaultdict(set)
for k, v in state_dict.items():
# Need to add device as key because of multiple GPU.
tensors[(v.device, storage_ptr(v), storage_size(v))].add(k)
tensors = list(sorted(tensors.values()))
+ tensors = _filter_shared_not_shared(tensors, state_dict)
return tensors
def _remove_duplicate_names(
state_dict: Dict[str, torch.Tensor],
*,
- preferred_names: List[str] = None,
- discard_names: List[str] = None,
+ preferred_names: Optional[List[str]] = None,
+ discard_names: Optional[List[str]] = None,
) -> Dict[str, List[str]]:
if preferred_names is None:
preferred_names = []
complete_names = set([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."
+ "Error while trying to find names to remove to save state dict, but found no suitable name to keep"
+ f" 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."
)
keep_name = sorted(list(complete_names))[0]
def test_disjoint_tensors_shared_storage(self):
A = torch.zeros((10, 10))
data = {
- "test": A[:, :0],
- "test2": A[:0],
+ "test": A[1:],
+ "test2": A[:1],
}
local = "./tests/data/out_safe_pt_mmap_small4.safetensors"
- with self.assertRaises(RuntimeError) as ex:
- save_file(data, local)
- self.assertIn("tensors share memory", str(ex.exception))
+ save_file(data, local)
def test_meta_tensor(self):
A = torch.zeros((10, 10), device=torch.device("meta"))
self.assertEqual(
binary,
# Spaces are for forcing the alignment.
- b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"F32","shape":[2,2],"data_offsets":[0,16]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"F32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
reloaded = load(binary)
self.assertTrue(torch.equal(data["test"], reloaded["test"]))
save_file(data, local)
self.assertEqual(
str(ctx.exception),
- "You are trying to save a sparse tensors: `['test']` which this library does not support. You can make it a"
- " dense tensor before saving with `.to_dense()` but be aware this might make a much larger file than"
+ "You are trying to save a sparse tensors: `['test']` which this library does not support. You can make it"
+ " a dense tensor before saving with `.to_dense()` but be aware this might make a much larger file than"
" needed.",
)
from safetensors import safe_open
from safetensors.torch import (
+ _end_ptr,
_find_shared_tensors,
_is_complete,
_remove_duplicate_names,
self.assertEqual(_find_shared_tensors({"C": C}), [])
self.assertEqual(_find_shared_tensors({"D": D}), [])
+ def test_find_shared_non_shared_tensors(self):
+ A = torch.zeros((4,))
+ B = A[:2]
+ C = A[2:]
+ # Shared storage but do not overlap
+ self.assertEqual(_find_shared_tensors({"B": B, "C": C}), [{"B"}, {"C"}])
+
+ B = A[:2]
+ C = A[1:]
+ # Shared storage but *do* overlap
+ self.assertEqual(_find_shared_tensors({"B": B, "C": C}), [{"B", "C"}])
+
+ B = A[:2]
+ C = A[2:]
+ D = A[:1]
+ # Shared storage but *do* overlap
+ self.assertEqual(_find_shared_tensors({"B": B, "C": C, "D": D}), [{"B", "D"}, {"C"}])
+
+ def test_end_ptr(self):
+ A = torch.zeros((4,))
+ start = A.data_ptr()
+ end = _end_ptr(A)
+ self.assertEqual(end - start, 16)
+ B = torch.zeros((16,))
+ A = B[::4]
+ start = A.data_ptr()
+ end = _end_ptr(A)
+ # Jump 3 times 16 byes (the stride of B)
+ # Then add the size of the datapoint 4 bytes
+ self.assertEqual(end - start, 16 * 3 + 4)
+
+ ## FLOAT16
+ A = torch.zeros((4,), dtype=torch.float16)
+ start = A.data_ptr()
+ end = _end_ptr(A)
+ self.assertEqual(end - start, 8)
+ B = torch.zeros((16,), dtype=torch.float16)
+ A = B[::4]
+ start = A.data_ptr()
+ end = _end_ptr(A)
+ # Jump 3 times 8 bytes (the stride of B)
+ # Then add the size of the datapoint 4 bytes
+ self.assertEqual(end - start, 8 * 3 + 2)
+
def test_remove_duplicate_names(self):
A = torch.zeros((3, 3))
B = A[:1, :]
self.assertEqual(
out,
- b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
data[1, 1] = 1
self.assertEqual(
out,
- b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00',
+ b'@\x00\x00\x00\x00\x00\x00\x00{"test":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} '
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00",
)
def test_deserialization(self):
np.testing.assert_array_equal(out["test"], np.zeros((2, 2), dtype=np.int32))
def test_deserialization_metadata(self):
- serialized = b'f\x00\x00\x00\x00\x00\x00\x00{"__metadata__":{"framework":"pt"},"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
+ serialized = (
+ b'f\x00\x00\x00\x00\x00\x00\x00{"__metadata__":{"framework":"pt"},"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}}'
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ )
with tempfile.NamedTemporaryFile() as f:
f.write(serialized)
self.assertEqual(out1, out2)
self.assertEqual(
out1,
- b'\x80\x00\x00\x00\x00\x00\x00\x00{"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]},"test2":{"dtype":"F16","shape":[2,2],"data_offsets":[16,24]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ b'\x80\x00\x00\x00\x00\x00\x00\x00{"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]},"test2":{"dtype":"F16","shape":[2,2],"data_offsets":[16,24]}}'
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
self.assertEqual(out1[8:].index(b"\x00") + 8, 136)
self.assertEqual((out1[8:].index(b"\x00") + 8) % 8, 0)
out1 = save({"test1": data}, metadata={"framework": "pt"})
self.assertEqual(
out1,
- b'`\x00\x00\x00\x00\x00\x00\x00{"__metadata__":{"framework":"pt"},"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}} \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ b'`\x00\x00\x00\x00\x00\x00\x00{"__metadata__":{"framework":"pt"},"test1":{"dtype":"I32","shape":[2,2],"data_offsets":[0,16]}}'
+ b" \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
)
self.assertEqual(out1[8:].index(b"\x00") + 8, 104)
self.assertEqual((out1[8:].index(b"\x00") + 8) % 8, 0)