Implementation:LaurentMazare Tch rs TchError
| Knowledge Sources | |
|---|---|
| Domains | Error Handling, Rust FFI |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
TchError is the main error enum for the tch-rs library, unifying all possible failure modes -- from C++ Torch errors to I/O, parsing, shape, and format errors -- into a single thiserror-derived type.
Description
The TchError enum is defined using the thiserror crate's derive macro, which automatically generates Display and Error trait implementations. It aggregates twelve distinct error variants covering the full range of failures that can occur when working with tensors, file formats, and the underlying PyTorch C++ runtime. Several variants use #[error(transparent)] to wrap standard library errors (io::Error, NulError, ParseIntError) and third-party errors (ZipError, ndarray::ShapeError, safetensors::SafeTensorError) without additional formatting.
The enum also provides a path_context method that prepends file-path context to Torch variant error messages, useful for enriching error messages during file loading operations.
Usage
Use TchError as the error type in any function that interacts with tensors, loads model files, performs type conversions, or calls into the PyTorch C++ backend. The crate root defines type Result<T> = std::result::Result<T, TchError> so that all fallible functions in the library return this unified error type.
Code Reference
Source Location
- Repository: LaurentMazare_Tch_rs
- File: src/error.rs
Signature
#[derive(Error, Debug)]
pub enum TchError {
Convert(String),
FileFormat(String),
TensorNameNotFound(String, String),
Io(#[from] io::Error),
Kind(String),
MissingImage(String),
Nul(#[from] NulError),
ParseInt(#[from] ParseIntError),
Shape(String),
UnknownKind(libc::c_int),
Torch(String),
Zip(#[from] ZipError),
NdArray(#[from] ndarray::ShapeError),
SafeTensorError { path: String, err: safetensors::SafeTensorError },
}
impl TchError {
pub fn path_context(&self, path_name: &str) -> Self;
}
Import
use tch::TchError;
// or use the Result alias:
use tch::Result;
I/O Contract
| Variant | Source | Error Message Pattern |
|---|---|---|
| Convert | Type conversion failures | conversion error: {0}
|
| FileFormat | Invalid file headers or formats | invalid file format: {0}
|
| TensorNameNotFound | Missing named tensor in file | cannot find the tensor named {0} in {1}
|
| Io | Standard I/O errors (transparent) | Delegated to io::Error |
| Kind | Tensor kind mismatches | tensor kind error: {0}
|
| MissingImage | Image file not found | no image found in {0}
|
| Nul | Null byte in C string (transparent) | Delegated to NulError |
| ParseInt | Integer parsing failure (transparent) | Delegated to ParseIntError |
| Shape | Invalid tensor shape | invalid shape: {0}
|
| UnknownKind | Unrecognized C int kind value | unknown kind: {0}
|
| Torch | C++ PyTorch runtime errors | Internal torch error: {0}
|
| Zip | Zip archive errors (transparent) | Delegated to ZipError |
| NdArray | ndarray shape errors (transparent) | Delegated to ndarray::ShapeError |
| SafeTensorError | Safetensors library errors | safetensors error {path}: {err}
|
Usage Examples
use tch::{TchError, Result};
// Functions return tch::Result which uses TchError
fn load_model(path: &str) -> Result<tch::Tensor> {
tch::Tensor::read_npy(path)
}
// Matching on error variants
match load_model("model.npy") {
Ok(tensor) => println!("loaded tensor: {:?}", tensor.size()),
Err(TchError::FileFormat(msg)) => eprintln!("bad format: {}", msg),
Err(TchError::Io(e)) => eprintln!("io error: {}", e),
Err(e) => eprintln!("other error: {}", e),
}
// Using path_context to enrich Torch errors
let err = TchError::Torch("out of memory".to_string());
let enriched = err.path_context("weights.pt");
// enriched displays: "Internal torch error: weights.pt: out of memory"