Skip to main content

tenferro_xla/
error.rs

1use std::error::Error as StdError;
2use std::path::PathBuf;
3
4use tenferro_tensor::{DType, ErrorKind, ValidationKind};
5
6/// Erased typed source used only at the XLA plugin boundary.
7pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
8
9/// Error type for StableHLO lowering and runtime PJRT plugin loading.
10///
11/// # Examples
12///
13/// ```
14/// use tenferro_runtime::{TraceContext, DType, GraphCompiler, TracedTensor};
15/// use tenferro_xla::{lower_compiled_to_stablehlo, Error};
16///
17/// let trace = TraceContext::new();
18/// let x = trace.input_symbolic_shape(DType::I64, 1).unwrap();
19/// let mut compiler = GraphCompiler::new();
20/// let y = x.neg().unwrap();
21/// let program = compiler
22///     .compile_with_input_specs(&y, &[(&x, DType::I64, &[2])])
23///     .unwrap();
24/// let err = lower_compiled_to_stablehlo(&program).unwrap_err();
25/// assert!(matches!(err, Error::UnsupportedDType { .. }));
26/// ```
27#[derive(Debug, thiserror::Error)]
28pub enum Error {
29    #[error("XLA lowering does not support dtype {dtype:?} in {context}")]
30    UnsupportedDType { dtype: DType, context: &'static str },
31    #[error("XLA lowering does not support ExecOp::{op}: {reason}")]
32    UnsupportedOp {
33        op: &'static str,
34        reason: &'static str,
35    },
36    #[error(
37        "XLA lowering supports only exact static shapes; ExecOp::{op} output {output_index} axis {axis} is {kind}"
38    )]
39    NonStaticShape {
40        op: &'static str,
41        output_index: usize,
42        axis: usize,
43        kind: &'static str,
44    },
45    #[error("invalid XLA program: {message}")]
46    InvalidProgram { message: String },
47    #[error("XLA tensor input/output error: {0}")]
48    Tensor(#[from] tenferro_tensor::Error),
49    #[error("XLA extension standard-op lowering failed: {source}")]
50    ExtensionLowering {
51        #[source]
52        source: tenferro_ops::ext_op::ExtensionLoweringError,
53    },
54    #[error("PJRT support requires enabling the tenferro-xla `pjrt` feature")]
55    PjrtFeatureDisabled,
56    #[error("PJRT execution requires an executor created from a loaded plugin")]
57    PjrtPluginNotLoaded,
58    #[error("PJRT call {call} failed: {message}")]
59    PjrtCall { call: &'static str, message: String },
60    #[error("environment variable {var} is not set; set it to a PJRT plugin .so path")]
61    MissingEnv { var: &'static str },
62    #[error("failed to load PJRT plugin from {path}: {source}")]
63    PluginLoad {
64        path: PathBuf,
65        #[source]
66        source: BoxError,
67    },
68}
69
70impl Error {
71    /// Return the stable coarse classification for this XLA failure.
72    ///
73    /// # Examples
74    ///
75    /// ```
76    /// use tenferro_tensor::ErrorKind;
77    /// use tenferro_xla::Error;
78    ///
79    /// assert_eq!(
80    ///     Error::UnsupportedOp { op: "Maximum", reason: "not lowered" }.kind(),
81    ///     ErrorKind::Unsupported,
82    /// );
83    /// ```
84    #[must_use]
85    pub fn kind(&self) -> ErrorKind {
86        match self {
87            Self::UnsupportedDType { .. } | Self::UnsupportedOp { .. } => ErrorKind::Unsupported,
88            Self::NonStaticShape { .. } => ErrorKind::Validation(ValidationKind::ShapeMismatch),
89            Self::InvalidProgram { .. } => ErrorKind::Validation(ValidationKind::InvalidArgument),
90            Self::Tensor(source) => source.kind(),
91            Self::ExtensionLowering { source } => source.kind(),
92            Self::PjrtFeatureDisabled | Self::PjrtPluginNotLoaded | Self::MissingEnv { .. } => {
93                ErrorKind::RuntimeState
94            }
95            Self::PluginLoad { .. } => ErrorKind::Io,
96            Self::PjrtCall { .. } => ErrorKind::BackendFailure,
97        }
98    }
99}
100
101/// Result alias for `tenferro-xla`.
102///
103/// # Examples
104///
105/// ```
106/// use tenferro_xla::Result;
107///
108/// fn ok() -> Result<()> {
109///     Ok(())
110/// }
111///
112/// ok().unwrap();
113/// ```
114pub type Result<T> = std::result::Result<T, Error>;
115
116#[cfg(test)]
117mod tests;