]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fixing shared detection logic. (#232)
authorNicolas Patry <patry.nicolas@protonmail.com>
Mon, 24 Apr 2023 14:15:32 +0000 (16:15 +0200)
committerGitHub <noreply@github.com>
Mon, 24 Apr 2023 14:15:32 +0000 (16:15 +0200)
* Fixing shared tensor logic.

* Fixing shared detection logic.

* torch 1.10 support.

* Rebase.

bindings/python/py_src/safetensors/torch.py
bindings/python/tests/test_pt_comparison.py

index 7b920526c3dfed49f8b19a377ebc27e280e46cf5..9ac81954d383f6fb128c8c700079974df1ac8fee 100644 (file)
@@ -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():
index c68efbe23fc2cc57e6af3fad14c890bb23190e42..855589fb1dcb0e9e2705b1a4de6276ca3d9f3cde 100644 (file)
@@ -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]