From a56b49f9a02865d09d9aec494651990e5e0eafc5 Mon Sep 17 00:00:00 2001 From: Zero Rains Date: Mon, 18 Aug 2025 18:37:11 +0800 Subject: [PATCH] Support using paddle in safe_open (#630) * support using paddle in with_open * update implementation and add device test case * update version requirement * add link * remove the name of pp * remove pp * fix the bug in Mmap when paddle < 3.1.1 --- bindings/python/src/lib.rs | 250 +++++++++++++++++- .../python/tests/test_paddle_comparison.py | 142 ++++++++++ 2 files changed, 380 insertions(+), 12 deletions(-) diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index c039d6e..f48f102 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -24,6 +24,7 @@ static NUMPY_MODULE: OnceLock> = OnceLock::new(); static TENSORFLOW_MODULE: OnceLock> = OnceLock::new(); static FLAX_MODULE: OnceLock> = OnceLock::new(); static MLX_MODULE: OnceLock> = OnceLock::new(); +static PADDLE_MODULE: OnceLock> = OnceLock::new(); struct PyView<'a> { shape: Vec, @@ -240,6 +241,7 @@ enum Framework { Tensorflow, Flax, Mlx, + Paddle, } impl fmt::Display for Framework { @@ -250,6 +252,7 @@ impl fmt::Display for Framework { Framework::Tensorflow => "tensorflow", Framework::Flax => "flax", Framework::Mlx => "mlx", + Framework::Paddle => "paddle", }) } } @@ -271,6 +274,8 @@ impl<'source> FromPyObject<'source> for Framework { "jax" => Ok(Framework::Flax), "flax" => Ok(Framework::Flax), "mlx" => Ok(Framework::Mlx), + + "paddle" => Ok(Framework::Paddle), name => Err(SafetensorError::new_err(format!( "framework {name} is invalid" ))), @@ -378,6 +383,11 @@ enum Storage { /// so Pytorch can handle the whole lifecycle. /// https://pytorch.org/docs/stable/storage.html#torch.TypedStorage.from_file. TorchStorage(OnceLock), + // Paddle specific mmap + // This allows us to not manage the lifecycle of the storage, + // Paddle can handle the whole lifecycle. + // https://www.paddlepaddle.org.cn/documentation/docs/en/develop/api/paddle/MmapStorage_en.html + PaddleStorage(OnceLock), } #[derive(Debug, PartialEq, Eq, PartialOrd)] @@ -439,8 +449,10 @@ impl Open { )) })?; let device = device.unwrap_or(Device::Cpu); - - if device != Device::Cpu && framework != Framework::Pytorch { + if device != Device::Cpu + && framework != Framework::Pytorch + && framework != Framework::Paddle + { return Err(SafetensorError::new_err(format!( "Device {device} is not supported for framework {framework}", ))); @@ -455,13 +467,16 @@ impl 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_attached(py, || module.into()) } + Framework::Paddle => { + let module = PyModule::import(py, intern!(py, "paddle"))?; + PADDLE_MODULE.get_or_init_py_attached(py, || module.into()) + } _ => { let module = PyModule::import(py, intern!(py, "numpy"))?; NUMPY_MODULE.get_or_init_py_attached(py, || module.into()) @@ -472,6 +487,43 @@ impl Open { })?; let storage = match &framework { + Framework::Paddle => Python::with_gil(|py| -> PyResult { + let paddle = get_module(py, &PADDLE_MODULE)?; + let version: String = paddle.getattr(intern!(py, "__version__"))?.extract()?; + let version = Version::from_string(&version).map_err(SafetensorError::new_err)?; + + // todo: version check, only paddle 3.1.1 or develop + if version >= Version::new(3, 1, 1) || version == Version::new(0, 0, 0) { + let py_filename: PyObject = filename + .to_str() + .ok_or_else(|| { + SafetensorError::new_err(format!( + "Path {} is not valid UTF-8", + filename.display() + )) + })? + .into_pyobject(py)? + .into(); + let size: PyObject = buffer.len().into_pyobject(py)?.into(); + let init_kargs = [ + (intern!(py, "filename"), py_filename), + (intern!(py, "nbytes"), size), + ] + .into_py_dict(py)?; + let storage = paddle + .getattr(intern!(py, "MmapStorage"))? + .call((), Some(&init_kargs))? + .into_pyobject(py)? + .into(); + let gil_storage = OnceLock::new(); + gil_storage.get_or_init_py_attached(py, || storage); + Ok(Storage::PaddleStorage(gil_storage)) + } else { + let module = PyModule::import(py, intern!(py, "numpy"))?; + NUMPY_MODULE.get_or_init_py_attached(py, || module.into()); + Ok(Storage::Mmap(buffer)) + } + })?, Framework::Pytorch => Python::with_gil(|py| -> PyResult { let module = get_module(py, &TORCH_MODULE)?; @@ -606,6 +658,92 @@ impl Open { &self.device, ) } + Storage::PaddleStorage(storage) => { + Python::with_gil(|py| -> PyResult { + let paddle = get_module(py, &PADDLE_MODULE)?; + let cur_type = if info.dtype == Dtype::U16 { + Dtype::BF16 + } else { + info.dtype + }; + let dtype: PyObject = get_pydtype(paddle, cur_type, false)?; + let paddle_uint8: PyObject = get_pydtype(paddle, Dtype::U8, false)?; + let mut shape = info.shape.to_vec(); + if cur_type == Dtype::F4 { + let n = shape.len(); + if shape[n - 1] % 2 != 0 { + return Err(SafetensorError::new_err(format!( + "f4_x2 dtype requires that the last dim be divisible by 2 in torch: got {shape:?}", + ))); + } + shape[n - 1] /= 2; + } + let shape: PyObject = shape.into_pyobject(py)?.into(); + let start = (info.data_offsets.0 + self.offset) as isize; + let stop = (info.data_offsets.1 + self.offset) as isize; + + let kwargs = [ + (intern!(py, "dtype"), paddle_uint8), + (intern!(py, "start"), start.into_pyobject(py)?.into()), + (intern!(py, "stop"), stop.into_pyobject(py)?.into()), + ] + .into_py_dict(py)?; + let sys = PyModule::import(py, intern!(py, "sys"))?; + let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?; + let storage: &PyObject = storage + .get() + .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; + let storage: &PyBound = storage.bind(py); + let storage_slice = storage + .getattr(intern!(py, "get_slice"))? + .call((), Some(&kwargs))?; + let mut tensor = storage_slice + .getattr(intern!(py, "view"))? + .call1((dtype,))?; + + if byteorder == "big" { + let inplace_kwargs = + [(intern!(py, "inplace"), PyBool::new(py, false))].into_py_dict(py)?; + + let intermediary_dtype = match cur_type { + Dtype::BF16 => Some(Dtype::F16), + Dtype::F8_E5M2 => Some(Dtype::U8), + Dtype::F8_E4M3 => Some(Dtype::U8), + Dtype::F8_E8M0 => Some(Dtype::U8), + _ => None, + }; + if let Some(intermediary_dtype) = intermediary_dtype { + // Reinterpret to f16 for numpy compatibility. + let dtype: PyObject = get_pydtype(paddle, intermediary_dtype, false)?; + tensor = tensor.getattr(intern!(py, "view"))?.call1((dtype,))?; + } + let numpy = tensor + .getattr(intern!(py, "numpy"))? + .call0()? + .getattr("byteswap")? + .call((), Some(&inplace_kwargs))?; + tensor = paddle.getattr(intern!(py, "to_tensor"))?.call1((numpy,))?; + if intermediary_dtype.is_some() { + // Reinterpret to f16 for numpy compatibility. + let dtype: PyObject = get_pydtype(paddle, cur_type, false)?; + tensor = tensor.getattr(intern!(py, "view"))?.call1((dtype,))?; + } + } + + if self.device != Device::Cpu { + let device: PyObject = if let Device::Cuda(index) = self.device { + format!("gpu:{index}").into_pyobject(py)?.into() + } else { + self.device.clone().into_pyobject(py)?.into() + }; + let kwargs = PyDict::new(py); + tensor = tensor.call_method("to", (device,), Some(&kwargs))?; + } + + let tensor = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?; + Ok(tensor.into_pyobject(py)?.into()) + }) + } Storage::TorchStorage(storage) => { Python::with_gil(|py| -> PyResult { let torch = get_module(py, &TORCH_MODULE)?; @@ -1069,6 +1207,82 @@ impl PySafeSlice { } Ok(tensor.into()) }), + Storage::PaddleStorage(storage) => Python::with_gil(|py| -> PyResult { + let paddle = get_module(py, &PADDLE_MODULE)?; + let cur_type = if self.info.dtype == Dtype::U16 { + Dtype::BF16 + } else { + self.info.dtype + }; + let dtype: PyObject = get_pydtype(paddle, cur_type, false)?; + let paddle_uint8: PyObject = get_pydtype(paddle, Dtype::U8, false)?; + let shape = self.info.shape.to_vec(); + let shape: PyObject = shape.into_pyobject(py)?.into(); + let start = (self.info.data_offsets.0 + self.offset) as isize; + let stop = (self.info.data_offsets.1 + self.offset) as isize; + let slices = slices.into_pyobject(py)?; + let storage: &PyObject = storage + .get() + .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; + let storage: &PyBound<'_, PyAny> = storage.bind(py); + let slice_kwargs = [ + (intern!(py, "dtype"), paddle_uint8), + (intern!(py, "start"), start.into_pyobject(py)?.into()), + (intern!(py, "stop"), stop.into_pyobject(py)?.into()), + ] + .into_py_dict(py)?; + let storage_slice = storage + .getattr(intern!(py, "get_slice"))? + .call((), Some(&slice_kwargs))?; + let mut tensor = storage_slice + .getattr(intern!(py, "view"))? + .call1((dtype,))?; + let sys = PyModule::import(py, intern!(py, "sys"))?; + let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?; + if byteorder == "big" { + let inplace_kwargs = + [(intern!(py, "inplace"), PyBool::new(py, false))].into_py_dict(py)?; + + let intermediary_dtype = match cur_type { + Dtype::BF16 => Some(Dtype::F16), + Dtype::F8_E5M2 => Some(Dtype::U8), + Dtype::F8_E4M3 => Some(Dtype::U8), + Dtype::F8_E8M0 => Some(Dtype::U8), + _ => None, + }; + if let Some(intermediary_dtype) = intermediary_dtype { + // Reinterpret to f16 for numpy compatibility. + let dtype: PyObject = get_pydtype(paddle, intermediary_dtype, false)?; + tensor = tensor.getattr(intern!(py, "view"))?.call1((dtype,))?; + } + let numpy = tensor + .getattr(intern!(py, "numpy"))? + .call0()? + .getattr("byteswap")? + .call((), Some(&inplace_kwargs))?; + tensor = paddle.getattr(intern!(py, "to_tensor"))?.call1((numpy,))?; + if intermediary_dtype.is_some() { + // Reinterpret to f16 for numpy compatibility. + let dtype: PyObject = get_pydtype(paddle, cur_type, false)?; + tensor = tensor.getattr(intern!(py, "view"))?.call1((dtype,))?; + } + } + tensor = tensor + .getattr(intern!(py, "reshape"))? + .call1((shape,))? + .getattr(intern!(py, "__getitem__"))? + .call1((slices,))?; + if self.device != Device::Cpu { + let device: PyObject = if let Device::Cuda(index) = self.device { + format!("gpu:{index}").into_pyobject(py)?.into() + } else { + self.device.clone().into_pyobject(py)?.into() + }; + let kwargs = PyDict::new(py); + tensor = tensor.call_method("to", (device,), Some(&kwargs))?; + } + Ok(tensor.into()) + }), } } } @@ -1113,18 +1327,13 @@ fn create_tensor<'a>( Framework::Flax => { let _ = PyModule::import(py, intern!(py, "flax")); } + Framework::Paddle => { + let _ = PyModule::import(py, intern!(py, "paddle")); + } _ => {} }; - ( - NUMPY_MODULE - .get() - .ok_or_else(|| { - SafetensorError::new_err(format!("Could not find module {framework}",)) - })? - .bind(py), - true, - ) + (get_module(py, &NUMPY_MODULE)?, true) } }; let dtype: PyObject = get_pydtype(module, dtype, is_numpy)?; @@ -1191,6 +1400,23 @@ fn create_tensor<'a>( // .getattr(intern!(py, "array"))? .call_method1("array", (tensor,))? } + Framework::Paddle => { + let module = Python::with_gil(|py| -> PyResult<&Py> { + let module = PyModule::import(py, intern!(py, "paddle"))?; + Ok(PADDLE_MODULE.get_or_init_py_attached(py, || module.into())) + })? + .bind(py); + let device: PyObject = if let Device::Cuda(index) = device { + format!("gpu:{index}").into_pyobject(py)?.into() + } else { + device.clone().into_pyobject(py)?.into() + }; + let kwargs = [(intern!(py, "place"), device)].into_py_dict(py)?; + let tensor = module + .getattr(intern!(py, "to_tensor"))? + .call((tensor,), Some(&kwargs))?; + tensor + } Framework::Pytorch => { if device != &Device::Cpu { let device: PyObject = device.clone().into_pyobject(py)?.into(); diff --git a/bindings/python/tests/test_paddle_comparison.py b/bindings/python/tests/test_paddle_comparison.py index 931486c..47ad022 100644 --- a/bindings/python/tests/test_paddle_comparison.py +++ b/bindings/python/tests/test_paddle_comparison.py @@ -2,6 +2,8 @@ import unittest import numpy as np +from safetensors import safe_open + try: import paddle @@ -45,3 +47,143 @@ class SafeTestCase(unittest.TestCase): for k, v in weights.items(): tv = paddle_weights[k] self.assertTrue(np.allclose(v, tv)) + + +@unittest.skipIf(not HAS_PADDLE, "Paddle is not available") +class WithOpenCase(unittest.TestCase): + def test_paddle_tensor_cpu(self): + A = paddle.randn((10, 5)) + tensors = { + "a": A, + } + save_file(tensors, "./tensor_paddle.safetensors") + + # Now loading cpu + with safe_open("./tensor_paddle.safetensors", framework="paddle", device="cpu") as f: + tensor = f.get_tensor("a") + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert not tensor.place.is_gpu_place() + + def test_paddle_tensor_gpu(self): + A = paddle.randn((10, 5)) + tensors = { + "a": A, + } + save_file(tensors, "./tensor_paddle.safetensors") + # Now loading gpu + with safe_open("./tensor_paddle.safetensors", framework="paddle", device="cuda") as f: + tensor = f.get_tensor("a") + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert tensor.place.is_gpu_place() + + def test_paddle_slice_cpu(self): + A = paddle.randn((10, 5)) + tensors = { + "a": A, + } + save_file(tensors, "./slice_paddle.safetensors") + + # Now loading + with safe_open("./slice_paddle.safetensors", framework="paddle", device="cpu") as f: + slice_ = f.get_slice("a") + tensor = slice_[:] + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[tuple()] + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[:2] + self.assertEqual(list(tensor.shape), [2, 5]) + assert paddle.allclose(tensor, A[:2]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[:, :2] + self.assertEqual(list(tensor.shape), [10, 2]) + assert paddle.allclose(tensor, A[:, :2]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[0, :2] + self.assertEqual(list(tensor.shape), [2]) + assert paddle.allclose(tensor, A[0, :2]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[2:, 0] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, 0]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[2:, 1] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, 1]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[2:, -1] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, -1]).item() + assert not tensor.place.is_gpu_place() + + tensor = slice_[list()] + self.assertEqual(list(tensor.shape), [0, 5]) + assert paddle.allclose(tensor, A[list()]).item() + assert not tensor.place.is_gpu_place() + + def test_paddle_slice_gpu(self): + A = paddle.randn((10, 5)) + tensors = { + "a": A, + } + save_file(tensors, "./slice_paddle.safetensors") + + # Now loading + with safe_open("./slice_paddle.safetensors", framework="paddle", device="cuda") as f: + slice_ = f.get_slice("a") + tensor = slice_[:] + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[tuple()] + self.assertEqual(list(tensor.shape), [10, 5]) + assert paddle.allclose(tensor, A).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[:2] + self.assertEqual(list(tensor.shape), [2, 5]) + assert paddle.allclose(tensor, A[:2]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[:, :2] + self.assertEqual(list(tensor.shape), [10, 2]) + assert paddle.allclose(tensor, A[:, :2]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[0, :2] + self.assertEqual(list(tensor.shape), [2]) + assert paddle.allclose(tensor, A[0, :2]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[2:, 0] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, 0]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[2:, 1] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, 1]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[2:, -1] + self.assertEqual(list(tensor.shape), [8]) + assert paddle.allclose(tensor, A[2:, -1]).item() + assert tensor.place.is_gpu_place() + + tensor = slice_[list()] + self.assertEqual(list(tensor.shape), [0, 5]) + assert paddle.allclose(tensor, A[list()]).item() + assert tensor.place.is_gpu_place() -- 2.43.0