From: Nicolas Patry Date: Tue, 1 Nov 2022 08:04:40 +0000 (+0100) Subject: Sharing modules. (#48) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=f7ec3c2040fea47e5164284cbddfba8efcac1618;p=safetensors.git Sharing modules. (#48) --- diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index 42b1bbc..488e376 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -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" diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 08b4608..9fb49c7 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -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> = GILOnceCell::new(); +static NUMPY_MODULE: GILOnceCell> = GILOnceCell::new(); + fn prepare(tensor_dict: HashMap) -> PyResult>> { 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 { + 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 { @@ -342,8 +363,8 @@ impl PySafeSlice { let mut offset = 0; let length = iterator.remaining_byte_len(); - let array: PyObject = Python::with_gil(|py| -> PyResult { - 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 { match framework { Framework::Pytorch | Framework::Numpy => Python::with_gil(|py| -> PyResult { - 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 = [ diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index f329dfe..68a77cf 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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)")