]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Cleaning up Python organisation + readme + tests.
authorNicolas Patry <patry.nicolas@protonmail.com>
Wed, 2 Mar 2022 13:41:57 +0000 (14:41 +0100)
committerNicolas Patry <patry.nicolas@protonmail.com>
Wed, 2 Mar 2022 13:41:57 +0000 (14:41 +0100)
README.md
bindings/python/README.md
bindings/python/py_src/safetensors/__init__.py
bindings/python/py_src/safetensors/numpy.py [moved from bindings/python/py_src/safetensors/numpy_functions.py with 98% similarity]
bindings/python/py_src/safetensors/torch.py [new file with mode: 0644]
bindings/python/py_src/safetensors/torch_functions.py [deleted file]
bindings/python/tests/test_comparison.py
bindings/python/tests/test_simple.py

index 4b3f1fa964b177acf5aa954c48ff5a99e8b2bd61..b06f2642bad05871b42c7564bcf24ff6b4da20b8 100644 (file)
--- a/README.md
+++ b/README.md
@@ -36,8 +36,8 @@ This is my very personal and probably biased view:
 - Zero-copy: Does reading the file require more memory than the original file ?
 - Lazy loading: Can I inspect the file without loading everything ? And loading only
 some tensors in it without scanning the whole file (distributed setting) ?
+- Layout control: Lazy loading, is not necessarily enough since if the information about tensors is spread out in your file, then even if the information is lazily accessible you might have to access most of your file to read the available tensors (incurring many DISK -> RAM copies). Controlling layout to keep fast access to single tensors is important.
 - No file size limit: Is there a limit to the file size ?
-- Layout control: Is the format saved in such a way that we don't need to look at the whole file when reading only 0/1 tensor in lazy mode
 - Flexibility: Can I save custom code in the format and be able to use it later with zero extra code ? (~ means we can store more than pure tensors, but no custom code)
 
 
@@ -48,7 +48,7 @@ some tensors in it without scanning the whole file (distributed setting) ?
 - SavedModel: Tensorflow specific
 - MsgPack: No layout control to enable lazy loading (important for loading specific parts in distributed setting)
 - Protobuf: Hard 2Go max file size limit
