From: Nicolas Patry Date: Wed, 31 Jul 2024 12:30:40 +0000 (+0200) Subject: Fixing zero-width tensor for in memory loading. (#510) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=8d2126156a24d9b4045968ff88b83ed6803d7113;p=safetensors.git Fixing zero-width tensor for in memory loading. (#510) --- 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 = {