fuel-ir 0.24.0

Core types and traits for the fuel ML framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Fuel-specific Error and Result types.
use std::{convert::Infallible, fmt::Display};

use crate::{DType, DeviceLocation, Layout, Shape};

/// Diagnostic information for a matrix multiplication that encountered unexpected striding.
#[derive(Debug, Clone)]
pub struct MatMulUnexpectedStriding {
    pub lhs_l: Layout,
    pub rhs_l: Layout,
    pub bmnk: (usize, usize, usize, usize),
    pub msg: &'static str,
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self}")
    }
}

/// The main error type for the fuel library.
#[derive(thiserror::Error)]
pub enum Error {
    // === DType Errors ===
    #[error("{msg}, expected: {expected:?}, got: {got:?}")]
    UnexpectedDType {
        msg: &'static str,
        expected: DType,
        got: DType,
    },

    #[error("dtype mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")]
    DTypeMismatchBinaryOp {
        lhs: DType,
        rhs: DType,
        op: &'static str,
    },

    #[error("unsupported dtype {0:?} for op {1}")]
    UnsupportedDTypeForOp(DType, &'static str),

    #[error("no zero scalar for dtype {0:?} (scale format has no exact zero)")]
    NoZeroScalar(DType),
    #[error("no one scalar for dtype {0:?}")]
    NoOneScalar(DType),
    #[error("value {1} not representable as a scalar of dtype {0:?}")]
    ScalarUnrepresentable(DType, f64),
    #[error("dtype {0:?} is a packed element format with no scalar representation")]
    PackedElementHasNoScalar(DType),

    // === Dimension Index Errors ===
    #[error("{op}: dimension index {dim} out of range for shape {shape:?}")]
    DimOutOfRange {
        shape: Box<Shape>,
        dim: i32,
        op: &'static str,
    },

    #[error("{op}: duplicate dim index {dims:?} for shape {shape:?}")]
    DuplicateDimIndex {
        shape: Box<Shape>,
        dims: Vec<usize>,
        op: &'static str,
    },

    // === Shape Errors ===
    #[error("unexpected rank, expected: {expected}, got: {got} ({shape:?})")]
    UnexpectedNumberOfDims {
        expected: usize,
        got: usize,
        shape: Box<Shape>,
    },

    #[error("{msg}, expected: {expected:?}, got: {got:?}")]
    UnexpectedShape {
        msg: String,
        expected: Box<Shape>,
        got: Box<Shape>,
    },

    #[error(
        "Shape mismatch, got buffer of size {buffer_size} which is compatible with shape {shape:?}"
    )]
    ShapeMismatch {
        buffer_size: usize,
        shape: Box<Shape>,
    },

    #[error("shape mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")]
    ShapeMismatchBinaryOp {
        lhs: Box<Shape>,
        rhs: Box<Shape>,
        op: &'static str,
    },

    #[error(
        "shape mismatch in cat for dim {dim}, shape for arg 1: {first_shape:?} shape for arg {n}: {nth_shape:?}"
    )]
    ShapeMismatchCat {
        dim: usize,
        first_shape: Box<Shape>,
        n: usize,
        nth_shape: Box<Shape>,
    },

    #[error("Cannot divide tensor of shape {shape:?} equally along dim {dim} into {n_parts}")]
    ShapeMismatchSplit {
        shape: Box<Shape>,
        dim: usize,
        n_parts: usize,
    },

    #[error("{op} can only be performed on a single dimension")]
    OnlySingleDimension { op: &'static str, dims: Vec<usize> },

    #[error("empty tensor for {op}")]
    EmptyTensor { op: &'static str },

    // === Device Errors ===
    #[error("device mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")]
    DeviceMismatchBinaryOp {
        lhs: DeviceLocation,
        rhs: DeviceLocation,
        op: &'static str,
    },

    // === Op Specific Errors ===
    #[error("narrow invalid args {msg}: {shape:?}, dim: {dim}, start: {start}, len:{len}")]
    NarrowInvalidArgs {
        shape: Box<Shape>,
        dim: usize,
        start: usize,
        len: usize,
        msg: &'static str,
    },

    #[error(
        "conv1d invalid args {msg}: inp: {inp_shape:?}, k: {k_shape:?}, pad: {padding}, stride: {stride}"
    )]
    Conv1dInvalidArgs {
        inp_shape: Box<Shape>,
        k_shape: Box<Shape>,
        padding: usize,
        stride: usize,
        msg: &'static str,
    },

    #[error("{op} invalid index {index} with dim size {size}")]
    InvalidIndex {
        op: &'static str,
        index: usize,
        size: usize,
    },

    #[error("cannot broadcast {src_shape:?} to {dst_shape:?}")]
    BroadcastIncompatibleShapes {
        src_shape: Box<Shape>,
        dst_shape: Box<Shape>,
    },

    #[error("cannot set variable {msg}")]
    CannotSetVar { msg: &'static str },

    #[error("{0:?}")]
    MatMulUnexpectedStriding(Box<MatMulUnexpectedStriding>),

    #[error("{op} only supports contiguous tensors")]
    RequiresContiguous { op: &'static str },

    #[error("{op} expects at least one tensor")]
    OpRequiresAtLeastOneTensor { op: &'static str },

    #[error("{op} expects at least two tensors")]
    OpRequiresAtLeastTwoTensors { op: &'static str },

    #[error("backward is not supported for {op}")]
    BackwardNotSupported { op: &'static str },

    // === Phase 7.5 storage-unification dispatch errors ===
    /// No registered backend supports `(op, dtypes)` for the given
    /// input residency. Fires at DAG construction (planning time),
    /// not at execution.
    ///
    /// `dtypes` is the per-operand dtype list (inputs in order, then
    /// outputs) used as the binding-table lookup key. For uniform-
    /// precision ops the list contains a single repeated dtype; for
    /// mixed-precision ops (e.g. Cast: src→dst) the list distinguishes
    /// the operands.
    #[error(
        "no backend supports {op} on {dtypes:?}; available backends: \
         {available_backends:?}; supported (op, dtypes) by backend: \
         {supported_combinations:?}"
    )]
    NoBackendForOp {
        op: crate::dispatch::OpKind,
        dtypes: Vec<DType>,
        available_backends: Vec<crate::probe::BackendId>,
        supported_combinations: Vec<(crate::probe::BackendId, crate::dispatch::OpKind, Vec<DType>)>,
    },

    /// No transfer path connects `from` and `to` directly, and
    /// host-staging fallback isn't available either (e.g. neither
    /// device can copy_to_host). Fires at DAG construction.
    #[error("unsupported transfer from {from:?} to {to:?}; available paths: {available_paths:?}")]
    UnsupportedTransfer {
        from: DeviceLocation,
        to: DeviceLocation,
        available_paths: Vec<crate::backend::TransferPath>,
    },

    /// Source storage's alignment doesn't meet the destination
    /// backend's required alignment, and Router has no way to
    /// repack on this path. Fires at DAG construction.
    #[error("alignment mismatch on {backend:?}: required {required} bytes, got {actual} bytes")]
    AlignmentMismatch {
        backend: crate::probe::BackendId,
        required: usize,
        actual: usize,
    },

    /// The `ExecutionPlan` consumed by the executor was built against
    /// an older `SystemTopology` generation than the one observable
    /// at dispatch time — backends were added, removed, or had their
    /// capabilities re-probed since the plan was committed. Caught
    /// at dispatch-chunk boundaries by Phase 4.3 of the picker-work
    /// arc; the realize layer catches this and rebuilds the plan
    /// against the fresh topology.
    ///
    /// `plan_generation` is the counter the plan was stamped with at
    /// `compile_plan` time. `current_generation` is the value
    /// `fuel_dispatch::dispatch::topology_generation()` observed when
    /// the executor crossed the chunk boundary.
    #[error(
        "execution plan was built against topology generation {plan_generation}, \
         but generation {current_generation} is now current; rebuild and retry"
    )]
    TopologyChanged {
        plan_generation: u64,
        current_generation: u64,
    },

    // === Other Errors ===
    #[error("the fuel crate has not been built with cuda support")]
    NotCompiledWithCudaSupport,

    #[error("the fuel crate has not been built with metal support")]
    NotCompiledWithMetalSupport,

    #[error("the fuel crate has not been built with vulkan support")]
    NotCompiledWithVulkanSupport,

    #[error("cannot find tensor {path}")]
    CannotFindTensor { path: String },

    // === Wrapped Errors ===
    #[error(transparent)]
    Cuda(Box<dyn std::error::Error + Send + Sync>),

    #[error(transparent)]
    Metal(Box<dyn std::error::Error + Send + Sync>),

    #[error(transparent)]
    Vulkan(Box<dyn std::error::Error + Send + Sync>),

    #[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios"), feature = "ug"))]
    #[error(transparent)]
    Ug(Box<dyn std::error::Error + Send + Sync>),

    #[error(transparent)]
    TryFromIntError(#[from] core::num::TryFromIntError),

    #[error("npy/npz error {0}")]
    Npy(String),

    /// Zip file format error.
    #[error(transparent)]
    Zip(#[from] zip::result::ZipError),

    /// Integer parse error.
    #[error(transparent)]
    ParseInt(#[from] std::num::ParseIntError),

    /// Utf8 parse error.
    #[error(transparent)]
    FromUtf8(#[from] std::string::FromUtf8Error),

    /// I/O error.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// SafeTensor error.
    #[error(transparent)]
    SafeTensor(#[from] safetensors::SafeTensorError),

    #[error("unsupported safetensor dtype {0:?}")]
    UnsupportedSafeTensorDtype(safetensors::Dtype),

    /// Arbitrary errors wrapping.
    #[error("{0}")]
    Wrapped(Box<dyn std::fmt::Display + Send + Sync>),

    /// Arbitrary errors wrapping with context.
    #[error("{wrapped:?}\n{context:?}")]
    WrappedContext {
        wrapped: Box<dyn std::error::Error + Send + Sync>,
        context: String,
    },

    #[error("{context}\n{inner}")]
    Context {
        inner: Box<Self>,
        context: Box<dyn std::fmt::Display + Send + Sync>,
    },

    /// Adding path information to an error.
    #[error("path: {path:?} {inner}")]
    WithPath {
        inner: Box<Self>,
        path: std::path::PathBuf,
    },

    #[error("{inner}\n{backtrace}")]
    WithBacktrace {
        inner: Box<Self>,
        backtrace: Box<std::backtrace::Backtrace>,
    },

    /// User generated error message, typically created via `bail!`.
    #[error("{0}")]
    Msg(String),

    #[error("unwrap none")]
    UnwrapNone,

    /// A hard filter in the optimizer ranker's filter chain rejected
    /// every candidate at this decision point. Phase 1.1 of the
    /// picker-work arc. The user asked for something the binding-table
    /// can't deliver — typically a precision floor or tolerance budget
    /// no registered kernel meets — and the ranker surfaces it rather
    /// than silently substituting a non-admissible alternative.
    ///
    /// Soft filters (caps preferences, empirical refinements) never
    /// raise this error; only filters classified `FilterClass::Hard`
    /// fail loudly when they would leave the candidate set empty.
    #[error(
        "ranker hard filter `{filter}` rejected all {available_alternatives} candidate(s); \
         context: {ctx_summary}"
    )]
    FilterRejected {
        /// Name of the filter that triggered the rejection.
        filter: &'static str,
        /// Short diagnostic summary of the decision point's context
        /// (op kind, dtypes, device).
        ctx_summary: String,
        /// How many candidates entered the filter (zero on the way
        /// in is also possible — the candidate enumerator may have
        /// produced an empty set).
        available_alternatives: usize,
    },

    /// Build-time rejection from the `Op::Branch` builders
    /// (`Graph::open_branch` / `BranchBuilder::add_arm` /
    /// `BranchBuilder::finalize_branches`). Phase A PR-A1 of the
    /// "plan IS the graph" rebuild. The multi-path structure is an
    /// arena fact validated at graph-build time — never a realize-time
    /// panic — so an ill-formed branch (a `reconverge_at` that is not a
    /// descendant of the diverge point, arms that are not internally
    /// disjoint, arm exits that disagree on shape/dtype at reconverge)
    /// surfaces here with a human-readable reason rather than corrupting
    /// the arena.
    #[error("invalid branch: {reason}")]
    InvalidBranch {
        /// Why the branch was rejected — names the violated invariant
        /// and the offending node ids for localization.
        reason: String,
    },
}

/// A specialized [`Result`](std::result::Result) type for fuel operations.
pub type Result<T> = std::result::Result<T, Error>;

// ── Error size guard (clippy::result_large_err) ────────────────────────────
// `Result<T>` here is `Result<T, Error>`, so EVERY fallible fuel-ir function —
// **including the Ok path** — carries `size_of::<Error>()` bytes inline. The
// diagnostic variants used to embed `Shape` (128 bytes) BY VALUE, which bloated
// `Error` to 288 bytes and every `Result<T>` with it (clippy fired
// `result_large_err` on 58 sites); the `Shape` fields are now `Box<Shape>` and
// `Error` measures 80 bytes (`-Zprint-type-sizes`, 2026-08-14).
//
// This guard keeps that win maintained rather than one-time: a NEW variant that
// embeds a large type by value (another `Shape`, a big struct) is a HOT-PATH
// regression — not cosmetic — and trips here at COMPILE time, before it can
// re-inflate every `Result<T>`. Same shape as a retained sabotage control: a
// one-time fix becomes a maintained property. Raising the bound is a DELIBERATE
// decision about that Ok-path cost, not a formality — measure the new size and
// justify it. 96 = the measured 80 + headroom, and stays well under clippy's
// 128-byte threshold so this catches a regression before the lint would.
const _: () = assert!(
    std::mem::size_of::<Error>() <= 96,
    "fuel_ir::Error exceeded its size budget: a Result<T> hot-path regression. \
     Box the large field, or consciously raise the bound (see the comment above)."
);

impl Error {
    /// Wraps an arbitrary displayable error.
    pub fn wrap(err: impl std::fmt::Display + Send + Sync + 'static) -> Self {
        Self::Wrapped(Box::new(err)).bt()
    }

    /// Creates an error message from any displayable value.
    pub fn msg(err: impl std::fmt::Display) -> Self {
        Self::Msg(err.to_string()).bt()
    }

    /// Creates an error message from the debug representation of a value.
    pub fn debug(err: impl std::fmt::Debug) -> Self {
        Self::Msg(format!("{err:?}")).bt()
    }

    /// Wraps a CUDA backend error.
    pub fn cuda(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Cuda(Box::new(err)).bt()
    }

    /// Wraps a Metal backend error.
    pub fn metal(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Metal(Box::new(err)).bt()
    }

    /// Wraps a Vulkan backend error.
    pub fn vulkan(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Vulkan(Box::new(err)).bt()
    }

    /// Captures a backtrace and attaches it to this error.
    pub fn bt(self) -> Self {
        let backtrace = std::backtrace::Backtrace::capture();
        match backtrace.status() {
            std::backtrace::BacktraceStatus::Disabled
            | std::backtrace::BacktraceStatus::Unsupported => self,
            _ => Self::WithBacktrace {
                inner: Box::new(self),
                backtrace: Box::new(backtrace),
            },
        }
    }

    /// Attaches a filesystem path to this error for better diagnostics.
    pub fn with_path<P: AsRef<std::path::Path>>(self, p: P) -> Self {
        Self::WithPath {
            inner: Box::new(self),
            path: p.as_ref().to_path_buf(),
        }
    }

    /// Wraps this error with additional context.
    pub fn context(self, c: impl std::fmt::Display + Send + Sync + 'static) -> Self {
        Self::Context {
            inner: Box::new(self),
            context: Box::new(c),
        }
    }
}

/// Returns early from a function with a formatted error message.
#[macro_export]
macro_rules! bail {
    ($msg:literal $(,)?) => {
        return Err($crate::Error::Msg(format!($msg).into()).bt())
    };
    ($err:expr $(,)?) => {
        return Err($crate::Error::Msg(format!($err).into()).bt())
    };
    ($fmt:expr, $($arg:tt)*) => {
        return Err($crate::Error::Msg(format!($fmt, $($arg)*).into()).bt())
    };
}

/// Combines two results into a single result containing a tuple.
pub fn zip<T, U>(r1: Result<T>, r2: Result<U>) -> Result<(T, U)> {
    match (r1, r2) {
        (Ok(r1), Ok(r2)) => Ok((r1, r2)),
        (Err(e), _) => Err(e),
        (_, Err(e)) => Err(e),
    }
}

#[doc(hidden)]
pub mod private {
    pub trait Sealed {}

    impl<T, E> Sealed for std::result::Result<T, E> where E: std::error::Error {}
    impl<T> Sealed for Option<T> {}
}

/// Attach more context to an error.
pub trait Context<T, E>: private::Sealed {
    /// Wrap the error value with additional context.
    fn context<C>(self, context: C) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static;

    /// Wrap the error value with additional context evaluated lazily.
    fn with_context<C, F>(self, f: F) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C;
}

impl<T, E> Context<T, E> for std::result::Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn context<C>(self, context: C) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
    {
        self.map_err(|e| Error::WrappedContext {
            wrapped: Box::new(e),
            context: context.to_string(),
        })
    }

    fn with_context<C, F>(self, context: F) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(Error::WrappedContext {
                wrapped: Box::new(error),
                context: context().to_string(),
            }
            .bt()),
        }
    }
}

impl<T> Context<T, Infallible> for Option<T> {
    fn context<C>(self, context: C) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
    {
        // Not using ok_or_else to save 2 useless frames off the captured
        // backtrace.
        match self {
            Some(ok) => Ok(ok),
            None => Err(Error::msg(context).bt()),
        }
    }

    fn with_context<C, F>(self, context: F) -> std::result::Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        match self {
            Some(v) => Ok(v),
            None => Err(Error::UnwrapNone.context(context()).bt()),
        }
    }
}