From: Nicolas Patry Date: Wed, 2 Mar 2022 13:41:57 +0000 (+0100) Subject: Cleaning up Python organisation + readme + tests. X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=ab9d1e7a1d878f536cb7dd07df3e6c19aad7b3da;p=safetensors.git Cleaning up Python organisation + readme + tests. --- diff --git a/README.md b/README.md index 4b3f1fa..b06f264 100644 --- 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 diff --git a/bindings/python/README.md b/bindings/python/README.md index e69de29..1b086e1 100644 --- a/bindings/python/README.md +++ b/bindings/python/README.md @@ -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") +``` diff --git a/bindings/python/py_src/safetensors/__init__.py b/bindings/python/py_src/safetensors/__init__.py index 7574291..f102a9c 100644 --- a/bindings/python/py_src/safetensors/__init__.py +++ b/bindings/python/py_src/safetensors/__init__.py @@ -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 diff --git a/bindings/python/py_src/safetensors/numpy_functions.py b/bindings/python/py_src/safetensors/numpy.py similarity index 98% rename from bindings/python/py_src/safetensors/numpy_functions.py rename to bindings/python/py_src/safetensors/numpy.py index da2e75c..aa8eff2 100644 --- a/bindings/python/py_src/safetensors/numpy_functions.py +++ b/bindings/python/py_src/safetensors/numpy.py @@ -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 index 0000000..2dfcbe0 --- /dev/null +++ b/bindings/python/py_src/safetensors/torch.py @@ -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 index dc1d40d..0000000 --- a/bindings/python/py_src/safetensors/torch_functions.py +++ /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) diff --git a/bindings/python/tests/test_comparison.py b/bindings/python/tests/test_comparison.py index 6ac845c..a3c8651 100644 --- a/bindings/python/tests/test_comparison.py +++ b/bindings/python/tests/test_comparison.py @@ -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 diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 8ea009d..3adf447 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -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)