From: Nicolas Patry Date: Fri, 30 Jun 2023 07:53:38 +0000 (+0200) Subject: Fixing uniform empty tensor handling (#283) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=e9671260d5b0f3da2f4355cd88061bdb6c048f07;p=safetensors.git Fixing uniform empty tensor handling (#283) - Fixes #280 --- diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index f74d2a9..68450a0 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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())) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 4399710..fb22d28 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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),