From: Árpád Goretity  Date: Sun, 15 Jun 2025 09:11:36 +0000 (+0200) Subject: Better error handling through improved `Display` and `Error` impls (#616) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=30122417236e0deafa35001bc8f92dbd34c18c77;p=safetensors.git Better error handling through improved `Display` and `Error` impls (#616) * Better error handling: reliable `Display` impls and more useful `Error` impls * Reliable `Display` impls and improved error formatting in Python bindings * Remove some remaining instances of unwarranted `{:?}` formtting --------- Co-authored-by: Nicolas Patry --- diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 2765dc0..28c9512 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -49,20 +49,20 @@ impl View for &PyView<'_> { fn prepare(tensor_dict: HashMap>) -> PyResult> { let mut tensors = HashMap::with_capacity(tensor_dict.len()); - for (tensor_name, tensor_desc) in &tensor_dict { + for (tensor_name, tensor_desc) in tensor_dict { let shape: Vec = tensor_desc .get_item("shape")? - .ok_or_else(|| SafetensorError::new_err(format!("Missing `shape` in {tensor_desc:?}")))? + .ok_or_else(|| SafetensorError::new_err(format!("Missing `shape` in {tensor_desc}")))? .extract()?; let pydata: PyBound = tensor_desc.get_item("data")?.ok_or_else(|| { - SafetensorError::new_err(format!("Missing `data` in {tensor_desc:?}")) + 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 = pydata.extract()?; let pydtype = tensor_desc.get_item("dtype")?.ok_or_else(|| { - SafetensorError::new_err(format!("Missing `dtype` in {tensor_desc:?}")) + SafetensorError::new_err(format!("Missing `dtype` in {tensor_desc}")) })?; let dtype: String = pydtype.extract()?; let dtype = match dtype.as_ref() { @@ -94,7 +94,7 @@ fn prepare(tensor_dict: HashMap>) -> PyResult( ) -> PyResult> { let tensors = prepare(tensor_dict)?; let out = safetensors::tensor::serialize(&tensors, &metadata) - .map_err(|e| SafetensorError::new_err(format!("Error while serializing: {e:?}")))?; + .map_err(|e| SafetensorError::new_err(format!("Error while serializing: {e}")))?; let pybytes = PyBytes::new(py, &out); Ok(pybytes) } @@ -147,8 +147,10 @@ fn serialize_file( metadata: Option>, ) -> PyResult<()> { let tensors = prepare(tensor_dict)?; + safetensors::tensor::serialize_to_file(&tensors, &metadata, filename.as_path()) - .map_err(|e| SafetensorError::new_err(format!("Error while serializing: {e:?}")))?; + .map_err(|e| SafetensorError::new_err(format!("Error while serializing: {e}")))?; + Ok(()) } @@ -166,14 +168,14 @@ fn serialize_file( #[pyo3(signature = (bytes))] fn deserialize(py: Python, bytes: &[u8]) -> PyResult)>> { let safetensor = SafeTensors::deserialize(bytes) - .map_err(|e| SafetensorError::new_err(format!("Error while deserializing: {e:?}")))?; + .map_err(|e| SafetensorError::new_err(format!("Error while deserializing: {e}")))?; let tensors = safetensor.tensors(); let mut items = Vec::with_capacity(tensors.len()); for (tensor_name, tensor) in tensors { let pyshape: PyObject = PyList::new(py, tensor.shape().iter())?.into(); - let pydtype: PyObject = format!("{:?}", tensor.dtype()).into_pyobject(py)?.into(); + let pydtype: PyObject = tensor.dtype().to_string().into_pyobject(py)?.into(); let pydata: PyObject = PyByteArray::new(py, tensor.data()).into(); @@ -233,6 +235,18 @@ enum Framework { Mlx, } +impl fmt::Display for Framework { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match *self { + Framework::Pytorch => "pytorch", + Framework::Numpy => "numpy", + Framework::Tensorflow => "tensorflow", + Framework::Flax => "flax", + Framework::Mlx => "mlx", + }) + } +} + impl<'source> FromPyObject<'source> for Framework { fn extract_bound(ob: &PyBound<'source, PyAny>) -> PyResult { let name: String = ob.extract()?; @@ -272,12 +286,28 @@ enum Device { Anonymous(usize), } + +impl fmt::Display for Device { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Device::Cpu => write!(f, "cpu"), + Device::Mps => write!(f, "mps"), + Device::Cuda(index) => write!(f, "cuda:{index}"), + Device::Npu(index) => write!(f, "npu:{index}"), + Device::Xpu(index) => write!(f, "xpu:{index}"), + Device::Xla(index) => write!(f, "xla:{index}"), + Device::Mlu(index) => write!(f, "mlu:{index}"), + Device::Hpu(index) => write!(f, "hpu:{index}"), + Device::Anonymous(index) => write!(f, "{index}"), + } + } +} + /// Parsing the device index. fn parse_device(name: &str) -> PyResult { let tokens: Vec<_> = name.split(':').collect(); - if tokens.len() == 2 { - let device: usize = tokens[1].parse()?; - Ok(device) + if let Ok([_, token]) = <[_; 2]>::try_from(tokens) { + Ok(token.parse()?) } else { Err(SafetensorError::new_err(format!( "device {name} is invalid" @@ -288,7 +318,7 @@ fn parse_device(name: &str) -> PyResult { impl<'source> FromPyObject<'source> for Device { fn extract_bound(ob: &PyBound<'source, PyAny>) -> PyResult { if let Ok(name) = ob.extract::() { - match &name[..] { + match name.as_str() { "cpu" => Ok(Device::Cpu), "cuda" => Ok(Device::Cuda(0)), "mps" => Ok(Device::Mps), @@ -321,17 +351,7 @@ impl<'py> IntoPyObject<'py> for Device { type Error = std::convert::Infallible; fn into_pyobject(self, py: Python<'py>) -> Result { - match self { - 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::Hpu(n) => format!("hpu:{n}").into_pyobject(py).map(|x| x.into_any()), - Device::Anonymous(n) => n.into_pyobject(py).map(|x| x.into_any()), - } + self.to_string().into_pyobject(py).map(pyo3::BoundObject::into_any) } } @@ -397,13 +417,13 @@ struct Open { impl Open { fn new(filename: PathBuf, framework: Framework, device: Option) -> PyResult { let file = File::open(&filename).map_err(|_| { - PyFileNotFoundError::new_err(format!("No such file or directory: {filename:?}")) + PyFileNotFoundError::new_err(format!("No such file or directory: {}", filename.display())) })?; let device = device.unwrap_or(Device::Cpu); if device != Device::Cpu && framework != Framework::Pytorch { return Err(SafetensorError::new_err(format!( - "Device {device:?} is not support for framework {framework:?}", + "Device {device} is not supported for framework {framework}", ))); } @@ -412,7 +432,7 @@ impl Open { let buffer = unsafe { MmapOptions::new().map_copy_read_only(&file)? }; let (n, metadata) = SafeTensors::read_metadata(&buffer).map_err(|e| { - SafetensorError::new_err(format!("Error while deserializing header: {e:?}")) + SafetensorError::new_err(format!("Error while deserializing header: {e}")) })?; let offset = n + 8; @@ -446,7 +466,7 @@ impl Open { let py_filename: PyObject = filename .to_str() .ok_or_else(|| { - SafetensorError::new_err(format!("Path {filename:?} is not a string")) + SafetensorError::new_err(format!("Path {} is not valid UTF-8", filename.display())) })? .into_pyobject(py)? .into(); @@ -519,8 +539,7 @@ impl Open { /// (`List[str]`): /// The name of the tensors contained in that file pub fn offset_keys(&self) -> PyResult> { - let keys: Vec = self.metadata.offset_keys(); - Ok(keys) + Ok(self.metadata.offset_keys()) } /// Returns a full tensor @@ -823,11 +842,7 @@ impl fmt::Display for Disp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[")?; for (i, item) in self.0.iter().enumerate() { - if i != self.0.len() - 1 { - write!(f, "{item}, ")?; - } else { - write!(f, "{item}")?; - } + write!(f, "{prefix}{item}", prefix = if i == 0 { "" } else { ", " })?; } write!(f, "]") } @@ -872,9 +887,7 @@ impl PySafeSlice { /// dtype = tslice.get_dtype() # "F32" /// ``` pub fn get_dtype(&self, py: Python) -> PyResult { - let dtype = self.info.dtype; - let dtype: PyObject = format!("{:?}", dtype).into_pyobject(py)?.into(); - Ok(dtype) + Ok(self.info.dtype.to_string().into_pyobject(py)?.into()) } pub fn __getitem__(&self, slices: &PyBound<'_, PyAny>) -> PyResult { @@ -904,7 +917,7 @@ impl PySafeSlice { let tensor = TensorView::new(self.info.dtype, self.info.shape.clone(), data) .map_err(|e| { - SafetensorError::new_err(format!("Error preparing tensor view: {e:?}")) + SafetensorError::new_err(format!("Error preparing tensor view: {e}")) })?; let slices: Vec = slices .into_iter() @@ -915,10 +928,9 @@ impl PySafeSlice { let iterator = tensor.sliced_data(&slices).map_err(|e| { SafetensorError::new_err(format!( - "Error during slicing {} with shape {:?}: {:?}", + "Error during slicing {} with shape {:?}: {e}", Disp(slices), self.info.shape, - e )) })?; let newshape = iterator.newshape(); @@ -1052,7 +1064,7 @@ fn create_tensor<'a>( TORCH_MODULE .get() .ok_or_else(|| { - SafetensorError::new_err(format!("Could not find module {framework:?}",)) + SafetensorError::new_err(format!("Could not find module {framework}",)) })? .bind(py), false, @@ -1076,7 +1088,7 @@ fn create_tensor<'a>( .get() .ok_or_else(|| { SafetensorError::new_err( - format!("Could not find module {framework:?}",), + format!("Could not find module {framework}",), ) })? .bind(py), @@ -1198,7 +1210,7 @@ fn get_pydtype(module: &PyBound<'_, PyModule>, dtype: Dtype, is_numpy: bool) -> Dtype::F8_E5M2 => module.getattr(intern!(py, "float8_e5m2"))?.into(), dtype => { return Err(SafetensorError::new_err(format!( - "Dtype not understood: {dtype:?}" + "Dtype not understood: {dtype}" ))) } }; diff --git a/safetensors/src/slice.rs b/safetensors/src/slice.rs index 9f9ee8d..485f082 100644 --- a/safetensors/src/slice.rs +++ b/safetensors/src/slice.rs @@ -1,9 +1,10 @@ //! Module handling lazy loading via iterating on slices on the original buffer. -use crate::lib::{String, ToString, Vec}; +use crate::lib::Vec; use crate::tensor::TensorView; use core::ops::{ Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }; +use core::fmt::Display; /// Error representing invalid slicing attempt #[derive(Debug)] @@ -22,6 +23,25 @@ pub enum InvalidSlice { }, } +impl Display for InvalidSlice { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match *self { + InvalidSlice::TooManySlices => { + write!(f, "more slicing indexes than dimensions in tensor") + } + InvalidSlice::SliceOutOfRange { dim_index, asked, dim_size } => { + write!(f, "index {asked} out of bounds for tensor dimension #{dim_index} of size {dim_size}") + } + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for InvalidSlice {} + +#[cfg(not(feature = "std"))] +impl core::error::Error for InvalidSlice {} + #[derive(Debug, Clone)] /// Generic structure used to index a slice of the tensor pub enum TensorIndexer { @@ -29,19 +49,18 @@ pub enum TensorIndexer { Select(usize), /// This is a regular slice, purely indexing a chunk of the tensor Narrow(Bound, Bound), - //IndexSelect(Tensor), } -fn display_bound(bound: &Bound) -> String { +fn display_bound(bound: &Bound) -> &dyn Display { match bound { - Bound::Unbounded => "".to_string(), - Bound::Excluded(n) => format!("{n}"), - Bound::Included(n) => format!("{n}"), + Bound::Unbounded => &"", + Bound::Excluded(n) => n, + Bound::Included(n) => n, } } /// Intended for Python users mostly or at least for its conventions -impl core::fmt::Display for TensorIndexer { +impl Display for TensorIndexer { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { TensorIndexer::Select(n) => { diff --git a/safetensors/src/tensor.rs b/safetensors/src/tensor.rs index a510034..9546b5b 100644 --- a/safetensors/src/tensor.rs +++ b/safetensors/src/tensor.rs @@ -2,6 +2,8 @@ use crate::lib::{Cow, HashMap, String, ToString, Vec}; use crate::slice::{InvalidSlice, SliceIterator, TensorIndexer}; use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer}; +use core::fmt::Display; +use core::str::Utf8Error; #[cfg(feature = "std")] use std::io::Write; @@ -12,11 +14,11 @@ const MAX_HEADER_SIZE: usize = 100_000_000; #[derive(Debug)] pub enum SafeTensorError { /// The header is an invalid UTF-8 string and cannot be read. - InvalidHeader, + InvalidHeader(Utf8Error), /// The header's first byte is not the expected `{`. InvalidHeaderStart, /// The header does contain a valid string, but it is not valid JSON. - InvalidHeaderDeserialization, + InvalidHeaderDeserialization(serde_json::Error), /// The header is large than 100Mo which is considered too large (Might evolve in the future). HeaderTooLarge, /// The header is smaller than 8 bytes @@ -58,17 +60,60 @@ impl From for SafeTensorError { } } -impl core::fmt::Display for SafeTensorError { +impl Display for SafeTensorError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{self:?}") + use SafeTensorError::*; + + match self { + InvalidHeader(error) => write!(f, "invalid UTF-8 in header: {error}"), + InvalidHeaderStart => write!(f, "invalid start character in header, must be `{{`"), + InvalidHeaderDeserialization(error) => write!(f, "invalid JSON in header: {error}"), + JsonError(error) => write!(f, "JSON error: {error}"), + HeaderTooLarge => write!(f, "header too large"), + HeaderTooSmall => write!(f, "header too small"), + InvalidHeaderLength => write!(f, "invalid header length"), + TensorNotFound(name) => write!(f, "tensor `{name}` not found"), + TensorInvalidInfo => write!(f, "invalid shape, data type, or offset for tensor"), + InvalidOffset(name) => write!(f, "invalid offset for tensor `{name}`"), + #[cfg(feature = "std")] + IoError(error) => write!(f, "I/O error: {error}"), + InvalidTensorView(dtype, shape, n_bytes) => { + write!(f, "tensor of type {dtype} and shape (")?; + for (i, &dim) in shape.iter().enumerate() { + write!(f, "{sep}{dim}", sep = if i == 0 { "" } else { ", " })?; + } + write!(f, ") can't be created from {n_bytes} bytes") + } + MetadataIncompleteBuffer => write!(f, "incomplete metadata, file not fully covered"), + ValidationOverflow => write!(f, "overflow computing buffer size from shape and/or element type"), + } } } #[cfg(not(feature = "std"))] -impl core::error::Error for SafeTensorError {} +impl core::error::Error for SafeTensorError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + SafeTensorError::InvalidHeader(source) => Some(source), + SafeTensorError::JsonError(source) => Some(source), + SafeTensorError::InvalidHeaderDeserialization(source) => Some(source), + _ => None, + } + } +} #[cfg(feature = "std")] -impl std::error::Error for SafeTensorError {} +impl std::error::Error for SafeTensorError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + SafeTensorError::InvalidHeader(source) => Some(source), + SafeTensorError::JsonError(source) => Some(source), + SafeTensorError::InvalidHeaderDeserialization(source) => Some(source), + SafeTensorError::IoError(source) => Some(source), + _ => None, + } + } +} struct PreparedData { n: u64, @@ -308,14 +353,14 @@ impl<'data> SafeTensors<'data> { return Err(SafeTensorError::InvalidHeaderLength); } let string = - core::str::from_utf8(&buffer[8..stop]).map_err(|_| SafeTensorError::InvalidHeader)?; + core::str::from_utf8(&buffer[8..stop]).map_err(SafeTensorError::InvalidHeader)?; // Assert the string starts with { // NOTE: Add when we move to 0.4.0 // if !string.starts_with('{') { // return Err(SafeTensorError::InvalidHeaderStart); // } let metadata: HashMetadata = serde_json::from_str(string) - .map_err(|_| SafeTensorError::InvalidHeaderDeserialization)?; + .map_err(SafeTensorError::InvalidHeaderDeserialization)?; let metadata: Metadata = metadata.try_into()?; let buffer_end = metadata.validate()?; if buffer_end + 8 + n != buffer_len { @@ -739,6 +784,28 @@ impl Dtype { } } +impl Display for Dtype { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(match *self { + Dtype::BOOL => "BOOL", + Dtype::I8 => "I8", + Dtype::U8 => "U8", + Dtype::F8_E5M2 => "F8_E5M2", + Dtype::F8_E4M3 => "F8_E4M3", + Dtype::I16 => "I16", + Dtype::U16 => "U16", + Dtype::I32 => "I32", + Dtype::U32 => "U32", + Dtype::I64 => "I64", + Dtype::U64 => "U64", + Dtype::F16 => "F16", + Dtype::BF16 => "BF16", + Dtype::F32 => "F32", + Dtype::F64 => "F64", + }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -1204,7 +1271,7 @@ mod tests { fn test_invalid_header_non_utf8() { let serialized = b"\x01\x00\x00\x00\x00\x00\x00\x00\xff"; match SafeTensors::deserialize(serialized) { - Err(SafeTensorError::InvalidHeader) => { + Err(SafeTensorError::InvalidHeader(_)) => { // Yes we have the correct error } _ => panic!("This should not be able to be deserialized"), @@ -1215,7 +1282,7 @@ mod tests { fn test_invalid_header_not_json() { let serialized = b"\x01\x00\x00\x00\x00\x00\x00\x00{"; match SafeTensors::deserialize(serialized) { - Err(SafeTensorError::InvalidHeaderDeserialization) => { + Err(SafeTensorError::InvalidHeaderDeserialization(_)) => { // Yes we have the correct error } _ => panic!("This should not be able to be deserialized"),