]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Make tensor identifier a bit more robust, and transformers compatible (#264)
authorThomas Wang <24695242+thomasw21@users.noreply.github.com>
Tue, 13 Jun 2023 16:20:19 +0000 (18:20 +0200)
committerGitHub <noreply@github.com>
Tue, 13 Jun 2023 16:20:19 +0000 (18:20 +0200)
* Make tensor identifier a bit more robust, and transformers compatible

* Prove that you need to storage storage size as well

* Lint

* Backward compatility for torch version

* Lint

* Fixing tests.

* Test supporting mutliple torch versions.

* Fixing _flatten share pointer detection.

* More code reuse.

* Better error message.

* Attempting to debug what's wrong.

* Fixing torch 1.13... God this is awful.

* Latest python ?

* Dancing with versions.

* ..

---------

Co-authored-by: Nicolas Patry <patry.nicolas@protonmail.com>
.github/workflows/python.yml
bindings/python/py_src/safetensors/torch.py
bindings/python/tests/test_pt_comparison.py
bindings/python/tests/test_simple.py

index f0f5c5657b710891fe5c3382ff301d9590acef54..e53cb8c13a3c16c228954f930bd224305907c5bb 100644 (file)
@@ -12,7 +12,7 @@ jobs:
         os: [ubuntu-latest, macos-latest, windows-latest]
         # Lowest and highest, no version specified so that 
         # new releases get automatically tested against
-        torch_version: [torch==1.10, torch]
+        version: [{torch: torch==1.10, python: "3.7"}, {torch: torch, python: "3.10"}]
     defaults:
       run:
         working-directory: ./bindings/python
@@ -34,7 +34,7 @@ jobs:
       - name: Install Python
         uses: actions/setup-python@v2
         with:
-          python-version: 3.7
+          python-version: ${{ matrix.version.python }}
           architecture: "x64"
 
       - name: Lint with RustFmt
@@ -50,7 +50,7 @@ jobs:
         run: |
           pip install -U pip
           pip install .[numpy,tensorflow,paddlepaddle]
-          pip install ${{ matrix.torch_version }}
+          pip install ${{ matrix.version.torch }}
 
       - name: Install (jax, flax)
         if: matrix.os != 'windows-latest'
index 9ac81954d383f6fb128c8c700079974df1ac8fee..f74d2a97d5e1e9cfb897f8242e8f75759b2d3164 100644 (file)
@@ -38,7 +38,7 @@ def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
     for k, v in state_dict.items():
         if v.device != torch.device("meta"):
             # Need to add device as key because of multiple GPU.
-            tensors[(storage_ptr(v), v.device)].add(k)
+            tensors[(v.device, storage_ptr(v), storage_size(v))].add(k)
     tensors = list(sorted(tensors.values()))
     return tensors
 
@@ -377,16 +377,24 @@ def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
         raise ValueError("Big endian is not supported, serialization need to be in little endian")
     if not isinstance(tensors, dict):
         raise ValueError(f"Expected a dict of [str, torch.Tensor] but received {type(tensors)}")
-    ptrs = defaultdict(set)
+
+    invalid_tensors = []
     for k, v in tensors.items():
         if not isinstance(v, torch.Tensor):
             raise ValueError(f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}")
 
-        if v.layout == torch.strided:
-            ptrs[storage_ptr(v)].add(k)
+        if v.layout != torch.strided:
+            invalid_tensors.append(k)
+    if invalid_tensors:
+        raise ValueError(
+            f"You are trying to save a sparse tensors: `{invalid_tensors}` 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."
+        )
 
+    shared_pointers = _find_shared_tensors(tensors)
     failing = []
-    for ptr, names in ptrs.items():
+    for names in shared_pointers:
         if len(names) > 1:
             failing.append(names)
 
index 855589fb1dcb0e9e2705b1a4de6276ca3d9f3cde..4399710efd0798118cfad63a0507265eee75cc72 100644 (file)
@@ -59,7 +59,7 @@ class TorchTestCase(unittest.TestCase):
             save_file(data, local)
         self.assertEqual(
             str(ctx.exception),
-            "You are trying to save a sparse tensor: `test` which this library does not support. You can make it a"
+            "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 23ccba40e17d109cf42e046d820e24c4882d3e01..07846c5efcdf583a3130f744265c577607b562b0 100644 (file)
@@ -8,8 +8,10 @@ import torch
 
 from safetensors import SafetensorError, safe_open, serialize
 from safetensors.numpy import load, load_file, save, save_file
+from safetensors.torch import _find_shared_tensors
 from safetensors.torch import load_file as load_file_pt
 from safetensors.torch import save_file as save_file_pt
+from safetensors.torch import storage_ptr, storage_size
 
 
 class TestCase(unittest.TestCase):
@@ -91,6 +93,35 @@ class TestCase(unittest.TestCase):
         load_file_pt(Path("./out.safetensors"))
         os.remove(Path("./out.safetensors"))
 
+    def test_pt_sf_save_model_overlapping_storage(self):
+        m = torch.randn(10)
+        n = torch.empty([], dtype=m.dtype, device=m.device)
+        element_size = torch.finfo(m.dtype).bits // 8
+        try:
+            smaller_storage = m.untyped_storage()[: 4 * element_size]
+        except Exception:
+            try:
+                # Fallback for torch>=1.13
+                smaller_storage = m.storage().untyped()[: 4 * element_size]
+            except Exception:
+                try:
+                    # Fallback for torch>=1.11
+                    smaller_storage = m.storage()._untyped()[: 4 * element_size]
+                except Exception:
+                    # Fallback for torch==1.10
+                    smaller_storage = m.storage()[:4]
+
+        n.set_(source=smaller_storage)
+
+        # Check that we can have tensors with storage that have the same `data_ptr` but not the same storage size
+        self.assertEqual(storage_ptr(n), storage_ptr(m))
+        self.assertNotEqual(storage_size(n), storage_size(m))
+        self.assertEqual(storage_size(n), 4 * element_size)
+        self.assertEqual(storage_size(m), 10 * element_size)
+
+        shared_tensors = _find_shared_tensors({"m": m, "n": n})
+        self.assertEqual(shared_tensors, [{"m"}, {"n"}])
+
 
 class WindowsTestCase(unittest.TestCase):
     def test_get_correctly_dropped(self):