From f00cffa729be2fcfb869c17a697c27fc23b1f402 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Thu, 3 Nov 2022 17:04:27 +0100 Subject: [PATCH] Supporting `safe_open` for TF and Flax. (#58) * Supporting `safe_open` for TF and Flax. * Move tensors only on Pytorch. --- bindings/python/src/lib.rs | 108 ++++++++++++------ bindings/python/tests/test_flax_comparison.py | 17 ++- bindings/python/tests/test_tf_comparison.py | 14 +++ 3 files changed, 103 insertions(+), 36 deletions(-) diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 02ad17d..5a8ab72 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -33,6 +33,8 @@ type MemcpyFn = unsafe extern "C" fn( ) -> std::ffi::c_uint; static TORCH_MODULE: GILOnceCell> = GILOnceCell::new(); static NUMPY_MODULE: GILOnceCell> = GILOnceCell::new(); +static TENSORFLOW_MODULE: GILOnceCell> = GILOnceCell::new(); +static FLAX_MODULE: GILOnceCell> = GILOnceCell::new(); static CUDA_MEMCPY: GILOnceCell>> = GILOnceCell::new(); fn prepare(tensor_dict: HashMap) -> PyResult>> { @@ -192,7 +194,7 @@ enum Framework { Pytorch, Numpy, Tensorflow, - Jax, + Flax, } impl<'source> FromPyObject<'source> for Framework { @@ -200,9 +202,17 @@ impl<'source> FromPyObject<'source> for Framework { let name: String = ob.extract()?; match &name[..] { "pt" => Ok(Framework::Pytorch), + "torch" => Ok(Framework::Pytorch), + "pytorch" => Ok(Framework::Pytorch), + "np" => Ok(Framework::Numpy), + "numpy" => Ok(Framework::Numpy), + "tf" => Ok(Framework::Tensorflow), - "jax" => Ok(Framework::Jax), + "tensorflow" => Ok(Framework::Tensorflow), + + "jax" => Ok(Framework::Flax), + "flax" => Ok(Framework::Flax), name => Err(exceptions::PyException::new_err(format!( "framework {name} is invalid" ))), @@ -717,40 +727,63 @@ fn create_tensor( array: PyObject, device: &Device, ) -> PyResult { - match framework { - Framework::Pytorch | Framework::Numpy => Python::with_gil(|py| -> PyResult { - let module: &PyModule = match framework { - Framework::Numpy => NUMPY_MODULE.get(py), - Framework::Pytorch => TORCH_MODULE.get(py), - _ => unreachable!(), + Python::with_gil(|py| -> PyResult { + let module: &PyModule = match framework { + Framework::Pytorch => TORCH_MODULE.get(py), + _ => NUMPY_MODULE.get(py), + } + .ok_or_else(|| { + exceptions::PyException::new_err(format!("Could not find module {framework:?}",)) + })? + .as_ref(py); + let frombuffer = module.getattr(intern!(py, "frombuffer"))?; + let dtype: PyObject = get_pydtype(module, dtype)?; + let kwargs = [ + (intern!(py, "buffer"), array), + (intern!(py, "dtype"), dtype), + ] + .into_py_dict(py); + let tensor = frombuffer.call((), Some(kwargs))?; + let shape = shape.to_vec(); + let shape: PyObject = shape.into_py(py); + let mut tensor: &PyAny = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?; + let tensor = match framework { + Framework::Flax => { + let module = Python::with_gil(|py| -> PyResult<&Py> { + let module = PyModule::import(py, intern!(py, "jax"))?; + Ok(FLAX_MODULE.get_or_init(py, || module.into())) + })? + .as_ref(py); + module + .getattr(intern!(py, "numpy"))? + .getattr(intern!(py, "array"))? + .call1((tensor,))? } - .ok_or_else(|| { - exceptions::PyException::new_err(format!("Could not find module {framework:?}",)) - })? - .as_ref(py); - let frombuffer = module.getattr(intern!(py, "frombuffer"))?; - let dtype: PyObject = get_pydtype(module, dtype)?; - let kwargs = [ - (intern!(py, "buffer"), array), - (intern!(py, "dtype"), dtype), - ] - .into_py_dict(py); - let tensor = frombuffer.call((), Some(kwargs))?; - let shape = shape.to_vec(); - let shape: PyObject = shape.into_py(py); - let mut tensor: &PyAny = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?; - if device != &Device::Cpu { - let device: PyObject = device.clone().into_py(py); - let kwargs = PyDict::new(py); - tensor = tensor - .getattr(intern!(py, "to"))? - .call((device,), Some(kwargs))?; + Framework::Tensorflow => { + let module = Python::with_gil(|py| -> PyResult<&Py> { + let module = PyModule::import(py, intern!(py, "tensorflow"))?; + Ok(TENSORFLOW_MODULE.get_or_init(py, || module.into())) + })? + .as_ref(py); + module + .getattr(intern!(py, "convert_to_tensor"))? + .call1((tensor,))? } - let tensor = tensor.into_py(py); - Ok(tensor) - }), - framework => todo!("{framework:?}"), - } + Framework::Pytorch => { + if device != &Device::Cpu { + let device: PyObject = device.clone().into_py(py); + let kwargs = PyDict::new(py); + tensor = tensor + .getattr(intern!(py, "to"))? + .call((device,), Some(kwargs))?; + } + tensor + } + _ => tensor, + }; + let tensor = tensor.into_py(py); + Ok(tensor) + }) } fn get_pydtype(module: &PyModule, dtype: Dtype) -> PyResult { @@ -769,7 +802,12 @@ fn get_pydtype(module: &PyModule, dtype: Dtype) -> PyResult { Dtype::U8 => module.getattr(intern!(py, "uint8"))?.into(), Dtype::I8 => module.getattr(intern!(py, "int8"))?.into(), Dtype::BOOL => module.getattr(intern!(py, "bool"))?.into(), - dtype => todo!("Dtype {dtype:?}"), + dtype => { + return Err(exceptions::PyException::new_err(format!( + "Dtype not understood: {:?}", + dtype + ))) + } }; Ok(dtype) }) diff --git a/bindings/python/tests/test_flax_comparison.py b/bindings/python/tests/test_flax_comparison.py index fa0aac5..ffe867c 100644 --- a/bindings/python/tests/test_flax_comparison.py +++ b/bindings/python/tests/test_flax_comparison.py @@ -9,11 +9,12 @@ if platform.system() != "Windows": # This test will be skipped anyway. import jax.numpy as jnp from flax.serialization import msgpack_restore, msgpack_serialize + from safetensors import safe_open from safetensors.flax import load_file, save_file # Jax doesn't not exist on Windows -@unittest.skipIf(platform.system() == "Windows", "Jax is not available on Windows") +@unittest.skipIf(platform.system() == "Windows", "Flax is not available on Windows") class LoadTestCase(unittest.TestCase): def setUp(self): data = { @@ -40,3 +41,17 @@ class LoadTestCase(unittest.TestCase): for k, v in weights.items(): tv = flax_weights[k] self.assertTrue(np.allclose(v, tv)) + + def test_deserialization_safe_open(self): + weights = {} + with safe_open(self.sf_filename, framework="flax") as f: + for k in f.keys(): + weights[k] = f.get_tensor(k) + + with open(self.flax_filename, "rb") as f: + data = f.read() + flax_weights = msgpack_restore(data) + + for k, v in weights.items(): + tv = flax_weights[k] + self.assertTrue(np.allclose(v, tv)) diff --git a/bindings/python/tests/test_tf_comparison.py b/bindings/python/tests/test_tf_comparison.py index db398da..efcf3a9 100644 --- a/bindings/python/tests/test_tf_comparison.py +++ b/bindings/python/tests/test_tf_comparison.py @@ -4,6 +4,7 @@ import h5py import numpy as np import tensorflow as tf +from safetensors import safe_open from safetensors.tensorflow import load_file, save_file @@ -49,3 +50,16 @@ class SafeTestCase(unittest.TestCase): for k, v in weights.items(): tv = tf_weights[k] self.assertTrue(np.allclose(v, tv)) + + def test_deserialization_safe_open(self): + weights = {} + with safe_open(self.sf_filename, framework="tf") as f: + for k in f.keys(): + weights[k] = f.get_tensor(k) + + with h5py.File(self.tf_filename, "r") as f: + tf_weights = _load(f) + + for k, v in weights.items(): + tv = tf_weights[k] + self.assertTrue(np.allclose(v, tv)) -- 2.43.0