From a35d5e0353562e3a93cd6a53d073b531416f95eb Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Mon, 24 Apr 2023 16:15:32 +0200 Subject: [PATCH] Fixing shared detection logic. (#232) * Fixing shared tensor logic. * Fixing shared detection logic. * torch 1.10 support. * Rebase. --- bindings/python/py_src/safetensors/torch.py | 2 +- bindings/python/tests/test_pt_comparison.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 7b92052..9ac8195 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -383,7 +383,7 @@ def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]: raise ValueError(f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}") if v.layout == torch.strided: - ptrs[v.data_ptr()].add(k) + ptrs[storage_ptr(v)].add(k) failing = [] for ptr, names in ptrs.items(): diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index c68efbe..855589f 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -161,6 +161,18 @@ class SliceTestCase(unittest.TestCase): with self.assertRaises(ValueError): save_file(data, "./tests/data/out.safetensors") + def test_cannot_serialize_shared(self): + A = torch.arange(6, dtype=torch.float32).reshape((2, 3)) + B = A[:1] + data = {"A": A, "B": B} + with self.assertRaises(RuntimeError): + save_file(data, "./tests/data/out.safetensors") + + B = A[1:] + data = {"A": A, "B": B} + with self.assertRaises(RuntimeError): + save_file(data, "./tests/data/out.safetensors") + def test_deserialization_slice(self): with safe_open(self.local, framework="pt") as f: tensor = f.get_slice("test")[:, :, 1:2] -- 2.43.0