From: Nicolas Patry Date: Wed, 2 Mar 2022 16:52:51 +0000 (+0100) Subject: Support and tests vs other frameworks. X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=0ea99c05e6d04fb4060dcb2a865ca01989239dab;p=safetensors.git Support and tests vs other frameworks. --- diff --git a/.gitignore b/.gitignore index 0e633d6..24a965d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ safetensors/target Cargo.lock *.bin +*.h5 +*.msgpack diff --git a/README.md b/README.md index b06f264..ee614ac 100644 --- a/README.md +++ b/README.md @@ -44,8 +44,8 @@ some tensors in it without scanning the whole file (distributed setting) ? ## Main oppositions - Pickle: Unsafe, runs arbitrary code -- H5: Slow (also now discouraged for TF/Keras) -- SavedModel: Tensorflow specific +- H5: Apparently now discouraged for TF/Keras. Seems like a great fit otherwise actually. Some classic user after free issues: https://www.cvedetails.com/vulnerability-list/vendor_id-15991/product_id-35054/Hdfgroup-Hdf5.html. On a very different level than pickle security wise. Also 210k lines of code vs ~400 lines for this lib currently. +- SavedModel: Tensorflow specific (it contains TF graph information). - 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. Layout control seems possible but not trivial as buffers have limitations [link](https://stackoverflow.com/questions/48458839/capnproto-maximum-filesize). diff --git a/bindings/python/py_src/safetensors/flax.py b/bindings/python/py_src/safetensors/flax.py new file mode 100644 index 0000000..e315d2b --- /dev/null +++ b/bindings/python/py_src/safetensors/flax.py @@ -0,0 +1,36 @@ +from safetensors import numpy +import numpy as np +from typing import Dict +import jax.numpy as jnp + + +def np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, jnp.DeviceArray]: + for k, v in numpy_dict.items(): + numpy_dict[k] = jnp.array(v) + return numpy_dict + + +def jnp2np(jnp_dict: Dict[str, jnp.DeviceArray]) -> Dict[str, np.array]: + for k, v in jnp_dict.items(): + jnp_dict[k] = np.asarray(v) + return jnp_dict + + +def save(tensors: Dict[str, jnp.DeviceArray]) -> bytes: + np_tensors = jnp2np(tensors) + return numpy.save(np_tensors) + + +def save_file(tensors: Dict[str, jnp.DeviceArray], filename: str): + np_tensors = jnp2np(tensors) + return numpy.save_file(np_tensors, filename) + + +def load(buffer: bytes) -> Dict[str, jnp.DeviceArray]: + flat = numpy.load(buffer) + return np2jnp(flat) + + +def load_file(filename: str) -> Dict[str, jnp.DeviceArray]: + flat = numpy.load_file(filename) + return np2jnp(flat) diff --git a/bindings/python/py_src/safetensors/tensorflow.py b/bindings/python/py_src/safetensors/tensorflow.py new file mode 100644 index 0000000..6970079 --- /dev/null +++ b/bindings/python/py_src/safetensors/tensorflow.py @@ -0,0 +1,36 @@ +from safetensors import numpy +import numpy as np +from typing import Dict +import tensorflow as tf + + +def np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.DeviceArray]: + for k, v in numpy_dict.items(): + numpy_dict[k] = tf.convert_to_tensor(v) + return numpy_dict + + +def tf2np(tf_dict: Dict[str, tf.DeviceArray]) -> Dict[str, np.array]: + for k, v in tf_dict.items(): + tf_dict[k] = v.numpy() + return tf_dict + + +def save(tensors: Dict[str, tf.DeviceArray]) -> bytes: + np_tensors = tf2np(tensors) + return numpy.save(np_tensors) + + +def save_file(tensors: Dict[str, tf.DeviceArray], filename: str): + np_tensors = tf2np(tensors) + return numpy.save_file(np_tensors, filename) + + +def load(buffer: bytes) -> Dict[str, tf.DeviceArray]: + flat = numpy.load(buffer) + return np2tf(flat) + + +def load_file(filename: str) -> Dict[str, tf.DeviceArray]: + flat = numpy.load_file(filename) + return np2tf(flat) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 2dfcbe0..d28dff2 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -10,16 +10,20 @@ def np2pt(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]: return numpy_dict +def pt2np(torch_dict: Dict[str, torch.Tensor]) -> Dict[str, np.array]: + for k, v in torch_dict.items(): + torch_dict[k] = v.numpy() + return torch_dict + + def save(tensors: Dict[str, torch.Tensor]) -> bytes: - for k, v in tensors.items(): - tensors[k] = v.numpy() - return numpy.save(tensors) + np_tensors = pt2np(tensors) + return numpy.save(np_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) + np_tensors = pt2np(tensors) + return numpy.save_file(np_tensors, filename) def load(buffer: bytes) -> Dict[str, torch.Tensor]: diff --git a/bindings/python/tests/data/__init__.py b/bindings/python/tests/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bindings/python/tests/test_comparison.py b/bindings/python/tests/test_comparison.py deleted file mode 100644 index a3c8651..0000000 --- a/bindings/python/tests/test_comparison.py +++ /dev/null @@ -1,96 +0,0 @@ -import unittest -from safetensors.torch import save_file, load_file, load -from huggingface_hub import hf_hub_download -import torch -import datetime -import os - - -MODEL_ID = os.getenv("MODEL_ID", "gpt2") - - -class BigTestCase(unittest.TestCase): - def test_gpt2_deserialization_safe(self): - filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") - data = torch.load(filename) - - local = "out_safe.bin" - 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) - load(serialized) - print("Deserialization (Safe) took ", datetime.datetime.now() - start) - - def test_gpt2_deserialization_safe_mmap(self): - filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") - data = torch.load(filename) - - local = "out_safe_mmap.bin" - save_file(data, local) - - start = datetime.datetime.now() - load_file(local) - print() - print("Deserialization (Safe) took ", datetime.datetime.now() - start) - - def test_gpt2_deserialization_pt(self): - filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") - - start = datetime.datetime.now() - torch.load(filename) - print() - print("Deserialization (PT) took ", datetime.datetime.now() - start) - - def test_gpt2_deserialization_flax(self): - from flax.serialization import msgpack_restore - - filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack") - start = datetime.datetime.now() - with open(filename, "rb") as f: - data = f.read() - msgpack_restore(data) - print() - print("Deserialization (flax) took ", datetime.datetime.now() - start) - - def test_gpt2_deserialization_tf(self): - import h5py - import numpy as np - - filename = hf_hub_download(MODEL_ID, filename="tf_model.h5") - start = datetime.datetime.now() - tensors = {} - - def _load(f, prefix=""): - for k in f.keys(): - if isinstance(f[k], h5py._hl.dataset.Dataset): - tensors[f"{prefix}_{k}"] = np.array(f[k]) - else: - _load(f[k], prefix=f"{prefix}_{k}") - - with h5py.File(filename, "r") as f: - _load(f) - - print() - print("Deserialization (TF) took ", datetime.datetime.now() - start) - - def test_gpt2_serialization_pt(self): - filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") - data = torch.load(filename) - - start = datetime.datetime.now() - with open("out_pt.bin", "wb") as f: - torch.save(data, f) - print("Serialization (PT) took ", datetime.datetime.now() - start) - - def test_gpt2_serialization_safe(self): - filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") - data = torch.load(filename) - start = datetime.datetime.now() - outfilename = "out_py_test.bin" - out = save_file(data, outfilename) - print("Serialization (safe) took ", datetime.datetime.now() - start) - del out diff --git a/bindings/python/tests/test_flax_comparison.py b/bindings/python/tests/test_flax_comparison.py new file mode 100644 index 0000000..a37570a --- /dev/null +++ b/bindings/python/tests/test_flax_comparison.py @@ -0,0 +1,71 @@ +import unittest +from safetensors.flax import save_file, load_file +from huggingface_hub import hf_hub_download +from flax.serialization import msgpack_restore, msgpack_serialize +import numpy as np +import jax.numpy as jnp +import datetime +import os + +MODEL_ID = os.getenv("MODEL_ID", "gpt2") + + +def _load(nested, flat, prefix=""): + for k, v in nested.items(): + if isinstance(v, dict): + _load(v, flat, prefix=f"{prefix}_{k}") + elif isinstance(v, np.ndarray): + flat[f"{prefix}_{k}"] = jnp.array(v) + + +def load(nested_np_dicts): + tensors = {} + _load(nested_np_dicts, tensors) + return tensors + + +class SafeTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack") + with open(self.filename, "rb") as f: + data = f.read() + self.data = load(msgpack_restore(data)) + self.local = "./tests/data/out_safe_flax_mmap.bin" + save_file(self.data, self.local) + + def test_deserialization_safe(self): + start = datetime.datetime.now() + load_file(self.local) + print() + print("Deserialization (Safe) took ", datetime.datetime.now() - start) + + def test_serialization_safe(self): + start = datetime.datetime.now() + outfilename = "./tests/data/out_safe.bin" + save_file(self.data, outfilename) + print() + print("Serialization (safe) took ", datetime.datetime.now() - start) + + +class FlaxTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="flax_model.msgpack") + with open(self.filename, "rb") as f: + data = f.read() + self.data = msgpack_restore(data) + + def test_deserialization_flax(self): + start = datetime.datetime.now() + with open(self.filename, "rb") as f: + data = f.read() + msgpack_restore(data) + print() + print("Deserialization (flax) took ", datetime.datetime.now() - start) + + def test_serialization_flax(self): + start = datetime.datetime.now() + serialized = msgpack_serialize(self.data) + with open("./tests/data/out_flax.msgpack", "wb") as f: + f.write(serialized) + print() + print("Serialization (flax) took ", datetime.datetime.now() - start) diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py new file mode 100644 index 0000000..71e1ae0 --- /dev/null +++ b/bindings/python/tests/test_pt_comparison.py @@ -0,0 +1,50 @@ +import unittest +from safetensors.torch import save_file, load_file, load +from huggingface_hub import hf_hub_download +import torch +import datetime +import os + + +MODEL_ID = os.getenv("MODEL_ID", "gpt2") + + +class SafeTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") + self.data = torch.load(self.filename, map_location="cpu") + print("PT keys", len(self.data.keys())) + self.local = "./tests/data/out_safe_pt_mmap.bin" + # Need to copy since that call mutates the tensors to numpy + save_file(self.data.copy(), self.local) + + def test_deserialization_safe(self): + start = datetime.datetime.now() + load_file(self.local) + print() + print("Deserialization (Safe) took ", datetime.datetime.now() - start) + + def test_serialization_safe(self): + start = datetime.datetime.now() + outfilename = "./tests/data/out_safe.bin" + save_file(self.data, outfilename) + print() + print("Serialization (safe) took ", datetime.datetime.now() - start) + + +class TorchTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="pytorch_model.bin") + self.data = torch.load(self.filename) + + def test_deserialization(self): + start = datetime.datetime.now() + torch.load(self.filename) + print() + print("Deserialization (PT) took ", datetime.datetime.now() - start) + + def test_serialization(self): + start = datetime.datetime.now() + with open("./tests/data/out_pt.bin", "wb") as f: + torch.save(self.data, f) + print("Serialization (PT) took ", datetime.datetime.now() - start) diff --git a/bindings/python/tests/test_tf_comparison.py b/bindings/python/tests/test_tf_comparison.py new file mode 100644 index 0000000..b5f7e17 --- /dev/null +++ b/bindings/python/tests/test_tf_comparison.py @@ -0,0 +1,74 @@ +import unittest +from safetensors.flax import save_file, load_file +from huggingface_hub import hf_hub_download +import datetime +import h5py +import numpy as np +import os + +MODEL_ID = os.getenv("MODEL_ID", "gpt2") + + +def _load(f, tensors, prefix=""): + for k in f.keys(): + if isinstance(f[k], h5py._hl.dataset.Dataset): + tensors[f"{prefix}_{k}"] = np.array(f[k]) + else: + tensors.update(_load(f[k], tensors, prefix=f"{prefix}_{k}")) + return tensors + + +def _save(f, tensors, prefix=""): + for name, tensor in tensors.items(): + dset = f.create_dataset(name, tensor.shape, dtype=tensor.dtype) + dset[:] = tensor + + +class SafeTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="tf_model.h5") + tensors = {} + with h5py.File(self.filename, "r") as f: + self.data = _load(f, tensors) + + print("TF keys", len(self.data.keys())) + self.local = "./tests/data/out_safe_tf_mmap.h5" + save_file(self.data, self.local) + + def test_deserialization_safe(self): + start = datetime.datetime.now() + load_file(self.local) + print() + print("Deserialization (Safe) took ", datetime.datetime.now() - start) + + def test_serialization_safe(self): + start = datetime.datetime.now() + outfilename = "./tests/data/out_safe.bin" + save_file(self.data, outfilename) + print() + print("Serialization (Safe) took ", datetime.datetime.now() - start) + + +class TFTestCase(unittest.TestCase): + def setUp(self): + self.filename = hf_hub_download(MODEL_ID, filename="tf_model.h5") + tensors = {} + with h5py.File(self.filename, "r") as f: + self.data = _load(f, tensors) + self.local = "./tests/data/out_safe_tf_mmap.bin" + save_file(self.data, self.local) + + def test_deserialization_tf(self): + start = datetime.datetime.now() + tensors = {} + with h5py.File(self.filename, "r") as f: + self.data = _load(f, tensors) + print() + print("Deserialization (TF) took ", datetime.datetime.now() - start) + + def test_serialization_tf(self): + start = datetime.datetime.now() + with h5py.File("./tests/data/out_tf_tf.h5", "w") as f: + _save(f, self.data) + print() + print("Serialization (TF) took ", datetime.datetime.now() - start)