use std::error::Error;
pub type ModuleResult<T, B> = Result<T, ModuleError<<B as coeus_core::ComputeBackend>::Error>>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModuleError<E>
where
E: Error + 'static,
{
#[error("{module} backend operation failed")]
Backend {
module: &'static str,
#[source]
source: E,
},
#[error(transparent)]
Interpolation(coeus_ops::InterpolationError),
#[error("{module} expected input rank {expected}, got {actual}")]
InvalidRank {
module: &'static str,
expected: &'static str,
actual: usize,
},
#[error("{module} axis {axis} is out of range for rank {rank}")]
InvalidAxis {
module: &'static str,
axis: usize,
rank: usize,
},
#[error("{module} axis {axis} requires an even extent, got {extent}")]
UnevenSplit {
module: &'static str,
axis: usize,
extent: usize,
},
#[error("{module} {parameter} shape mismatch: expected {expected:?}, got {actual:?}")]
ShapeMismatch {
module: &'static str,
parameter: &'static str,
expected: Vec<usize>,
actual: Vec<usize>,
},
#[error("{module} channel mismatch: expected {expected}, got {actual}")]
ChannelMismatch {
module: &'static str,
expected: usize,
actual: usize,
},
#[error("{module} group count {groups} does not divide {channels} channels")]
InvalidGroupCount {
module: &'static str,
groups: usize,
channels: usize,
},
#[error("{module} epsilon must be finite and non-negative")]
InvalidEpsilon {
module: &'static str,
},
#[error("{module} requires at least {minimum} values per channel, got {actual}")]
InsufficientElements {
module: &'static str,
minimum: usize,
actual: usize,
},
#[error("{module} state {state} is already borrowed")]
StateBorrow {
module: &'static str,
state: &'static str,
},
}
impl<E> From<E> for ModuleError<E>
where
E: Error + 'static,
{
fn from(source: E) -> Self {
Self::Backend {
module: "neural network module",
source,
}
}
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParameterLoadError {
#[error("named parameter count mismatch: expected {expected}, got {actual}")]
Count {
expected: usize,
actual: usize,
},
#[error("named parameter mismatch at index {index}: expected {expected}, got {actual}")]
Name {
index: usize,
expected: String,
actual: String,
},
}
#[cfg(test)]
mod tests {
use super::ModuleError;
use coeus_core::BackendError;
#[test]
fn backend_failure_preserves_module_and_source() {
let source = BackendError::AxisOutOfRange {
operation: "sum",
axis: 3,
rank: 2,
};
let error = ModuleError::Backend {
module: "LayerNorm",
source: source.clone(),
};
match error {
ModuleError::Backend {
module,
source: actual,
} => {
assert_eq!(module, "LayerNorm");
assert_eq!(actual, source);
}
other => panic!("expected backend failure, got {other:?}"),
}
}
}