]> khamidou — GitHub mirrors - safetensors.git/commitdiff
feat: Add filter for shared storage non overlapping tensors (#309)
authorNicolas Patry <patry.nicolas@protonmail.com>
Mon, 7 Aug 2023 07:08:02 +0000 (09:08 +0200)
committerGitHub <noreply@github.com>
Mon, 7 Aug 2023 07:08:02 +0000 (09:08 +0200)
* feat: Add filter for shared storage non overlapping tensors

Deepspeed does some tensor sharing but not actually overlapping
tensors. (It's not exactly clear why).

This PR fixes it by adding a global check for all shared tensors if the
actual offsets are overlapping or not.
It looks at all (start, stop) pointers of the tensors, sorts them by start pointer, and decides 2 tensors are disjoint if stop(previous) <= start(next)

* Style.

* Update for zero-sized tensors.

* Update test that now passes.

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

index 9c26ccd86e553334a25a7a3cb4c00ea1208d3f69..b01f393ff418cc79207fefe4316cf3e66b1f434d 100644 (file)
@@ -20,6 +20,14 @@ def storage_ptr(tensor: torch.Tensor) -> int:
             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()
@@ -33,6 +41,32 @@ def storage_size(tensor: torch.Tensor) -> int:
             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():
@@ -40,6 +74,7 @@ def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
             # 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
 
 
@@ -50,8 +85,8 @@ def _is_complete(tensor: torch.Tensor) -> bool:
 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 = []
@@ -66,7 +101,11 @@ def _remove_duplicate_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]
index d2a3878a1c09d50c124d38e2c16cc7de9577c2a4..b824341f7b5ac69818da9c68faa4b9f922d8646d 100644 (file)
@@ -43,13 +43,11 @@ class TorchTestCase(unittest.TestCase):
     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"))
@@ -69,7 +67,8 @@ class TorchTestCase(unittest.TestCase):
         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"]))
@@ -91,8 +90,8 @@ class TorchTestCase(unittest.TestCase):
             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.",
         )
 
index 45b66164df1d63e1e719632869d75226bebae214..5862528881cc1d5bed4ff0875f5c7eea98e57cfe 100644 (file)
@@ -5,6 +5,7 @@ import torch
 
 from safetensors import safe_open
 from safetensors.torch import (
+    _end_ptr,
     _find_shared_tensors,
     _is_complete,
     _remove_duplicate_names,
@@ -74,6 +75,50 @@ class TorchModelTestCase(unittest.TestCase):
         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, :]
index 07846c5efcdf583a3130f744265c577607b562b0..ae0764327e1e1b4f6c1e28549483bb31f43bd175 100644 (file)
@@ -21,7 +21,8 @@ class TestCase(unittest.TestCase):
 
         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
@@ -29,7 +30,8 @@ class TestCase(unittest.TestCase):
 
         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):
@@ -40,7 +42,10 @@ class TestCase(unittest.TestCase):
         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)
@@ -63,7 +68,8 @@ class TestCase(unittest.TestCase):
         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)
@@ -73,7 +79,8 @@ class TestCase(unittest.TestCase):
         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)