From: Oliver Ford Date: Tue, 4 Feb 2025 10:31:44 +0000 (+0000) Subject: Return error on out of range index (#565) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=fa833511664338bfc927fc02653ddb7d38d40be9;p=safetensors.git Return error on out of range index (#565) * 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 --- diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 06f77d2..1a28594 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -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", diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index c9ac26c..517bac3 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -798,8 +798,12 @@ struct Disp(Vec); 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, "]") } diff --git a/bindings/python/tests/test_simple.py b/bindings/python/tests/test_simple.py index 6930226..8e84013 100644 --- a/bindings/python/tests/test_simple.py +++ b/bindings/python/tests/test_simple.py @@ -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 }", ) diff --git a/flake.nix b/flake.nix index d9effba..a0cba1b 100644 --- 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"; }; } diff --git a/safetensors/src/slice.rs b/safetensors/src/slice.rs index 9108717..9f9ee8d 100644 --- a/safetensors/src/slice.rs +++ b/safetensors/src/slice.rs @@ -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 = 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) + ); + } }