]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Supporting `safe_open` for TF and Flax. (#58)
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 3 Nov 2022 16:04:27 +0000 (17:04 +0100)
committerGitHub <noreply@github.com>
Thu, 3 Nov 2022 16:04:27 +0000 (17:04 +0100)
* Supporting `safe_open` for TF and Flax.

* Move tensors only on Pytorch.

bindings/python/src/lib.rs
bindings/python/tests/test_flax_comparison.py
bindings/python/tests/test_tf_comparison.py

index 02ad17dab99d5524760dbf5048fab316ab662906..5a8ab7285f217a4c4b7d31b596f1268948bc1708 100644 (file)
@@ -33,6 +33,8 @@ type MemcpyFn = unsafe extern "C" fn(
 ) -> std::ffi::c_uint;
 static TORCH_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 static NUMPY_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
+static TENSORFLOW_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
+static FLAX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 static CUDA_MEMCPY: GILOnceCell<Option<Symbol<MemcpyFn>>> = GILOnceCell::new();
 
 fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<BTreeMap<String, TensorView<'_>>> {
@@ -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<PyObject> {
-    match framework {
-        Framework::Pytorch | Framework::Numpy => Python::with_gil(|py| -> PyResult<PyObject> {
-            let module: &PyModule = match framework {
-                Framework::Numpy => NUMPY_MODULE.get(py),
-                Framework::Pytorch => TORCH_MODULE.get(py),
-                _ => unreachable!(),
+    Python::with_gil(|py| -> PyResult<PyObject> {
+        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<PyModule>> {
+                    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<PyModule>> {
+                    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<PyObject> {
@@ -769,7 +802,12 @@ fn get_pydtype(module: &PyModule, dtype: Dtype) -> PyResult<PyObject> {
             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)
     })
index fa0aac5e76ecf5cb3b5867857eb4a7e427d4eddf..ffe867c4d4971807861c4f503ae1c6af377accb1 100644 (file)
@@ -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))
index db398da7259d04d21ac40d067f0c4e75862dcc35..efcf3a907e26e5330d9501ed0cf284d0e45a2a83 100644 (file)
@@ -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))