]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Sharing modules. (#48)
authorNicolas Patry <patry.nicolas@protonmail.com>
Tue, 1 Nov 2022 08:04:40 +0000 (09:04 +0100)
committerGitHub <noreply@github.com>
Tue, 1 Nov 2022 08:04:40 +0000 (09:04 +0100)
bindings/python/Cargo.toml
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py

index 42b1bbcb0fac8c69c019644240743cc392655831..488e376bf83d4a1c00208b44e023090fb1d6fc4c 100644 (file)
@@ -9,7 +9,7 @@ name = "safetensors_rust"
 crate-type = ["cdylib"]
 
 [dependencies]
-pyo3 = { version = "0.17.1", features = ["extension-module"] }
+pyo3 = { version = "0.17.2", features = ["extension-module"] }
 memmap = "0.7"
 serde_json = "1.0"
 
index 08b4608db558bcbdb261b2383b172f62f139b555..9fb49c794663307c7b3a9882745ac90a7a5de757 100644 (file)
@@ -2,6 +2,7 @@
 //! Dummy doc
 use memmap::{Mmap, MmapOptions};
 use pyo3::exceptions;
+use pyo3::once_cell::GILOnceCell;
 use pyo3::prelude::*;
 use pyo3::types::IntoPyDict;
 use pyo3::types::PySlice;
@@ -15,6 +16,9 @@ use std::iter::FromIterator;
 use std::ops::Bound;
 use std::sync::Arc;
 
+static TORCH_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
+static NUMPY_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
+
 fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<BTreeMap<String, TensorView<'_>>> {
     let mut tensors = BTreeMap::new();
     for (tensor_name, tensor_desc) in tensor_dict {
@@ -233,6 +237,21 @@ impl safe_open {
 
         let offset = n + 8;
 
+        Python::with_gil(|py| -> PyResult<()> {
+            match framework {
+                Framework::Pytorch => {
+                    let module = PyModule::import(py, intern!(py, "torch"))?;
+                    TORCH_MODULE.get_or_init(py, || module.into())
+                }
+                _ => {
+                    let module = PyModule::import(py, intern!(py, "numpy"))?;
+                    NUMPY_MODULE.get_or_init(py, || module.into())
+                }
+            };
+
+            Ok(())
+        })?;
+
         Ok(Self {
             metadata,
             offset,
@@ -259,15 +278,17 @@ impl safe_open {
 
         let data = &self.mmap[info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset];
 
-        let array: PyObject = Python::with_gil(|py| PyByteArray::new(py, data).into_py(py));
+        Python::with_gil(|py| -> PyResult<PyObject> {
+            let array: PyObject = PyByteArray::new(py, data).into_py(py);
 
-        create_tensor(
-            &self.framework,
-            info.dtype,
-            &info.shape,
-            array,
-            &self.device,
-        )
+            create_tensor(
+                &self.framework,
+                info.dtype,
+                &info.shape,
+                array,
+                &self.device,
+            )
+        })
     }
 
     pub fn get_slice(&self, name: &str) -> PyResult<PySafeSlice> {
@@ -342,8 +363,8 @@ impl PySafeSlice {
         let mut offset = 0;
         let length = iterator.remaining_byte_len();
 
-        let array: PyObject = Python::with_gil(|py| -> PyResult<PyObject> {
-            Ok(PyByteArray::new_with(py, length, |bytes: &mut [u8]| {
+        Python::with_gil(|py| {
+            let array: PyObject = PyByteArray::new_with(py, length, |bytes: &mut [u8]| {
                 for slice in iterator {
                     let len = slice.len();
                     bytes[offset..offset + slice.len()].copy_from_slice(slice);
@@ -351,15 +372,15 @@ impl PySafeSlice {
                 }
                 Ok(())
             })?
-            .into_py(py))
-        })?;
-        create_tensor(
-            &self.framework,
-            self.info.dtype,
-            &newshape,
-            array,
-            &self.device,
-        )
+            .into_py(py);
+            create_tensor(
+                &self.framework,
+                self.info.dtype,
+                &newshape,
+                array,
+                &self.device,
+            )
+        })
     }
 }
 
@@ -372,12 +393,15 @@ fn create_tensor(
 ) -> PyResult<PyObject> {
     match framework {
         Framework::Pytorch | Framework::Numpy => Python::with_gil(|py| -> PyResult<PyObject> {
-            let module_name = match framework {
-                Framework::Numpy => intern!(py, "numpy"),
-                Framework::Pytorch => intern!(py, "torch"),
+            let module: &PyModule = match framework {
+                Framework::Numpy => NUMPY_MODULE.get(py),
+                Framework::Pytorch => TORCH_MODULE.get(py),
                 _ => unreachable!(),
-            };
-            let module = PyModule::import(py, module_name)?;
+            }
+            .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 = [
index f329dfe462daf040f75e0d8e07dc0bc137b1eaf2..68a77cf78da57e3de7fd20aa2fadee87943a0349 100644 (file)
@@ -86,6 +86,12 @@ class SpeedTestCase(unittest.TestCase):
 
     @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
     def test_deserialization_safe_gpu(self):
+        # First time to hit disk
+        torch.load(self.filename, map_location="cuda:0")
+        start = datetime.datetime.now()
+        tweights = torch.load(self.filename, map_location="cuda:0")
+        pt_time = datetime.datetime.now() - start
+
         # First time to hit disk
         load_file(self.local, device=0)
         load_file(self.local, device="cuda:0")
@@ -94,11 +100,6 @@ class SpeedTestCase(unittest.TestCase):
         weights = load_file(self.local, device="cuda:0")
         safe_time = datetime.datetime.now() - start
 
-        # First time to hit disk
-        torch.load(self.filename, map_location="cuda:0")
-        start = datetime.datetime.now()
-        tweights = torch.load(self.filename, map_location="cuda:0")
-        pt_time = datetime.datetime.now() - start
         print()
         print(f"Deserialization (Safe - GPU) took {safe_time}")
         print(f"Deserialization (PT - GPU) took {pt_time} (Safe is {pt_time/safe_time} faster)")