candle_mi/error.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Error types for candle-mi.
4
5/// Errors that can occur during MI operations.
6///
7/// This enum is `#[non_exhaustive]`: new variants will be added in future
8/// releases as new backends and capabilities are added.
9#[non_exhaustive]
10#[derive(Debug, thiserror::Error)]
11pub enum MIError {
12 /// Model loading or forward pass error (wraps candle).
13 #[error("model error: {0}")]
14 Model(#[from] candle_core::Error),
15
16 /// Hook capture or lookup error.
17 #[error("hook error: {0}")]
18 Hook(String),
19
20 /// Intervention validation or application error.
21 #[error("intervention error: {0}")]
22 Intervention(String),
23
24 /// Model configuration parsing error.
25 #[error("config error: {0}")]
26 Config(String),
27
28 /// Tokenizer error.
29 #[error("tokenizer error: {0}")]
30 Tokenizer(String),
31
32 /// I/O error.
33 #[error(transparent)]
34 Io(#[from] std::io::Error),
35
36 /// Model download error.
37 ///
38 /// Returned when downloading a model from the `HuggingFace` Hub fails.
39 #[error("download error: {0}")]
40 Download(String),
41
42 /// Memory measurement error.
43 ///
44 /// Returned when a platform API for RAM or VRAM measurement fails.
45 #[error("memory error: {0}")]
46 Memory(String),
47}
48
49/// Bridge anamnesis errors into [`MIError`] when the `sae` feature is enabled.
50///
51/// [`AnamnesisError`](anamnesis::AnamnesisError) is `#[non_exhaustive]`, so the
52/// catch-all arm ensures forward compatibility with future variants.
53#[cfg(feature = "sae")]
54impl From<anamnesis::AnamnesisError> for MIError {
55 // `AnamnesisError` is an external `#[non_exhaustive]` error type. We map the
56 // few variants we act on and deliberately collapse the rest (and any future
57 // ones) to `Config` via the catch-all, rather than re-enumerating upstream's
58 // variants on every anamnesis release. The wildcard is required for the
59 // `#[non_exhaustive]` enum, so allow the otherwise-denied lint here.
60 #[allow(clippy::wildcard_enum_match_arm)]
61 fn from(e: anamnesis::AnamnesisError) -> Self {
62 match e {
63 anamnesis::AnamnesisError::Parse { reason } => Self::Config(reason),
64 anamnesis::AnamnesisError::Unsupported { format, detail } => {
65 Self::Config(format!("unsupported {format}: {detail}"))
66 }
67 anamnesis::AnamnesisError::Io(io_err) => Self::Io(io_err),
68 _ => Self::Config(e.to_string()),
69 }
70 }
71}
72
73/// Result type alias for candle-mi operations.
74pub type Result<T> = std::result::Result<T, MIError>;