]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fixing uniform empty tensor handling (#283)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 30 Jun 2023 07:53:38 +0000 (09:53 +0200)
committerGitHub <noreply@github.com>
Fri, 30 Jun 2023 07:53:38 +0000 (09:53 +0200)
- Fixes #280

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

index f74d2a97d5e1e9cfb897f8242e8f75759b2d3164..68450a0fe7339a771ff51e4cbb783c80f24fe8d9 100644 (file)
@@ -36,7 +36,7 @@ def storage_size(tensor: torch.Tensor) -> int:
 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"):
+        if v.device != torch.device("meta") and storage_ptr(v) != 0 and storage_size(v) != 0:
             # 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()))
index 4399710efd0798118cfad63a0507265eee75cc72..fb22d288dd9fb971c392822d84b7aef041875570 100644 (file)
@@ -29,6 +29,38 @@ class TorchTestCase(unittest.TestCase):
         reloaded = load_file(local)
         self.assertTrue(torch.equal(data["test"], reloaded["test"]))
 
+    def test_multiple_zero_sized(self):
+        data = {
+            "test": torch.zeros((2, 0), dtype=torch.float),
+            "test2": torch.zeros((2, 0), dtype=torch.float),
+        }
+        local = "./tests/data/out_safe_pt_mmap_small3.safetensors"
+        save_file(data, local)
+        reloaded = load_file(local)
+        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
+        self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
+
+    def test_disjoint_tensors_shared_storage(self):
+        A = torch.zeros((10, 10))
+        data = {
+            "test": A[:, :0],
+            "test2": A[:0],
+        }
+        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))
+
+    def test_meta_tensor(self):
+        A = torch.zeros((10, 10), device=torch.device("meta"))
+        data = {
+            "test": A,
+        }
+        local = "./tests/data/out_safe_pt_mmap_small5.safetensors"
+        with self.assertRaises(RuntimeError) as ex:
+            save_file(data, local)
+        self.assertIn("Cannot copy out of meta tensor", str(ex.exception))
+
     def test_in_memory(self):
         data = {
             "test": torch.zeros((2, 2), dtype=torch.float32),