numr 0.15.1

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
//! Error types for numr

use crate::dtype::DType;
use thiserror::Error;

/// Result type alias using numr's Error
pub type Result<T> = std::result::Result<T, Error>;

/// Errors that can occur in numr operations
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    /// Shape mismatch in an operation
    #[error("Shape mismatch: expected {expected:?}, got {got:?}")]
    ShapeMismatch {
        /// Expected shape
        expected: Vec<usize>,
        /// Actual shape
        got: Vec<usize>,
    },

    /// Shapes cannot be broadcast together
    #[error("Cannot broadcast shapes {lhs:?} and {rhs:?}")]
    BroadcastError {
        /// Left-hand side shape
        lhs: Vec<usize>,
        /// Right-hand side shape
        rhs: Vec<usize>,
    },

    /// Invalid dimension index
    #[error("Invalid dimension {dim} for tensor with {ndim} dimensions")]
    InvalidDimension {
        /// The invalid dimension
        dim: isize,
        /// Number of dimensions
        ndim: usize,
    },

    /// Unsupported dtype for an operation
    #[error("Unsupported dtype {dtype:?} for operation '{op}'")]
    UnsupportedDType {
        /// The unsupported dtype
        dtype: DType,
        /// The operation name
        op: &'static str,
    },

    /// DType mismatch between operands
    #[error("DType mismatch: {lhs:?} vs {rhs:?}")]
    DTypeMismatch {
        /// Left-hand side dtype
        lhs: DType,
        /// Right-hand side dtype
        rhs: DType,
    },

    /// Device mismatch between operands
    #[error("Device mismatch: tensors must be on the same device")]
    DeviceMismatch,

    /// Out of memory
    #[error("Out of memory: failed to allocate {size} bytes")]
    OutOfMemory {
        /// Requested size in bytes
        size: usize,
    },

    /// Tensor allocation failed, with the shape/dtype/device context
    ///
    /// Wraps the underlying allocation error (usually [`Error::OutOfMemory`])
    /// so the message names what was being allocated, not only a byte count.
    #[error("failed to allocate tensor {shape:?} {dtype} on {device}: {source}")]
    AllocFailed {
        /// Shape of the tensor that could not be allocated
        shape: Vec<usize>,
        /// Element type short name (e.g. "bf16", "q4_0")
        dtype: String,
        /// Device name (from [`Device::name`](crate::runtime::Device::name))
        device: String,
        /// The underlying allocation error
        #[source]
        source: Box<Error>,
    },

    /// Index out of bounds
    #[error("Index {index} out of bounds for dimension of size {size}")]
    IndexOutOfBounds {
        /// The invalid index
        index: usize,
        /// Size of the dimension
        size: usize,
    },

    /// Invalid argument provided to an operation
    #[error("Invalid argument '{arg}': {reason}")]
    InvalidArgument {
        /// The argument name
        arg: &'static str,
        /// Reason for invalidity
        reason: String,
    },

    /// Tensor is not contiguous when contiguous memory is required
    #[error("Operation requires contiguous tensor")]
    NotContiguous,

    /// A host read names an element type whose width differs from the dtype.
    ///
    /// A width mismatch sizes the copy wrong, so it would read past the buffer.
    #[error(
        "cannot read a {dtype} tensor ({dtype_bytes} bytes per element) as \
         {elem_bytes}-byte elements: cast it to the target dtype first"
    )]
    HostReadTypeMismatch {
        /// Short name of the stored dtype
        dtype: &'static str,
        /// Bytes per element of the stored dtype
        dtype_bytes: usize,
        /// Bytes per element of the requested host type
        elem_bytes: usize,
    },

    /// Missing gradient in backward pass
    #[error("Missing gradient for tensor")]
    MissingGradient,

    /// Backend-specific error
    #[error("Backend error: {0}")]
    Backend(String),

    /// Backend limitation - operation valid but exceeds backend capabilities
    #[error("{backend} limitation: {operation} - {reason}")]
    BackendLimitation {
        /// The backend that has the limitation
        backend: &'static str,
        /// The operation being attempted
        operation: &'static str,
        /// Description of the limitation
        reason: String,
    },

    /// CUDA-specific error
    #[cfg(feature = "cuda")]
    #[error("CUDA error: {0}")]
    Cuda(#[from] cudarc::driver::DriverError),

    /// Generic message error
    #[error("{0}")]
    Msg(String),

    /// Generic internal error
    #[error("Internal error: {0}")]
    Internal(String),

    /// Feature not yet implemented
    #[error("Not implemented: {feature}")]
    NotImplemented {
        /// Description of the unimplemented feature
        feature: &'static str,
    },

    /// Cargo feature required but not enabled
    #[error(
        "{dtype:?} requires the \"{feature}\" feature. Enable it with: cargo build --features {feature}"
    )]
    FeatureRequired {
        /// The dtype that needs the feature
        dtype: DType,
        /// The cargo feature name to enable
        feature: &'static str,
    },

    /// Allocator cannot reset while allocations are still live
    #[error("Allocator busy: {active_allocations} allocations still active")]
    AllocatorBusy {
        /// Number of allocations that are still live
        active_allocations: usize,
    },

    /// Allocator is frozen — no new allocations permitted
    #[error("Allocator frozen: allocation rejected while frozen")]
    AllocatorFrozen,

    /// A CUDA graph capture arena ran out of room for an intermediate
    /// allocation.
    ///
    /// Carries the numbers a caller needs to size a retry: the request that
    /// failed, the bytes the arena had already handed out, and the arena's
    /// total capacity. Raised during `capture_graph_into_with_arena` when an
    /// intermediate allocation inside the capture overruns the pre-sized
    /// arena; the caller can recapture with a larger arena sized from
    /// `used + requested`.
    #[error(
        "CUDA graph arena exhausted: requested {requested} bytes, {used} of {capacity} arena \
         bytes used; recapture with a larger arena sized from these numbers"
    )]
    ArenaExhausted {
        /// Bytes the failing allocation asked for
        requested: usize,
        /// Bytes already handed out by the arena before this request
        used: usize,
        /// Total arena capacity in bytes
        capacity: usize,
    },
}

