- 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)
- 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
+## 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")
+```
__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
"U16": np.uint16,
"I8": np.int8,
"U8": np.uint8,
- "BOOL": np.bool,
+ "BOOL": bool,
}
--- /dev/null
+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)
+++ /dev/null
-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)
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
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):
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)
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()
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 = {}
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
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
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)