From 3dab13f0d7d461c9342bb82203b8c826ccb87f7c Mon Sep 17 00:00:00 2001 From: Thomas Wang <24695242+thomasw21@users.noreply.github.com> Date: Tue, 13 Jun 2023 18:20:19 +0200 Subject: [PATCH] Make tensor identifier a bit more robust, and transformers compatible (#264) * 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 --- .github/workflows/python.yml | 6 ++-- bindings/python/py_src/safetensors/torch.py | 18 ++++++++---- bindings/python/tests/test_pt_comparison.py | 2 +- bindings/python/tests/test_simple.py | 31 +++++++++++++++++++++ 4 files changed, 48 insertions(+), 9 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index f0f5c56..e53cb8c 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -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' diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 9ac8195..f74d2a9 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index 855589f..4399710 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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.", ) diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 23ccba4..07846c5 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -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): -- 2.43.0