impl Error {
    /// The arena-exhaustion fields, if this error is
    /// [`Error::ArenaExhausted`] or wraps one as an
    /// [`Error::AllocFailed`] source.
    ///
    /// A CUDA graph intermediate is normally allocated through
    /// `Tensor::empty`/`Tensor::zeros`, which wraps every allocation failure
    /// in `AllocFailed` for shape/dtype/device context. This walks that one
    /// layer of wrapping so a caller can react to arena exhaustion without
    /// matching on message text.
    pub fn as_arena_exhausted(&self) -> Option<(usize, usize, usize)> {
        match self {
            Error::ArenaExhausted {
                requested,
                used,
                capacity,
            } => Some((*requested, *used, *capacity)),
            Error::AllocFailed { source, .. } => source.as_arena_exhausted(),
            _ => None,
        }
    }
}

impl Error {
    /// Create a shape mismatch error
    pub fn shape_mismatch(expected: &[usize], got: &[usize]) -> Self {
        Self::ShapeMismatch {
            expected: expected.to_vec(),
            got: got.to_vec(),
        }
    }

    /// Create a broadcast error
    pub fn broadcast(lhs: &[usize], rhs: &[usize]) -> Self {
        Self::BroadcastError {
            lhs: lhs.to_vec(),
            rhs: rhs.to_vec(),
        }
    }

    /// Create an unsupported dtype error
    pub fn unsupported_dtype(dtype: DType, op: &'static str) -> Self {
        Self::UnsupportedDType { dtype, op }
    }

    /// Returns `true` when an allocation fails for lack of memory.
    ///
    /// This holds for [`Error::OutOfMemory`], and for [`Error::AllocFailed`]
    /// that wraps it. A caller can then name the next action, such as a smaller
    /// input, without reading the message.
    pub fn is_out_of_memory(&self) -> bool {
        match self {
            Self::OutOfMemory { .. } => true,
            Self::AllocFailed { source, .. } => source.is_out_of_memory(),
            _ => false,
        }
    }

    /// Create a backend limitation error
    pub fn backend_limitation(
        backend: &'static str,
        operation: &'static str,
        reason: impl Into<String>,
    ) -> Self {
        Self::BackendLimitation {
            backend,
            operation,
            reason: reason.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn alloc_failed(source: Error) -> Error {
        Error::AllocFailed {
            shape: vec![2, 2],
            dtype: "f32".to_string(),
            device: "cpu".to_string(),
            source: Box::new(source),
        }
    }

    #[test]
    fn out_of_memory_is_found_directly_and_through_alloc_failed() {
        assert!(Error::OutOfMemory { size: 16 }.is_out_of_memory());
        assert!(alloc_failed(Error::OutOfMemory { size: 16 }).is_out_of_memory());
    }

    #[test]
    fn other_errors_are_not_out_of_memory() {
        assert!(!Error::Backend("cuMemAllocAsync failed".to_string()).is_out_of_memory());
        assert!(!alloc_failed(Error::Backend("capture".to_string())).is_out_of_memory());
        assert!(!Error::NotContiguous.is_out_of_memory());
    }
}