Skip to main content

tensorlogic_trustformers/moe/
error.rs

1//! Error taxonomy for the research-preview numerical MoE layer.
2//!
3//! Kept local (not merged into [`crate::error::TrustformerError`]) so that
4//! MoE-internal diagnostics do not pollute the public transformer error
5//! enum. A [`From`] bridge forwards errors to the crate-wide type when the
6//! layer is invoked from higher-level code.
7
8use thiserror::Error;
9
10/// Errors that can be raised by the numerical Mixture-of-Experts layer.
11#[derive(Debug, Clone, Error, PartialEq)]
12pub enum MoeError {
13    /// The caller tried to build a [`super::MoELayer`] with an empty
14    /// `Vec<Box<dyn Expert>>`.
15    #[error("MoE layer constructed with zero experts")]
16    EmptyExpertPool,
17
18    /// The requested top-k value is outside `1..=num_experts`.
19    #[error("invalid top-k: k={k} must be in 1..={num_experts}")]
20    InvalidTopK {
21        /// Requested `k`.
22        k: usize,
23        /// Size of the expert pool.
24        num_experts: usize,
25    },
26
27    /// An input vector had the wrong length for the gate or expert pool.
28    #[error("shape mismatch: expected feature length {expected}, got {got}")]
29    ShapeMismatch {
30        /// Expected length.
31        expected: usize,
32        /// Observed length.
33        got: usize,
34    },
35
36    /// `capacity_factor` must be strictly positive and finite.
37    #[error("invalid capacity factor: {value} (must be strictly positive and finite)")]
38    InvalidCapacityFactor {
39        /// The offending value.
40        value: f64,
41    },
42}
43
44/// Result alias used inside the `moe` research preview.
45pub type MoeResult<T> = Result<T, MoeError>;
46
47impl From<MoeError> for crate::error::TrustformerError {
48    fn from(err: MoeError) -> Self {
49        crate::error::TrustformerError::CompilationError(err.to_string())
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn invalid_topk_display_contains_context() {
59        let err = MoeError::InvalidTopK {
60            k: 5,
61            num_experts: 2,
62        };
63        let msg = err.to_string();
64        assert!(msg.contains('5'));
65        assert!(msg.contains('2'));
66    }
67
68    #[test]
69    fn capacity_factor_error_carries_value() {
70        let err = MoeError::InvalidCapacityFactor { value: -1.0 };
71        assert!(err.to_string().contains("-1"));
72    }
73
74    #[test]
75    fn bridges_into_trustformer_error() {
76        let err = MoeError::EmptyExpertPool;
77        let bridged: crate::error::TrustformerError = err.into();
78        assert!(bridged.to_string().contains("MoE"));
79    }
80}