]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fix test (#590)
authorNicolas Patry <patry.nicolas@protonmail.com>
Mon, 17 Mar 2025 10:58:03 +0000 (11:58 +0100)
committerGitHub <noreply@github.com>
Mon, 17 Mar 2025 10:58:03 +0000 (11:58 +0100)
* Revert "Demoing zero-copy save. (#567)"

This reverts commit 4b3864c802d727be3cd67e5107a0f873d047ae69.

* Fixing the test and removing the PyBuffer thing.

* Remove features from bench.

.github/workflows/build_documentation.yml
.github/workflows/build_pr_documentation.yml
.github/workflows/python-bench.yml
.github/workflows/python-release.yml
.github/workflows/python.yml
Dockerfile.s390x.test
bindings/python/Cargo.toml
bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/src/view.rs [deleted file]
bindings/python/tests/test_pt_comparison.py

index a491bc1561fddb7b913eeb437dc26d78a884b7f0..8b5019424de3b8131e6118c3b5f808035c36a4b5 100644 (file)
@@ -11,8 +11,6 @@ on:
 jobs:
   build:
     uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main
-    env:
-      MATURIN_PEP517_ARGS: "--features py311,pyo3/extension-module"
     with:
       commit_sha: ${{ github.sha }}
       package: safetensors
index 81214464f0e6cbf015375c5e648e17ea070a9e2d..efafcd489da05939613146e734d8c2fa9595b033 100644 (file)
@@ -14,8 +14,6 @@ concurrency:
 jobs:
   build:
     uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main
-    env:
-      MATURIN_PEP517_ARGS: "--features py311,pyo3/extension-module"
     with:
       commit_sha: ${{ github.event.pull_request.head.sha }}
       pr_number: ${{ github.event.number }}
index cbfd62de268d05729d9cf3508636dd7fb85ccb47..862d8e03e4443eff07d5ebe7e74086f1ec9f7a86 100644 (file)
@@ -39,7 +39,7 @@ jobs:
       - name: Run tests
         working-directory: ./bindings/python
         run: |
-          cargo test --features py311
+          cargo test
           pytest --benchmark-json output.json benches/
       # Download previous benchmark result from cache (if exists)
       - name: Download previous benchmark data
index 58c8efca609820ae5753c3f219df657d92992bab..2cc9643869396d9b542af8f90ef7113904aa6343 100644 (file)
@@ -23,7 +23,6 @@ jobs:
     runs-on: ${{ matrix.platform.runner }}
     strategy:
       matrix:
-        pyfeature: ["py38", "py311"]
         platform:
           - runner: ubuntu-latest
             target: x86_64
@@ -46,20 +45,19 @@ jobs:
         uses: PyO3/maturin-action@v1
         with:
           target: ${{ matrix.platform.target }}
-          args: --release --out dist --manifest-path bindings/python/Cargo.toml --features pyo3/extension-module,${{ matrix.pyfeature }} --no-default-features
+          args: --release --out dist --manifest-path bindings/python/Cargo.toml
           sccache: 'true'
           manylinux: auto
       - name: Upload wheels
         uses: actions/upload-artifact@v4
         with:
-          name: wheels-linux-${{ matrix.platform.target }}-${{ matrix.pyfeature }}
+          name: wheels-linux-${{ matrix.platform.target }}
           path: dist
 
   musllinux:
     runs-on: ${{ matrix.platform.runner }}
     strategy:
       matrix:
-        pyfeature: ["py38", "py311"]
         platform:
           - runner: ubuntu-latest
             target: x86_64
@@ -78,20 +76,19 @@ jobs:
         uses: PyO3/maturin-action@v1
         with:
           target: ${{ matrix.platform.target }}
-          args: --release --out dist --manifest-path bindings/python/Cargo.toml --features pyo3/extension-module,${{ matrix.pyfeature }} --no-default-features
+          args: --release --out dist --manifest-path bindings/python/Cargo.toml
           sccache: 'true'
           manylinux: musllinux_1_2
       - name: Upload wheels
         uses: actions/upload-artifact@v4
         with:
-          name: wheels-musllinux-${{ matrix.platform.target }}-${{ matrix.pyfeature }}
+          name: wheels-musllinux-${{ matrix.platform.target }}
           path: dist
 
   windows:
     runs-on: ${{ matrix.platform.runner }}
     strategy:
       matrix:
-        pyfeature: ["py38", "py311"]
         platform:
           - runner: windows-latest
             target: x64
@@ -107,19 +104,18 @@ jobs:
         uses: PyO3/maturin-action@v1
         with:
           target: ${{ matrix.platform.target }}
-          args: --release --out dist --manifest-path bindings/python/Cargo.toml --features pyo3/extension-module,${{ matrix.pyfeature }} --no-default-features
+          args: --release --out dist --manifest-path bindings/python/Cargo.toml
           sccache: 'true'
       - name: Upload wheels
         uses: actions/upload-artifact@v4
         with:
-          name: wheels-windows-${{ matrix.platform.target }}-${{ matrix.pyfeature }}
+          name: wheels-windows-${{ matrix.platform.target }}
           path: dist
 
   macos:
     runs-on: ${{ matrix.platform.runner }}
     strategy:
       matrix:
-        pyfeature: ["py38", "py311"]
         platform:
           - runner: macos-13
             target: x86_64
@@ -134,12 +130,12 @@ jobs:
         uses: PyO3/maturin-action@v1
         with:
           target: ${{ matrix.platform.target }}
-          args: --release --out dist --manifest-path bindings/python/Cargo.toml --features pyo3/extension-module,${{ matrix.pyfeature }} --no-default-features
+          args: --release --out dist --manifest-path bindings/python/Cargo.toml
           sccache: 'true'
       - name: Upload wheels
         uses: actions/upload-artifact@v4
         with:
-          name: wheels-macos-${{ matrix.platform.target }}-${{ matrix.pyfeature }}
+          name: wheels-macos-${{ matrix.platform.target }}
           path: dist
 
   sdist:
index 0b9dd32fe15a385bb6674de3b16641c085284ead..9fbbf2a7313dfc578532175da82f1310da19d234 100644 (file)
@@ -7,14 +7,12 @@ jobs:
   build_and_test:
     name: Check everything builds & tests
     runs-on: ${{ matrix.os }}
-    env: 
-      MATURIN_PEP517_ARGS: "--no-default-features --features ${{ matrix.version.pyfeature }},pyo3/extension-module"
     strategy:
       matrix:
         os: [ubuntu-latest, macos-13, windows-latest]
         # Lowest and highest, no version specified so that 
         # new releases get automatically tested against
-        version: [{torch: torch==1.10, python: "3.8", pyfeature: "py38"}, {torch: torch, python: "3.12", pyfeature: "py311"}]
+        version: [{torch: torch==1.10, python: "3.8"}, {torch: torch, python: "3.12"}]
           # TODO this would include macos ARM target.
           # however jax has an illegal instruction issue
           # that exists only in CI (probably difference in instruction support).
@@ -54,14 +52,14 @@ jobs:
         run: cargo fmt -- --check
 
       - name: Lint with Clippy
-        run: | 
-          cargo clippy --features ${{ matrix.version.pyfeature }} --no-default-features -- -D warnings
+        run: cargo clippy --all-targets --all-features -- -D warnings
 
       - name: Run Audit
         run: cargo audit -D warnings
 
       - name: Install
         run: |
+          pip install -U pip
           pip install .[numpy,tensorflow]
           pip install ${{ matrix.version.torch }}
 
@@ -84,7 +82,7 @@ jobs:
 
       - name: Run tests
         run: |
-          cargo test --features ${{ matrix.version.pyfeature }} --no-default-features
+          cargo test
           pip install .[testing]
           pytest -sv tests/
 
index cb5bdba7e154021a96671424fe44c3defaac7df5..d1dc75830bc5931f655b7836bbec7b0482caba01 100644 (file)
@@ -11,7 +11,6 @@ RUN /root/miniconda3/bin/pip install -U pip pytest
 COPY . .
 SHELL ["/bin/bash", "-c"]
 WORKDIR /safetensors/bindings/python/
-ENV MATURIN_PEP517_ARGS="--features py311,pyo3/extension-module"
 RUN source /root/.cargo/env && /root/miniconda3/bin/pip install -e .
 RUN /root/miniconda3/bin/pytest -sv tests/test_pt_* tests/test_simple.py
 # RUN /root/miniconda3/bin/python -c 'from huggingface_hub import hf_hub_download; filename = hf_hub_download("roberta-base", "model.safetensors"); from safetensors.torch import load_file; weights = load_file(filename); assert weights["roberta.embeddings.position_embeddings.weight"][0][0].abs().item() > 1e-10'
index 4052b9d4e45ff1a699146cb88cc205c448d703ca..de7692bca4b516a964f835c21b8b3fa6af5b12c9 100644 (file)
@@ -9,13 +9,8 @@ rust-version = "1.74"
 name = "safetensors_rust"
 crate-type = ["cdylib"]
 
-[features]
-py38 = ["pyo3/abi3-py38"]
-py311 = ["pyo3/abi3-py311"]
-default = ["py311"]
-
 [dependencies]
-pyo3 = { version = "0.23", features = ["abi3"] }
+pyo3 = { version = "0.23", features = ["abi3", "abi3-py38"] }
 memmap2 = "0.9"
 serde_json = "1.0"
 
index f3591adee420401fb35fd4b054df5c707f7a9ddc..c3477aad384eeb56174537900cf0a264c1fc23bc 100644 (file)
@@ -128,10 +128,7 @@ def _remove_duplicate_names(
 
 
 def save_model(
-    model: torch.nn.Module,
-    filename: str,
-    metadata: Optional[Dict[str, str]] = None,
-    force_contiguous: bool = True,
+    model: torch.nn.Module, filename: str, metadata: Optional[Dict[str, str]] = None, force_contiguous: bool = True
 ):
     """
     Saves a given torch model to specified filename.
@@ -177,10 +174,7 @@ def save_model(
 
 
 def load_model(
-    model: torch.nn.Module,
-    filename: Union[str, os.PathLike],
-    strict: bool = True,
-    device: Union[str, int] = "cpu",
+    model: torch.nn.Module, filename: Union[str, os.PathLike], strict: bool = True, device: Union[str, int] = "cpu"
 ) -> Tuple[List[str], List[str]]:
     """
     Loads a given filename onto a torch model.
@@ -408,7 +402,7 @@ def _view2torch(safeview) -> Dict[str, torch.Tensor]:
     return result
 
 
-def _tobytes(tensor: torch.Tensor, name: str) -> Union[memoryview, bytes]:
+def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
     if tensor.layout != torch.strided:
         raise ValueError(
             f"You are trying to save a sparse tensor: `{name}` which this library does not support."
@@ -462,11 +456,8 @@ def _tobytes(tensor: torch.Tensor, name: str) -> Union[memoryview, bytes]:
         }
         npdtype = NPDTYPES[tensor.dtype]
         # Not in place as that would potentially modify a live running model
-        data = data.view(npdtype).byteswap(inplace=False).view(np.uint8)
-    if sys.version_info >= (3, 11):
-        return data.data
-    else:
-        return data.tobytes()
+        data = data.view(npdtype).byteswap(inplace=False)
+    return data.tobytes()
 
 
 def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
index 6a654ada88403cf2a9247de532a103ed571e82c7..a65b1aabe0dfa9943bfdd0fd03246bcc69f82edd 100644 (file)
@@ -1,7 +1,5 @@
 #![deny(missing_docs)]
 //! Dummy doc
-#[cfg(any(feature = "py38", feature = "py311"))]
-mod view;
 use memmap2::{Mmap, MmapOptions};
 use pyo3::exceptions::{PyException, PyFileNotFoundError};
 use pyo3::prelude::*;
@@ -12,14 +10,14 @@ use pyo3::Bound as PyBound;
 use pyo3::{intern, PyErr};
 use safetensors::slice::TensorIndexer;
 use safetensors::tensor::{Dtype, Metadata, SafeTensors, TensorInfo, TensorView};
+use safetensors::View;
+use std::borrow::Cow;
 use std::collections::HashMap;
 use std::fs::File;
 use std::iter::FromIterator;
 use std::ops::Bound;
 use std::path::PathBuf;
 use std::sync::Arc;
-#[cfg(any(feature = "py38", feature = "py311"))]
-use view::prepare;
 
 static TORCH_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 static NUMPY_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
@@ -27,10 +25,79 @@ static TENSORFLOW_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 static FLAX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 static MLX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
 
-#[cfg(not(any(feature = "py38", feature = "py311")))]
-compile_error!("At least one python version must be enabled, use `maturin develop` for python 3.11, `maturin develop --features py38,pyo3/extension-module --no-default-features` for python 3.8");
-#[cfg(all(feature = "py38", feature = "py311"))]
-compile_error!("Only one python version must be enabled, make sure to deactivate default features for python <3.11");
+struct PyView<'a> {
+    shape: Vec<usize>,
+    dtype: Dtype,
+    data: PyBound<'a, PyBytes>,
+    data_len: usize,
+}
+
+impl View for &PyView<'_> {
+    fn data(&self) -> std::borrow::Cow<[u8]> {
+        Cow::Borrowed(self.data.as_bytes())
+    }
+    fn shape(&self) -> &[usize] {
+        &self.shape
+    }
+    fn dtype(&self) -> Dtype {
+        self.dtype
+    }
+    fn data_len(&self) -> usize {
+        self.data_len
+    }
+}
+
+fn prepare(tensor_dict: HashMap<String, PyBound<PyDict>>) -> PyResult<HashMap<String, PyView>> {
+    let mut tensors = HashMap::with_capacity(tensor_dict.len());
+    for (tensor_name, tensor_desc) in &tensor_dict {
+        let shape: Vec<usize> = tensor_desc
+            .get_item("shape")?
+            .ok_or_else(|| SafetensorError::new_err(format!("Missing `shape` in {tensor_desc:?}")))?
+            .extract()?;
+        let pydata: PyBound<PyAny> = tensor_desc.get_item("data")?.ok_or_else(|| {
+            SafetensorError::new_err(format!("Missing `data` in {tensor_desc:?}"))
+        })?;
+        // Make sure it's extractable first.
+        let data: &[u8] = pydata.extract()?;
+        let data_len = data.len();
+        let data: PyBound<PyBytes> = pydata.extract()?;
+        let pydtype = tensor_desc.get_item("dtype")?.ok_or_else(|| {
+            SafetensorError::new_err(format!("Missing `dtype` in {tensor_desc:?}"))
+        })?;
+        let dtype: String = pydtype.extract()?;
+        let dtype = match dtype.as_ref() {
+            "bool" => Dtype::BOOL,
+            "int8" => Dtype::I8,
+            "uint8" => Dtype::U8,
+            "int16" => Dtype::I16,
+            "uint16" => Dtype::U16,
+            "int32" => Dtype::I32,
+            "uint32" => Dtype::U32,
+            "int64" => Dtype::I64,
+            "uint64" => Dtype::U64,
+            "float16" => Dtype::F16,
+            "float32" => Dtype::F32,
+            "float64" => Dtype::F64,
+            "bfloat16" => Dtype::BF16,
+            "float8_e4m3fn" => Dtype::F8_E4M3,
+            "float8_e5m2" => Dtype::F8_E5M2,
+            dtype_str => {
+                return Err(SafetensorError::new_err(format!(
+                    "dtype {dtype_str} is not covered",
+                )));
+            }
+        };
+
+        let tensor = PyView {
+            shape,
+            dtype,
+            data,
+            data_len,
+        };
+        tensors.insert(tensor_name.to_string(), tensor);
+    }
+    Ok(tensors)
+}
 
 /// Serializes raw data.
 ///