-- Cap'n'proto: Float16 support is not present [link](https://capnproto.org/language.html#built-in-types) so using a manual wrapper over a byte-buffer would be necessary + 
+- Cap'n'proto: Float16 support is not present [link](https://capnproto.org/language.html#built-in-types) so using a manual wrapper over a byte-buffer would be necessary. Layout control seems possible but not trivial as buffers have limitations [link](https://stackoverflow.com/questions/48458839/capnproto-maximum-filesize).
 
 ## Notes
 
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..1b086e13bb09c4266e7ec4d8f0c1fa046aa98935 100644 (file)
@@ -0,0 +1,44 @@
+## Installation
+
+```
+pip install safetensors
+```
+
+
+## Usage
+
+### Numpy
+
+```python
+from safetensors.numpy import save_file, load_file
+import numpy as np
+
+tensors = {
+   "a": np.zeros((2, 2)),
+   "b": np.zeros((2, 3), dtype=np.uint8)
+}
+
+save_file(tensors, "./out.bin")
+
+
+# Now loading
+loaded = load_file("./out.bin")
+```
+
+### Torch
+
+```python
+from safetensors.torch import save_file, load_file
+import torch
+
+tensors = {
+   "a": torch.zeros((2, 2)),
+   "b": torch.zeros((2, 3), dtype=torch.uint8)
+}
+
+save_file(tensors, "./out.bin")
+
+
+# Now loading
+loaded = load_file("./out.bin")
+```
index 757429188f423a0b858b31b87b397a34b77d10fd..f102a9cadfa89ce554b3b26d2b90bfba2e05273c 100644 (file)
@@ -1,5 +1 @@
 __version__ = "0.0.1"
-
-
-from .numpy_functions import save, save_pt, load_file
-from .torch_functions import save_pt, save_file_pt, load_file_pt
similarity index 98%
rename from bindings/python/py_src/safetensors/numpy_functions.py
rename to bindings/python/py_src/safetensors/numpy.py
index da2e75ce70651f11a7fbc2efb223a8bde627ca4e..aa8eff2bd43e442e9d173237f1fd132ae59d12c4 100644 (file)
@@ -25,7 +25,7 @@ TYPES = {
     "U16": np.uint16,
     "I8": np.int8,
     "U8": np.uint8,
-    "BOOL": np.bool,
+    "BOOL": bool,
 }
 
 
diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py
new file mode 100644 (file)
index 0000000..2dfcbe0
--- /dev/null
@@ -0,0 +1,32 @@
+from safetensors import numpy
+import numpy as np
+from typing import Dict
+import torch
+
+
+def np2pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
+    for k, v in numpy_dict.items():
+        numpy_dict[k] = torch.from_numpy(v)
+    return numpy_dict
+
+
+def save(tensors: Dict[str, torch.Tensor]) -> bytes:
+    for k, v in tensors.items():
+        tensors[k] = v.numpy()
+    return numpy.save(tensors)
+
+
+def save_file(tensors: Dict[str, torch.Tensor], filename: str):
+    for k, v in tensors.items():
+        tensors[k] = v.numpy()
+    return numpy.save_file(tensors, filename)
+
+
+def load(buffer: bytes) -> Dict[str, torch.Tensor]:
+    flat = numpy.load(buffer)
+    return np2pt(flat)
+
+
+def load_file(filename: str) -> Dict[str, torch.Tensor]:
+    flat = numpy.load_file(filename)
+    return np2pt(flat)
diff --git a/bindings/python/py_src/safetensors/torch_functions.py b/bindings/python/py_src/safetensors/torch_functions.py
deleted file mode 100644 (file)
index dc1d40d..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-from safetensors.numpy_functions import save, save_file, load_file, load
-import numpy as np
-from typing import Dict
-import torch
-
-
-def np2pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
-    for k, v in numpy_dict.items():
-        numpy_dict[k] = torch.from_numpy(v)
-    return numpy_dict
-
-
-def save_pt(tensors: Dict[str, torch.Tensor]) -> bytes:
-    for k, v in tensors.items():
-        tensors[k] = v.numpy()
-    return save(tensors)
-
-
-def save_file_pt(tensors: Dict[str, torch.Tensor], filename: str):
-    for k, v in tensors.items():
-        tensors[k] = v.numpy()
-    return save_file(tensors, filename)
-
-
-def load_pt(buffer: bytes) -> Dict[str, torch.Tensor]:
-    flat = load(buffer)
-    return np2pt(flat)
-
-
-def load_file_pt(filename: str) -> Dict[str, torch.Tensor]:
-    flat = load_file(filename)
-    return np2pt(flat)
index 6ac845c52a65a53ff1b1bdd645d3c7f7ddf6ab63..a3c8651c156a8491ed79003a8dba0cf2c734d6fa 100644 (file)
@@ -1,5 +1,5 @@
 import unittest
-from safetensors import save_file_pt, load_file, np2pt, load
+from safetensors.torch import save_file, load_file, load
 from huggingface_hub import hf_hub_download
 import torch
 import datetime
@@ -15,14 +15,14 @@ class BigTestCase(unittest.TestCase):
         data = torch.load(filename)
 
         local = "out_safe.bin"
-        save_file_pt(data, local)
+        save_file(data, local)
 
         start = datetime.datetime.now()
         with open(local, "rb") as f:
             serialized = f.read()
         print()
         print("Reading file took ", datetime.datetime.now() - start)
-        np2pt(load(serialized))
+        load(serialized)
         print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
     def test_gpt2_deserialization_safe_mmap(self):
@@ -30,10 +30,10 @@ class BigTestCase(unittest.TestCase):
         data = torch.load(filename)
 
         local = "out_safe_mmap.bin"
-        save_file_pt(data, local)
+        save_file(data, local)
 
         start = datetime.datetime.now()
-        np2pt(load_file(local))
+        load_file(local)
         print()
         print("Deserialization (Safe) took ", datetime.datetime.now() - start)
 
@@ -48,7 +48,7 @@ class BigTestCase(unittest.TestCase):
     def test_gpt2_deserialization_flax(self):
         from flax.serialization import msgpack_restore
 
-        filename = "/home/nicolas/src/gpt2/flax_model.msgpack"
+        filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack")
         start = datetime.datetime.now()
         with open(filename, "rb") as f:
             data = f.read()
@@ -60,7 +60,7 @@ class BigTestCase(unittest.TestCase):
         import h5py
         import numpy as np
 
-        filename = "/home/nicolas/src/gpt2/tf_model.h5"
+        filename = hf_hub_download(MODEL_ID, filename="tf_model.h5")
         start = datetime.datetime.now()
         tensors = {}
 
@@ -91,6 +91,6 @@ class BigTestCase(unittest.TestCase):
         data = torch.load(filename)
         start = datetime.datetime.now()
         outfilename = "out_py_test.bin"
-        out = save_file_pt(data, outfilename)
+        out = save_file(data, outfilename)
         print("Serialization (safe) took ", datetime.datetime.now() - start)
         del out
index 8ea009d726dd15e5960155d0fc7b855b3532daa0..3adf447b77d8d22175f0da4ff1f4d73561704447 100644 (file)
@@ -1,5 +1,6 @@
 import unittest
-from safetensors import save, load, load_pt, save_pt
+from safetensors.numpy import save, load, save_file, load_file
+from safetensors.torch import load_file as load_file_pt, save_file as save_file_pt
 import numpy as np
 from huggingface_hub import hf_hub_download
 import torch
@@ -30,3 +31,37 @@ class TestCase(unittest.TestCase):
         out = load(serialized)
         self.assertEqual(list(out.keys()), ["test"])
         np.testing.assert_array_equal(out["test"], np.zeros((2, 2), dtype=np.int32))
+
+
+class ReadmeTestCase(unittest.TestCase):
+    def assertTensorEqual(self, tensors1, tensors2, equality_fn):
+        self.assertEqual(tensors1.keys(), tensors2.keys(), "tensor keys don't match")
+
+        for k, v1 in tensors1.items():
+            v2 = tensors2[k]
+
+            self.assertTrue(equality_fn(v1, v2), f"{k} tensors are different")
+
+    def test_numpy_example(self):
+        tensors = {"a": np.zeros((2, 2)), "b": np.zeros((2, 3), dtype=np.uint8)}
+
+        save_file(tensors, "./out.bin")
+
+        # Now loading
+        loaded = load_file("./out.bin")
+        self.assertTensorEqual(tensors, loaded, np.allclose)
+
+    def test_torch_example(self):
+        tensors = {
+            "a": torch.zeros((2, 2)),
+            "b": torch.zeros((2, 3), dtype=torch.uint8),
+        }
+        # Saving modifies the tensors to type numpy, so we must copy for the
+        # test to be correct.
+        tensors2 = tensors.copy()
+
+        save_file_pt(tensors, "./out.bin")
+
+        # Now loading
+        loaded = load_file_pt("./out.bin")
+        self.assertTensorEqual(tensors2, loaded, torch.allclose)