]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Return error on out of range index (#565)
authorOliver Ford <ojford@gmail.com>
Tue, 4 Feb 2025 10:31:44 +0000 (10:31 +0000)
committerGitHub <noreply@github.com>
Tue, 4 Feb 2025 10:31:44 +0000 (11:31 +0100)
* Return error on out of range index

Fix issue #560, return a SliceOutOfRange error if the stop value
exceeds the available span.

* Improve the fix.

* Revert this change.

* Adding unit test around invalid range

* Checking for too many slices too.

* Small cleanup.

---------

Co-authored-by: Nicolas Patry <patry.nicolas@protonmail.com>
.pre-commit-config.yaml
bindings/python/src/lib.rs
bindings/python/tests/test_simple.py
flake.nix
safetensors/src/slice.rs

index 06f77d27aaeafe328b0551080c1d0f0e3f71dc55..1a28594bf50122930ff80429a2661f0924223348 100644 (file)
@@ -11,7 +11,6 @@ repos:
           [
             "--manifest-path",
             "safetensors/Cargo.toml",
-            "--all-features",
             "--all-targets",
             "--",
             "-Dwarnings",
@@ -28,7 +27,6 @@ repos:
           [
             "--manifest-path",
             "bindings/python/Cargo.toml",
-            "--all-features",
             "--all-targets",
             "--",
             "-Dwarnings",
index c9ac26c39aa911dad950fcb043b57723fda903dc..517bac3ec9cfae37b7f8863b755aaedc267e658b 100644 (file)
@@ -798,8 +798,12 @@ struct Disp(Vec<TensorIndexer>);
 impl fmt::Display for Disp {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "[")?;
-        for item in &self.0 {
-            write!(f, "{item}")?;
+        for (i, item) in self.0.iter().enumerate() {
+            if i != self.0.len() - 1 {
+                write!(f, "{item}, ")?;
+            } else {
+                write!(f, "{item}")?;
+            }
         }
         write!(f, "]")
     }
index 6930226e4801fa88707e80e3472f0277f4f53be4..8e8401388a31a6931341099c9cc1ba50ee4ae63d 100644 (file)
@@ -340,5 +340,19 @@ class ReadmeTestCase(unittest.TestCase):
                 tensor = slice_[2:, 20]
             self.assertEqual(
                 str(cm.exception),
-                "Error during slicing [2:20] with shape [10, 5]:  SliceOutOfRange { dim_index: 1, asked: 20, dim_size: 5 }",
+                "Error during slicing [2:, 20] with shape [10, 5]:  SliceOutOfRange { dim_index: 1, asked: 20, dim_size: 5 }",
+            )
+
+            with self.assertRaises(SafetensorError) as cm:
+                tensor = slice_[:20]
+            self.assertEqual(
+                str(cm.exception),
+                "Error during slicing [:20] with shape [10, 5]:  SliceOutOfRange { dim_index: 0, asked: 19, dim_size: 10 }",
+            )
+
+            with self.assertRaises(SafetensorError) as cm:
+                tensor = slice_[:, :20]
+            self.assertEqual(
+                str(cm.exception),
+                "Error during slicing [:, :20] with shape [10, 5]:  SliceOutOfRange { dim_index: 1, asked: 19, dim_size: 5 }",
             )
index d9effbaf0dd210a4ec38c7033ff07818ae9510d8..a0cba1b7cd57b6cdb0878f6bb03020b0d9bb8428 100644 (file)
--- a/flake.nix
+++ b/flake.nix
@@ -32,7 +32,7 @@
             postShellHook = ''
               unset SOURCE_DATE_EPOCH
             '';
-            LD_LIBRARY_PATH = "$LD_LIBRARY_PATH:${pkgs.stdenv.cc.cc.lib}/lib";
+            LD_LIBRARY_PATH = "$LD_LIBRARY_PATH:${pkgs.stdenv.cc.cc.lib}/lib:${pkgs.zlib}/lib";
           };
 
         }
index 910871702199edf57c471c48feba9bffb3e1988b..9f9ee8d358e6aa9938fab3a8a23e1f611a9eb852 100644 (file)
@@ -7,6 +7,7 @@ use core::ops::{
 
 /// Error representing invalid slicing attempt
 #[derive(Debug)]
+#[cfg_attr(test, derive(Eq, PartialEq))]
 pub enum InvalidSlice {
     /// When the client asked for more slices than the tensors has dimensions
     TooManySlices,
@@ -235,6 +236,7 @@ where
 
 /// Iterator used to return the bits of the overall tensor buffer
 /// when client asks for a slice of the original tensor.
+#[cfg_attr(test, derive(Debug, Eq, PartialEq))]
 pub struct SliceIterator<'data> {
     view: &'data TensorView<'data>,
     indices: Vec<(usize, usize)>,
@@ -284,10 +286,15 @@ impl<'data> SliceIterator<'data> {
                     }
                     TensorIndexer::Select(s) => (*s, *s + 1),
                 };
-                if start >= shape && stop > shape {
+                if start >= shape || stop > shape {
+                    let asked = if start >= shape {
+                        start
+                    } else {
+                        stop.saturating_sub(1)
+                    };
                     return Err(InvalidSlice::SliceOutOfRange {
                         dim_index: i,
-                        asked: stop.saturating_sub(1),
+                        asked,
                         dim_size: shape,
                     });
                 }
@@ -573,4 +580,54 @@ mod tests {
         assert_eq!(iterator.next(), Some(&data[12..16]));
         assert_eq!(iterator.next(), None);
     }
+
+    #[test]
+    fn test_invalid_range() {
+        let data: Vec<u8> = vec![0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0]
+            .into_iter()
+            .flat_map(|f| f.to_le_bytes())
+            .collect();
+
+        let attn_0 = TensorView::new(Dtype::F32, vec![2, 3], &data).unwrap();
+
+        assert_eq!(
+            SliceIterator::new(
+                &attn_0,
+                &[
+                    TensorIndexer::Select(1),
+                    TensorIndexer::Narrow(Bound::Included(1), Bound::Excluded(4)),
+                ],
+            ),
+            Err(InvalidSlice::SliceOutOfRange {
+                asked: 3,
+                dim_index: 1,
+                dim_size: 3,
+            })
+        );
+        assert_eq!(
+            SliceIterator::new(
+                &attn_0,
+                &[
+                    TensorIndexer::Select(1),
+                    TensorIndexer::Narrow(Bound::Included(3), Bound::Excluded(2)),
+                ],
+            ),
+            Err(InvalidSlice::SliceOutOfRange {
+                asked: 3,
+                dim_index: 1,
+                dim_size: 3,
+            })
+        );
+        assert_eq!(
+            SliceIterator::new(
+                &attn_0,
+                &[
+                    TensorIndexer::Select(1),
+                    TensorIndexer::Select(1),
+                    TensorIndexer::Select(1),
+                ],
+            ),
+            Err(InvalidSlice::TooManySlices)
+        );
+    }
 }