From 8d2126156a24d9b4045968ff88b83ed6803d7113 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Wed, 31 Jul 2024 14:30:40 +0200 Subject: [PATCH] Fixing zero-width tensor for in memory loading. (#510) --- bindings/python/py_src/safetensors/torch.py | 7 ++++++- bindings/python/tests/test_pt_comparison.py | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 9a7c4de..48532ea 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -389,7 +389,12 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]: result = {} for k, v in safeview: dtype = _getdtype(v["dtype"]) - arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"]) + if len(v["data"]) == 0: + # Workaround because frombuffer doesn't accept zero-size tensors + assert any(x == 0 for x in v["shape"]) + arr = torch.empty(v["shape"], dtype=dtype) + else: + arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"]) if sys.byteorder == "big": arr = torch.from_numpy(arr.numpy().byteswap(inplace=False)) result[k] = arr diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index c0d9703..0e53a8a 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -100,6 +100,8 @@ class TorchTestCase(unittest.TestCase): save_file(data, local) reloaded = load_file(local) self.assertTrue(torch.equal(data["test"], reloaded["test"])) + reloaded = load(open(local, "rb").read()) + self.assertTrue(torch.equal(data["test"], reloaded["test"])) def test_multiple_zero_sized(self): data = { -- 2.43.0