]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Torch fixes (#90)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 18 Nov 2022 13:40:12 +0000 (14:40 +0100)
committerGitHub <noreply@github.com>
Fri, 18 Nov 2022 13:40:12 +0000 (14:40 +0100)
* Fix `KeyError: torch.float64` when serializing tensors of doubles and `KeyError: BF16` when parsing.

* Fix non-working `_view2torch` because of the forgotten returns.
Added some tests.

* Test in the same style.

* Like previous style.

Co-authored-by: KOLANICH <kolan_n@mail.ru>
bindings/python/py_src/safetensors/torch.py
bindings/python/tests/test_pt.py [deleted file]
bindings/python/tests/test_pt_comparison.py

index 55814b70ac1ddb1c6c7328cd9a18a00954d6546a..69d2087fce1a9cc7c370f9790647b25dff893c8d 100644 (file)
@@ -138,12 +138,14 @@ _SIZE = {
     torch.uint8: 1,
     torch.int8: 1,
     torch.bool: 1,
+    torch.float64: 8,
 }
 
 _TYPES = {
     "F64": torch.float64,
     "F32": torch.float32,
     "F16": torch.float16,
+    "BF16": torch.bfloat16,
     "I64": torch.int64,
     # "U64": torch.uint64,
     "I32": torch.int32,
@@ -167,6 +169,8 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]:
         arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
         result[k] = arr
 
+    return result
+
 
 def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
     if tensor.layout != torch.strided:
diff --git a/bindings/python/tests/test_pt.py b/bindings/python/tests/test_pt.py
deleted file mode 100644 (file)
index 617a1e0..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-import unittest
-
-import torch
-
-from safetensors.safetensors_rust import safe_open
-from safetensors.torch import load_file, save_file
-
-
-class TorchTestCase(unittest.TestCase):
-    def test_odd_dtype(self):
-        data = {
-            "test": torch.zeros((2, 2), dtype=torch.bfloat16),
-            "test2": torch.zeros((2, 2), dtype=torch.float16),
-            "test3": torch.zeros((2, 2), dtype=torch.bool),
-        }
-        local = "./tests/data/out_safe_pt_mmap_small.safetensors"
-        save_file(data, local)
-        reloaded = load_file(local)
-        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
-        self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
-        self.assertTrue(torch.equal(data["test3"], reloaded["test3"]))
-
-    @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
-    def test_gpu(self):
-        data = {
-            "test": torch.arange(4).view((2, 2)).to("cuda:0"),
-        }
-        local = "./tests/data/out_safe_pt_mmap_small.safetensors"
-        save_file(data, local)
-        reloaded = load_file(local)
-        self.assertTrue(torch.equal(torch.arange(4).view((2, 2)), reloaded["test"]))
-
-    def test_sparse(self):
-        data = {"test": torch.sparse_coo_tensor(size=(2, 3))}
-        local = "./tests/data/out_safe_pt_sparse.safetensors"
-        with self.assertRaises(ValueError):
-            save_file(data, local)
-
-
-class SliceTestCase(unittest.TestCase):
-    def setUp(self):
-        self.tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
-        self.data = {"test": self.tensor}
-        self.local = "./tests/data/out_safe_pt_mmap_slice.safetensors"
-        # Need to copy since that call mutates the tensors to numpy
-        save_file(self.data.copy(), self.local)
-
-    def test_cannot_serialize_a_non_contiguous_tensor(self):
-        tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
-        x = tensor[:, :, 1]
-        data = {"test": x}
-        self.assertFalse(
-            x.is_contiguous(),
-        )
-        with self.assertRaises(ValueError):
-            save_file(data, "./tests/data/out.safetensors")
-
-    def test_deserialization_slice(self):
-        with safe_open(self.local, framework="pt") as f:
-            tensor = f.get_slice("test")[:, :, 1:2]
-
-        self.assertEqual(
-            tensor.numpy().tobytes(),
-            b"\x00\x00\x80?\x00\x00\x80@",
-        )
-
-        self.assertTrue(torch.equal(tensor, torch.Tensor([[[1.0], [4.0]]])))
-        self.assertTrue(torch.equal(tensor, self.tensor[:, :, 1:2]))
-
-    def test_deserialization_metadata(self):
-        with safe_open(self.local, framework="pt") as f:
-            metadata = f.metadata()
-        self.assertEqual(metadata, None)
-
-        # Save another one *with* metadata
-        tensor = torch.arange(6, dtype=torch.float32).reshape((1, 2, 3))
-        data = {"test": tensor}
-        local = "./tests/data/out_safe_pt_mmap2.safetensors"
-        # Need to copy since that call mutates the tensors to numpy
-        save_file(data, local, metadata={"Something": "more"})
-        with safe_open(local, framework="pt") as f:
-            metadata = f.metadata()
-        self.assertEqual(metadata, {"Something": "more"})
index 8a91076a2ee754e73c2a95784c722fa7d648f37b..10f3148a5f9329b1f00891972c90c2fd78c8fc78 100644 (file)
@@ -3,7 +3,7 @@ import unittest
 import torch
 
 from safetensors.safetensors_rust import safe_open
-from safetensors.torch import load_file, save_file
+from safetensors.torch import load, load_file, save, save_file
 
 
 class TorchTestCase(unittest.TestCase):
@@ -20,6 +20,18 @@ class TorchTestCase(unittest.TestCase):
         self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
         self.assertTrue(torch.equal(data["test3"], reloaded["test3"]))
 
+    def test_in_memory(self):
+        data = {
+            "test": torch.zeros((2, 2), dtype=torch.float32),
+        }
+        binary = save(data)
+        self.assertEqual(
+            binary,
+            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',
+        )
+        reloaded = load(binary)
+        self.assertTrue(torch.equal(data["test"], reloaded["test"]))
+
     @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
     def test_gpu(self):
         data = {