diff --git a/bindings/python/src/view.rs b/bindings/python/src/view.rs
deleted file mode 100644 (file)
index 1ce22ca..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-use crate::SafetensorError;
-#[cfg(feature = "py311")]
-use pyo3::buffer::PyBuffer;
-use pyo3::prelude::*;
-#[cfg(feature = "py38")]
-use pyo3::types::PyBytes;
-use pyo3::types::PyDict;
-use pyo3::Bound as PyBound;
-use safetensors::{Dtype, View};
-use std::borrow::Cow;
-use std::collections::HashMap;
-
-#[cfg(feature = "py38")]
-pub struct PyView<'a> {
-    shape: Vec<usize>,
-    dtype: Dtype,
-    data: PyBound<'a, PyBytes>,
-    data_len: usize,
-}
-
-#[cfg(feature = "py311")]
-pub struct PyView<'a> {
-    shape: Vec<usize>,
-    dtype: Dtype,
-    data: PyBuffer<u8>,
-    data_len: usize,
-    // Kept to keep the GIL open while we hold the buffer
-    _py: Python<'a>,
-}
-
-impl View for &PyView<'_> {
-    #[cfg(feature = "py38")]
-    fn data(&self) -> std::borrow::Cow<[u8]> {
-        Cow::Borrowed(self.data.as_bytes())
-    }
-    #[cfg(feature = "py311")]
-    fn data(&self) -> std::borrow::Cow<[u8]> {
-        // We already checked this in the Python side.
-        assert!(self.data.is_c_contiguous());
-        // XXX: Ideally we could have at least readonly tensors
-        // assert!(self.data.readonly());
-        // SAFETY:
-        // This is actually totally unsafe, PyBuffer is not immutable and could be changed from
-        // under us.
-        // This is made safer because we're still hanging to the GIL while treating
-        // this structure
-        Cow::Borrowed(unsafe {
-            std::slice::from_raw_parts(self.data.buf_ptr() as *const u8, self.data.item_count())
-        })
-    }
-    fn shape(&self) -> &[usize] {
-        &self.shape
-    }
-    fn dtype(&self) -> Dtype {
-        self.dtype
-    }
-    fn data_len(&self) -> usize {
-        self.data_len
-    }
-}
-
-pub fn prepare(tensor_dict: HashMap<String, PyBound<PyDict>>) -> PyResult<HashMap<String, PyView>> {
-    let mut tensors = HashMap::with_capacity(tensor_dict.len());
-    for (tensor_name, tensor_desc) in &tensor_dict {
-        let shape: Vec<usize> = tensor_desc
-            .get_item("shape")?
-            .ok_or_else(|| SafetensorError::new_err(format!("Missing `shape` in {tensor_desc:?}")))?
-            .extract()?;
-        let pydata: PyBound<PyAny> = tensor_desc.get_item("data")?.ok_or_else(|| {
-            SafetensorError::new_err(format!("Missing `data` in {tensor_desc:?}"))
-        })?;
-
-        let pydtype = tensor_desc.get_item("dtype")?.ok_or_else(|| {
-            SafetensorError::new_err(format!("Missing `dtype` in {tensor_desc:?}"))
-        })?;
-        let dtype: String = pydtype.extract()?;
-        let dtype = match dtype.as_ref() {
-            "bool" => Dtype::BOOL,
-            "int8" => Dtype::I8,
-            "uint8" => Dtype::U8,
-            "int16" => Dtype::I16,
-            "uint16" => Dtype::U16,
-            "int32" => Dtype::I32,
-            "uint32" => Dtype::U32,
-            "int64" => Dtype::I64,
-            "uint64" => Dtype::U64,
-            "float16" => Dtype::F16,
-            "float32" => Dtype::F32,
-            "float64" => Dtype::F64,
-            "bfloat16" => Dtype::BF16,
-            "float8_e4m3fn" => Dtype::F8_E4M3,
-            "float8_e5m2" => Dtype::F8_E5M2,
-            dtype_str => {
-                return Err(SafetensorError::new_err(format!(
-                    "dtype {dtype_str} is not covered",
-                )));
-            }
-        };
-
-        #[cfg(feature = "py311")]
-        let tensor = {
-            let data: PyBuffer<u8> = pydata.extract()?;
-            if !data.is_c_contiguous() {
-                return Err(SafetensorError::new_err("Python buffer is not contiguous"));
-            }
-            // XXX Ideally this would be true.
-            // if !data.readonly() {
-            //     return Err(SafetensorError::new_err("Python buffer is not readonly"));
-            // }
-            let data_len = data.item_count();
-            let py = pydata.py();
-            PyView {
-                shape,
-                dtype,
-                data,
-                data_len,
-                _py: py,
-            }
-        };
-
-        #[cfg(feature = "py38")]
-        let tensor = {
-            let data: &[u8] = pydata.extract()?;
-            let data_len = data.len();
-            let data: PyBound<PyBytes> = pydata.extract()?;
-            PyView {
-                shape,
-                dtype,
-                data,
-                data_len,
-            }
-        };
-
-        tensors.insert(tensor_name.to_string(), tensor);
-    }
-    Ok(tensors)
-}
index 10e8cc0565c45174a1db8c5a71336b3d39aaa147..365292956659ed248db6ecae0a0ac9af71ea0a43 100644 (file)
@@ -264,6 +264,7 @@ class LoadTestCase(unittest.TestCase):
         torch.set_default_device(torch.device("cuda:0"))
         weights = load_file(self.sf_filename)
         self.assertEqual(weights["test"].device, torch.device("cpu"))
+        torch.set_default_device(torch.device("cpu"))
 
     @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available")
     def test_deserialization_safe_gpu(self):