From 6e9c9b3d5caf24324c13d1ec23f3befef9b1c5ac Mon Sep 17 00:00:00 2001 From: Ivan Carvalho <8753214+IvanIsCoding@users.noreply.github.com> Date: Thu, 2 Jan 2025 10:20:02 -0500 Subject: [PATCH] Upgrading PyO3 to 0.23 (#543) * Update pyo3 to 0.23 and remove calls to deprecated methods * Implement IntoPyObject trait * Migrate IntoPy to IntoPyObject for Device * Remove into_py calls pt1 * Remove into_py calls pt2 * Remove into_py calls pt3 * Macos-12 is deprecated. * Clippy. * Remove codecov. --------- Co-authored-by: Nicolas Patry --- .github/workflows/python-release.yml | 2 +- .github/workflows/rust.yml | 14 +-- bindings/python/Cargo.toml | 2 +- bindings/python/src/lib.rs | 147 +++++++++++++-------------- safetensors/src/tensor.rs | 4 +- 5 files changed, 81 insertions(+), 88 deletions(-) diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml index 84da219..2cc9643 100644 --- a/.github/workflows/python-release.yml +++ b/.github/workflows/python-release.yml @@ -117,7 +117,7 @@ jobs: strategy: matrix: platform: - - runner: macos-12 + - runner: macos-13 target: x86_64 - runner: macos-14 target: aarch64 diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index fe0e680..1c81649 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -49,10 +49,10 @@ jobs: if: matrix.os == 'ubuntu-latest' run: cargo llvm-cov --release --lcov --output-path lcov.info - - name: Upload to codecov.io - if: matrix.os == 'ubuntu-latest' - uses: codecov/codecov-action@v3 - with: - token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos - working-directory: ./safetensors - fail_ci_if_error: true + # - name: Upload to codecov.io + # if: matrix.os == 'ubuntu-latest' + # uses: codecov/codecov-action@v3 + # with: + # token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos + # working-directory: ./safetensors + # fail_ci_if_error: true diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index a83f742..63ae54e 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.22", features = ["abi3", "abi3-py38"] } +pyo3 = { version = "0.23", features = ["abi3", "abi3-py38"] } memmap2 = "0.9" serde_json = "1.0" diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 5c97ecf..ecd318c 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -5,7 +5,7 @@ use pyo3::exceptions::{PyException, PyFileNotFoundError}; use pyo3::prelude::*; use pyo3::sync::GILOnceCell; use pyo3::types::IntoPyDict; -use pyo3::types::{PyByteArray, PyBytes, PyDict, PyList, PySlice}; +use pyo3::types::{PyBool, PyByteArray, PyBytes, PyDict, PyList, PySlice}; use pyo3::Bound as PyBound; use pyo3::{intern, PyErr}; use safetensors::slice::TensorIndexer; @@ -32,7 +32,7 @@ struct PyView<'a> { data_len: usize, } -impl<'a> View for &PyView<'a> { +impl View for &PyView<'_> { fn data(&self) -> std::borrow::Cow<[u8]> { Cow::Borrowed(self.data.as_bytes()) } @@ -122,7 +122,7 @@ fn serialize<'b>( let metadata_map = metadata.map(HashMap::from_iter); let out = safetensors::tensor::serialize(&tensors, &metadata_map) .map_err(|e| SafetensorError::new_err(format!("Error while serializing: {e:?}")))?; - let pybytes = PyBytes::new_bound(py, &out); + let pybytes = PyBytes::new(py, &out); Ok(pybytes) } @@ -173,10 +173,10 @@ fn deserialize(py: Python, bytes: &[u8]) -> PyResult FromPyObject<'source> for Device { } } -impl IntoPy for Device { - fn into_py(self, py: Python<'_>) -> PyObject { +impl<'py> IntoPyObject<'py> for Device { + type Target = PyAny; + type Output = pyo3::Bound<'py, Self::Target>; + type Error = std::convert::Infallible; + + fn into_pyobject(self, py: Python<'py>) -> Result { match self { - Device::Cpu => "cpu".into_py(py), - Device::Cuda(n) => format!("cuda:{n}").into_py(py), - Device::Mps => "mps".into_py(py), - Device::Npu(n) => format!("npu:{n}").into_py(py), - Device::Xpu(n) => format!("xpu:{n}").into_py(py), - Device::Xla(n) => format!("xla:{n}").into_py(py), - Device::Mlu(n) => format!("mlu:{n}").into_py(py), - Device::Anonymous(n) => n.into_py(py), + Device::Cpu => "cpu".into_pyobject(py).map(|x| x.into_any()), + Device::Cuda(n) => format!("cuda:{n}").into_pyobject(py).map(|x| x.into_any()), + Device::Mps => "mps".into_pyobject(py).map(|x| x.into_any()), + Device::Npu(n) => format!("npu:{n}").into_pyobject(py).map(|x| x.into_any()), + Device::Xpu(n) => format!("xpu:{n}").into_pyobject(py).map(|x| x.into_any()), + Device::Xla(n) => format!("xla:{n}").into_pyobject(py).map(|x| x.into_any()), + Device::Mlu(n) => format!("mlu:{n}").into_pyobject(py).map(|x| x.into_any()), + Device::Anonymous(n) => n.into_pyobject(py).map(|x| x.into_any()), } } } @@ -413,11 +417,11 @@ impl Open { Python::with_gil(|py| -> PyResult<()> { match framework { Framework::Pytorch => { - let module = PyModule::import_bound(py, intern!(py, "torch"))?; + let module = PyModule::import(py, intern!(py, "torch"))?; TORCH_MODULE.get_or_init(py, || module.into()) } _ => { - let module = PyModule::import_bound(py, intern!(py, "numpy"))?; + let module = PyModule::import(py, intern!(py, "numpy"))?; NUMPY_MODULE.get_or_init(py, || module.into()) } }; @@ -436,9 +440,9 @@ impl Open { // Same for torch.asarray which is necessary for zero-copy tensor if version >= Version::new(1, 11, 0) { // storage = torch.ByteStorage.from_file(filename, shared=False, size=size).untyped() - let py_filename: PyObject = filename.into_py(py); - let size: PyObject = buffer.len().into_py(py); - let shared: PyObject = false.into_py(py); + let py_filename: PyObject = filename.into_pyobject(py)?.into(); + let size: PyObject = buffer.len().into_pyobject(py)?.into(); + let shared: PyObject = PyBool::new(py, false).to_owned().into(); let (size_name, storage_name) = if version >= Version::new(2, 0, 0) { (intern!(py, "nbytes"), intern!(py, "UntypedStorage")) } else { @@ -446,7 +450,7 @@ impl Open { }; let kwargs = - [(intern!(py, "shared"), shared), (size_name, size)].into_py_dict_bound(py); + [(intern!(py, "shared"), shared), (size_name, size)].into_py_dict(py)?; let storage = module .getattr(storage_name)? // .getattr(intern!(py, "from_file"))? @@ -457,7 +461,7 @@ impl Open { Ok(untyped) => untyped, Err(_) => storage.getattr(intern!(py, "_untyped"))?, }; - let storage = untyped.call0()?.into_py(py); + let storage = untyped.call0()?.into_pyobject(py)?.into(); let gil_storage = GILOnceCell::new(); gil_storage.get_or_init(py, || storage); @@ -532,7 +536,7 @@ impl Open { &mmap[info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset]; let array: PyObject = - Python::with_gil(|py| PyByteArray::new_bound(py, data).into_py(py)); + Python::with_gil(|py| PyByteArray::new(py, data).into_any().into()); create_tensor( &self.framework, @@ -547,14 +551,14 @@ impl Open { let torch = get_module(py, &TORCH_MODULE)?; let dtype: PyObject = get_pydtype(torch, info.dtype, false)?; let torch_uint8: PyObject = get_pydtype(torch, Dtype::U8, false)?; - let kwargs = [(intern!(py, "dtype"), torch_uint8)].into_py_dict_bound(py); - let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let kwargs = [(intern!(py, "dtype"), torch_uint8)].into_py_dict(py)?; + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; let shape = info.shape.to_vec(); - let shape: PyObject = shape.into_py(py); + 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 slice = PySlice::new_bound(py, start, stop, 1); + let slice = PySlice::new(py, start, stop, 1); let storage: &PyObject = storage .get(py) .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; @@ -563,7 +567,7 @@ impl Open { .getattr(intern!(py, "__getitem__"))? .call1((slice,))?; - let sys = PyModule::import_bound(py, intern!(py, "sys"))?; + let sys = PyModule::import(py, intern!(py, "sys"))?; let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?; let mut tensor = torch @@ -574,7 +578,7 @@ impl Open { if byteorder == "big" { let inplace_kwargs = - [(intern!(py, "inplace"), false.into_py(py))].into_py_dict_bound(py); + [(intern!(py, "inplace"), PyBool::new(py, false))].into_py_dict(py)?; let intermediary_dtype = match info.dtype { Dtype::BF16 => Some(Dtype::F16), @@ -585,8 +589,7 @@ impl Open { if let Some(intermediary_dtype) = intermediary_dtype { // Reinterpret to f16 for numpy compatibility. let dtype: PyObject = get_pydtype(torch, intermediary_dtype, false)?; - let view_kwargs = - [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; tensor = tensor .getattr(intern!(py, "view"))? .call((), Some(&view_kwargs))?; @@ -600,8 +603,7 @@ impl Open { if intermediary_dtype.is_some() { // Reinterpret to f16 for numpy compatibility. let dtype: PyObject = get_pydtype(torch, info.dtype, false)?; - let view_kwargs = - [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; tensor = tensor .getattr(intern!(py, "view"))? .call((), Some(&view_kwargs))?; @@ -610,11 +612,11 @@ impl Open { tensor = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?; if self.device != Device::Cpu { - let device: PyObject = self.device.clone().into_py(py); - let kwargs = PyDict::new_bound(py); + let device: PyObject = self.device.clone().into_pyobject(py)?.into(); + let kwargs = PyDict::new(py); tensor = tensor.call_method("to", (device,), Some(&kwargs))?; } - Ok(tensor.into_py(py)) + Ok(tensor.into_pyobject(py)?.into()) // torch.asarray(storage[start + n : stop + n], dtype=torch.uint8).view(dtype=dtype).reshape(shape) }) } @@ -818,7 +820,7 @@ impl PySafeSlice { /// ``` pub fn get_shape(&self, py: Python) -> PyResult { let shape = self.info.shape.clone(); - let shape: PyObject = shape.into_py(py); + let shape: PyObject = shape.into_pyobject(py)?.into(); Ok(shape) } @@ -838,7 +840,7 @@ impl PySafeSlice { /// ``` pub fn get_dtype(&self, py: Python) -> PyResult { let dtype = self.info.dtype; - let dtype: PyObject = format!("{:?}", dtype).into_py(py); + let dtype: PyObject = format!("{:?}", dtype).into_pyobject(py)?.into(); Ok(dtype) } @@ -852,12 +854,7 @@ impl PySafeSlice { Slice::Slice(slice) => vec![slice], Slice::Slices(slices) => { if slices.is_empty() && is_list { - vec![SliceIndex::Slice(PySlice::new_bound( - pyslices.py(), - 0, - 0, - 0, - ))] + vec![SliceIndex::Slice(PySlice::new(pyslices.py(), 0, 0, 0))] } else if is_list { return Err(SafetensorError::new_err( "Non empty lists are not implemented", @@ -897,7 +894,7 @@ impl PySafeSlice { let length = iterator.remaining_byte_len(); Python::with_gil(|py| { let array: PyObject = - PyByteArray::new_bound_with(py, length, |bytes: &mut [u8]| { + 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); @@ -905,7 +902,8 @@ impl PySafeSlice { } Ok(()) })? - .into_py(py); + .into_any() + .into(); create_tensor( &self.framework, self.info.dtype, @@ -919,14 +917,14 @@ impl PySafeSlice { let torch = get_module(py, &TORCH_MODULE)?; let dtype: PyObject = get_pydtype(torch, self.info.dtype, false)?; let torch_uint8: PyObject = get_pydtype(torch, Dtype::U8, false)?; - let kwargs = [(intern!(py, "dtype"), torch_uint8)].into_py_dict_bound(py); - let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let kwargs = [(intern!(py, "dtype"), torch_uint8)].into_py_dict(py)?; + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; let shape = self.info.shape.to_vec(); - let shape: PyObject = shape.into_py(py); + 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 slice = PySlice::new_bound(py, start, stop, 1); + let slice = PySlice::new(py, start, stop, 1); let storage: &PyObject = storage .get(py) .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; @@ -936,9 +934,9 @@ impl PySafeSlice { .getattr(intern!(py, "__getitem__"))? .call1((slice,))?; - let slices = slices.into_py(py); + let slices = slices.into_pyobject(py)?; - let sys = PyModule::import_bound(py, intern!(py, "sys"))?; + let sys = PyModule::import(py, intern!(py, "sys"))?; let byteorder: String = sys.getattr(intern!(py, "byteorder"))?.extract()?; let mut tensor = torch @@ -950,7 +948,7 @@ impl PySafeSlice { // Important, do NOT use inplace otherwise the slice itself // is byteswapped, meaning multiple calls will fails let inplace_kwargs = - [(intern!(py, "inplace"), false.into_py(py))].into_py_dict_bound(py); + [(intern!(py, "inplace"), PyBool::new(py, false))].into_py_dict(py)?; let intermediary_dtype = match self.info.dtype { Dtype::BF16 => Some(Dtype::F16), @@ -961,7 +959,7 @@ impl PySafeSlice { if let Some(intermediary_dtype) = intermediary_dtype { // Reinterpret to f16 for numpy compatibility. let dtype: PyObject = get_pydtype(torch, intermediary_dtype, false)?; - let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; tensor = tensor .getattr(intern!(py, "view"))? .call((), Some(&view_kwargs))?; @@ -975,7 +973,7 @@ impl PySafeSlice { if intermediary_dtype.is_some() { // Reinterpret to f16 for numpy compatibility. let dtype: PyObject = get_pydtype(torch, self.info.dtype, false)?; - let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; tensor = tensor .getattr(intern!(py, "view"))? .call((), Some(&view_kwargs))?; @@ -987,11 +985,11 @@ impl PySafeSlice { .getattr(intern!(py, "__getitem__"))? .call1((slices,))?; if self.device != Device::Cpu { - let device: PyObject = self.device.clone().into_py(py); - let kwargs = PyDict::new_bound(py); + let device: PyObject = self.device.clone().into_pyobject(py)?.into(); + let kwargs = PyDict::new(py); tensor = tensor.call_method("to", (device,), Some(&kwargs))?; } - Ok(tensor.into_py(py)) + Ok(tensor.into()) }), } } @@ -1043,9 +1041,9 @@ fn create_tensor<'a>( // Torch==1.10 does not allow frombuffer on empty buffers so we create // the tensor manually. // let zeros = module.getattr(intern!(py, "zeros"))?; - let shape: PyObject = shape.clone().into_py(py); + let shape: PyObject = shape.clone().into_pyobject(py)?.into(); let args = (shape,); - let kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict_bound(py); + let kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; module.call_method("zeros", args, Some(&kwargs))? } else { // let frombuffer = module.getattr(intern!(py, "frombuffer"))?; @@ -1053,13 +1051,13 @@ fn create_tensor<'a>( (intern!(py, "buffer"), array), (intern!(py, "dtype"), dtype), ] - .into_py_dict_bound(py); + .into_py_dict(py)?; let mut tensor = module.call_method("frombuffer", (), Some(&kwargs))?; - let sys = PyModule::import_bound(py, intern!(py, "sys"))?; + 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"), false.into_py(py))].into_py_dict_bound(py); + [(intern!(py, "inplace"), PyBool::new(py, false))].into_py_dict(py)?; tensor = tensor .getattr("byteswap")? .call((), Some(&inplace_kwargs))?; @@ -1070,7 +1068,7 @@ fn create_tensor<'a>( let tensor = match framework { Framework::Flax => { let module = Python::with_gil(|py| -> PyResult<&Py> { - let module = PyModule::import_bound(py, intern!(py, "jax"))?; + let module = PyModule::import(py, intern!(py, "jax"))?; Ok(FLAX_MODULE.get_or_init(py, || module.into())) })? .bind(py); @@ -1081,7 +1079,7 @@ fn create_tensor<'a>( } Framework::Tensorflow => { let module = Python::with_gil(|py| -> PyResult<&Py> { - let module = PyModule::import_bound(py, intern!(py, "tensorflow"))?; + let module = PyModule::import(py, intern!(py, "tensorflow"))?; Ok(TENSORFLOW_MODULE.get_or_init(py, || module.into())) })? .bind(py); @@ -1091,7 +1089,7 @@ fn create_tensor<'a>( } Framework::Mlx => { let module = Python::with_gil(|py| -> PyResult<&Py> { - let module = PyModule::import_bound(py, intern!(py, "mlx"))?; + let module = PyModule::import(py, intern!(py, "mlx"))?; Ok(MLX_MODULE.get_or_init(py, || module.into())) })? .bind(py); @@ -1102,8 +1100,8 @@ fn create_tensor<'a>( } Framework::Pytorch => { if device != &Device::Cpu { - let device: PyObject = device.clone().into_py(py); - let kwargs = PyDict::new_bound(py); + let device: PyObject = device.clone().into_pyobject(py)?.into(); + let kwargs = PyDict::new(py); tensor = tensor.call_method("to", (device,), Some(&kwargs))?; } tensor @@ -1111,7 +1109,7 @@ fn create_tensor<'a>( Framework::Numpy => tensor, }; // let tensor = tensor.into_py_bound(py); - Ok(tensor.into_py(py)) + Ok(tensor.into()) }) } @@ -1141,9 +1139,7 @@ fn get_pydtype(module: &PyBound<'_, PyModule>, dtype: Dtype, is_numpy: bool) -> Dtype::I8 => module.getattr(intern!(py, "int8"))?.into(), Dtype::BOOL => { if is_numpy { - py.import_bound("builtins")? - .getattr(intern!(py, "bool"))? - .into() + py.import("builtins")?.getattr(intern!(py, "bool"))?.into() } else { module.getattr(intern!(py, "bool"))?.into() } @@ -1174,10 +1170,7 @@ fn _safetensors_rust(m: &PyBound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(serialize_file, m)?)?; m.add_function(wrap_pyfunction!(deserialize, m)?)?; m.add_class::()?; - m.add( - "SafetensorError", - m.py().get_type_bound::(), - )?; + m.add("SafetensorError", m.py().get_type::())?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; Ok(()) } diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index 2d918a5..596fa36 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -565,7 +565,7 @@ pub struct TensorView<'data> { data: &'data [u8], } -impl<'data> View for &TensorView<'data> { +impl View for &TensorView<'_> { fn dtype(&self) -> Dtype { self.dtype } @@ -583,7 +583,7 @@ impl<'data> View for &TensorView<'data> { } } -impl<'data> View for TensorView<'data> { +impl View for TensorView<'_> { fn dtype(&self) -> Dtype { self.dtype } -- 2.43.0