Skip to main content

fuel_graph/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! # fuel-graph
3//!
4//! Lazy computation graph for Phase 6 of the fuel ML framework.
5//!
6//! ## Role
7//!
8//! Phase 6 transitions fuel from eager execution to a lazy computation graph
9//! with an autonomous router. This crate holds the minimal vocabulary that
10//! makes that transition possible:
11//!
12//! - [`Op`] — a closed enum describing every operation that can appear in a
13//!   graph node. New ops are added here and consumed by every backend.
14//! - [`Graph`] — an arena of [`Node`]s. Nodes are immutable once added and
15//!   referenced by index. The arena grows; it never shrinks.
16//! - [`NodeHandle`] — a cheaply-cloneable handle to a `(graph, node_id)` pair.
17//!   Users build computations by calling methods on `NodeHandle`; each method
18//!   appends a node to the underlying graph and returns a new handle.
19//!
20//! Execution is deliberately not implemented here. A separate executor —
21//! `fuel-dispatch`'s `PipelinedExecutor`, dispatching to the per-backend
22//! kernels (`fuel-cpu-backend`, `fuel-cuda-backend`, `fuel-vulkan-backend`) —
23//! walks a `Graph` and produces concrete outputs. (The retired
24//! `fuel-reference-backend` textbook walker was the original executor; the
25//! CPU backend's bit-stable kernels are the correctness oracle now.)
26//!
27//! ## Scope of the MVP
28//!
29//! This is the first landing of the graph types. It is deliberately minimal:
30//!
31//! - Four float dtypes: `f32`, `f64`, `bf16`, `f16`. Integer dtypes will be
32//!   added alongside the reference backend's integer op coverage, not
33//!   speculatively here.
34//! - A small starter `Op` catalog: `Const`, `Add`, `Mul`, `MatMul`,
35//!   `Transpose`, `Relu`, `Sqr`, `Exp`. More ops are added as validation
36//!   tests for them land.
37//! - Unfused backward autograd: [`NodeHandle::backward`] walks the forward
38//!   graph in reverse, applies per-op gradient rules, and emits new graph
39//!   nodes for the gradient of every leaf. Fused backward and symbolic
40//!   graph rewriting are deferred to Phase 6d.
41//! - No fusion, no planner. Those belong to later sub-phases of Phase 6.
42//! - Thread-safe. The graph is wrapped in `Arc<RwLock<_>>` so that
43//!   `fuel_graph::NodeHandle` — the lazy build handle — and any handle that
44//!   embeds it are `Send + Sync`. Borrow access goes through
45//!   `read().unwrap()` / `write().unwrap()`.
46
47pub mod grad;
48pub mod jit;
49pub mod opt;
50pub mod registry;
51pub mod run;
52pub mod runtime_fused;
53pub mod scan;
54mod shape;
55
56#[doc(inline)]
57pub use run::{
58    FEWNESS_THRESHOLD, PickedRoute, Run, branch_density, branch_density_multi,
59    branches_in_topo_order, device_alternating_order, effective_roots, extract_runs,
60    extract_runs_multi, lower_picked_route, lower_picked_route_streaming, lower_run,
61    lower_runs_arm0, passes_fewness_gate, walk_picked_route_streaming,
62};
63
64pub use shape::primitive_shape;
65
66use crate::registry::{FusedOpId, FusedOpParams};
67use fuel_backend_contract::Storage;
68use fuel_ir::{DType, DeviceLocation, DynScalar, Layout, Scalar, Shape, SymId, probe::BackendId};
69use half::{bf16, f16};
70use std::collections::{HashMap, HashSet};
71use std::sync::{Arc, RwLock};
72
73/// Compute the topological order of every node reachable from `root`.
74///
75/// The returned order places inputs before the nodes that depend on them,
76/// so iterating the list and caching each result as you go guarantees every
77/// dependency is available when its dependents are computed. Uses an
78/// explicit stack iterative post-order DFS — no recursion, so arbitrarily
79/// deep graphs are safe.
80///
81/// This is the utility an executor walks to realize a tensor, and the
82/// utility [`NodeHandle::backward`] walks in reverse to construct the backward
83/// graph.
84pub fn topo_order(graph: &Graph, root: NodeId) -> Vec<NodeId> {
85    topo_order_multi(graph, &[root])
86}
87
88/// Compute the topological order of every node reachable from ANY of the
89/// given roots. Each node appears in the output exactly once; the order
90/// still satisfies the dependency-before-dependent property, so walking
91/// it and caching results as you go computes every input before any node
92/// that depends on it.
93///
94/// Used by the multi-output `realize_many` entry points in executors:
95/// KV-cached inference wants the per-step logits AND the updated K/V
96/// tensors for every layer as outputs of a single forward pass. Asking
97/// the executor for them via `topo_order_multi` walks the graph exactly
98/// once for the combined dependency set, then the executor reads each
99/// requested root out of the cache.
100pub fn topo_order_multi(graph: &Graph, roots: &[NodeId]) -> Vec<NodeId> {
101    let mut order = Vec::new();
102    let mut visited: HashSet<NodeId> = HashSet::new();
103    // Each stack entry is (node, processed). `processed = false` means
104    // "push children then revisit me"; `processed = true` means "all my
105    // children are already in `order`, add me now."
106    let mut stack: Vec<(NodeId, bool)> = roots.iter().map(|&r| (r, false)).collect();
107    while let Some((id, processed)) = stack.pop() {
108        if processed {
109            order.push(id);
110            continue;
111        }
112        if visited.contains(&id) {
113            continue;
114        }
115        visited.insert(id);
116        stack.push((id, true));
117        for &child in &graph.node(id).inputs {
118            if !visited.contains(&child) {
119                stack.push((child, false));
120            }
121        }
122    }
123    order
124}
125
126/// A node ID in the arena. Stable for the lifetime of the [`Graph`].
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
128pub struct NodeId(pub usize);
129
130/// Quantization block format for the `QMatMul` fused op
131/// ([`crate::registry::FusedOpParams::QMatMul`]). Matches the
132/// GGML/GGUF block layouts; each variant implies a fixed bytes-per-block
133/// and elements-per-block. Only variants for which a backend has a
134/// fused dequant-in-kernel matmul are currently exposed.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub enum QuantType {
137    /// 32-element block = 2 bytes f16 scale + 16 bytes packed u4 quants.
138    Q4_0,
139    /// 32-element block = 2 bytes f16 d + 2 bytes f16 m + 16 bytes packed u4 quants.
140    Q4_1,
141    /// 32-element block = 2 bytes f16 d + 4 bytes high-bit + 16 bytes packed u4 quants.
142    Q5_0,
143    /// 32-element block = 2 bytes f16 d + 2 bytes f16 m + 4 bytes high-bit + 16 bytes packed u4.
144    Q5_1,
145    /// 32-element block = 2 bytes f16 scale + 32 bytes i8 quants.
146    Q8_0,
147    /// 32-element block = 2 bytes f16 d + 2 bytes f16 s + 32 bytes i8 quants.
148    Q8_1,
149    /// 256-element super-block = scales + 64-byte 2-bit packed quants + 4 bytes f16 d/dmin.
150    Q2K,
151    /// 256-element super-block = hmask + 64-byte 2-bit packed quants + 12-byte scales + 2 bytes f16 d.
152    Q3K,
153    /// 256-element super-block = 2 bytes f16 d + 2 bytes f16 dmin +
154    /// 12 bytes of 6-bit-packed sub-block scales/mins + 128 bytes
155    /// of 4-bit-packed quants. GGML k-quant "medium" format.
156    #[expect(
157        non_camel_case_types,
158        reason = "GGML k-quant spec identifier (Q4_K_M = 4-bit K-quant Medium); matches the upstream / on-disk format name -- external convention over internal casing"
159    )]
160    Q4_K_M,
161    /// 256-element super-block = d + dmin + 12-byte scales + 32-byte hmask + 128-byte qs.
162    Q5K,
163    /// 256-element super-block = 128-byte ql + 64-byte qh + 16-byte i8 scales + 2 bytes f16 d.
164    Q6K,
165    /// llama.cpp `IQ4_NL`: 32-element block = 2 bytes f16 d + 16 bytes packed 4-bit indices into a
166    /// non-linear codebook. Storage and dequantization only: `QMatMul` dequantizes tile by tile and
167    /// multiplies in float (board 307: no quantized-by-quantized product).
168    Iq4Nl,
169    /// llama.cpp `IQ4_XS`: 256-element super-block = 2 bytes f16 d + 2 bytes high scale bits + 4 bytes
170    /// low scale bits + 128 bytes packed 4-bit codebook indices. Same float-only route as `Iq4Nl`.
171    Iq4Xs,
172    /// llama.cpp `IQ3_S`: 256-element super-block = 2 bytes f16 d + 64 bytes grid indices + 8 bytes
173    /// high bits + 32 bytes signs + 4 bytes sub-block scales. Same float-only route as `Iq4Nl`.
174    Iq3S,
175}
176
177impl QuantType {
178    /// Bytes per quantization block. Mirrors `std::mem::size_of::<BlockQ*>()`.
179    pub fn bytes_per_block(self) -> usize {
180        match self {
181            QuantType::Q4_0 => 18,
182            QuantType::Q4_1 => 20,
183            QuantType::Q5_0 => 22,
184            QuantType::Q5_1 => 24,
185            QuantType::Q8_0 => 34,
186            QuantType::Q8_1 => 36,
187            QuantType::Q2K => 84,
188            QuantType::Q3K => 110,
189            QuantType::Q4_K_M => 144,
190            QuantType::Q5K => 176,
191            QuantType::Q6K => 210,
192            QuantType::Iq4Nl => 18,
193            QuantType::Iq4Xs => 136,
194            QuantType::Iq3S => 110,
195        }
196    }
197    /// Elements per quantization block.
198    pub fn elements_per_block(self) -> usize {
199        match self {
200            QuantType::Q4_0
201            | QuantType::Q4_1
202            | QuantType::Q5_0
203            | QuantType::Q5_1
204            | QuantType::Q8_0
205            | QuantType::Q8_1
206            | QuantType::Iq4Nl => 32,
207            QuantType::Q2K
208            | QuantType::Q3K
209            | QuantType::Q4_K_M
210            | QuantType::Q5K
211            | QuantType::Q6K
212            | QuantType::Iq4Xs
213            | QuantType::Iq3S => 256,
214        }
215    }
216}
217
218/// Fill mode for [`Op::Pad`]. Only [`PadMode::Constant`] is
219/// implemented in the v1 cut; the other variants are accepted at
220/// the IR level so the enum is forward-stable, but the executor
221/// returns a clean error until they ship.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223pub enum PadMode {
224    /// Fill padded slots with the constant `value` parameter on
225    /// the [`Op::Pad`] variant.
226    Constant,
227    /// Reflect input around the padded edges (without repeating the
228    /// edge value). Not yet implemented.
229    Reflect,
230    /// Repeat the edge value into the padded region. Not yet
231    /// implemented.
232    Replicate,
233}
234
235/// The closed enum of operations a graph node can represent.
236///
237/// This is the API contract between the graph layer and every backend.
238/// Adding a new op means (1) adding a variant here, (2) teaching every
239/// backend how to execute it, and (3) teaching the reference backend how
240/// to compute its textbook answer.
241// EXHAUSTIVE-BY-DESIGN: `Op` is the CLOSED graph vocabulary; `OpKind`
242// (fuel-ir/src/dispatch.rs) is the deliberately-`#[non_exhaustive]` EXTENSIBLE
243// dispatch key. This marker makes that split — currently stated only in the doc
244// above — explicit and machine-checkable. The forcing functions are in-crate and
245// exhaustive: `op_short_name` (below) and the autograd `backward` match; adding a
246// variant fails to compile until both get an arm, which is the intended
247// enforcement (a new op with no gradient rule must not compile silently). Because
248// those live in fuel-graph, `-p fuel-graph` DOES catch a variant-add here (unlike
249// Scalar/DType, whose exhaustive consumers are cross-crate) — but do NOT add
250// `#[non_exhaustive]`: it would falsely advertise Op as open to external
251// consumers, contradicting the "teach every backend" contract. Downstream
252// dispatch/cost/telemetry consumers legitimately PARTIAL-match Op with sound
253// defaults (`None`/`Err`/skip); execution is gated by `op_to_op_kind` returning
254// `None`, so a new op is never silently mis-executed — that is why a plain
255// wildcard is correct THERE and forbidden in the two forcing functions above.
256// A THIRD in-crate forcing function joined the two above (GAP-076):
257// `destructive_input` (this file) is now exhaustive as well — a new primitive
258// must classify itself there (destructive → `Some(idx)`, otherwise `None`), and
259// a new *fused* op declares destructiveness as a mandatory `FusedOpEntry` field
260// that `Op::destructive_input` reads via `default_registry()`. The old
261// `_ => None` there silently read a new destructive op as non-destructive and
262// dropped its scheduler ordering edges (a data race); it is gone. See GAP-049
263// and GAP-076.
264#[derive(Debug, Clone, PartialEq)]
265pub enum Op {
266    // --- leaves ---
267    /// A concrete constant tensor — a leaf with no input nodes. The
268    /// realized bytes live in the graph's `storage_map` slot for this
269    /// node, populated at construction time. The executor's slot-first
270    /// dispatch returns the slot's `Arc<RwLock<Storage>>` directly.
271    /// (Phase 7.5 work item G2 retired the host-side `ConstData`
272    /// payload — the slot is the sole source of bytes.)
273    Const,
274
275    /// Position-index generator — a leaf (no inputs) producing the 1-D
276    /// `F32` sequence `[0.0, 1.0, …, (len-1) as f32]` of shape `[len]`.
277    /// The integer-valued positions are exact in `f32` for any realistic
278    /// sequence length (`< 2^24`). Reshaped + broadcast, it builds the
279    /// row/column indices that express causal / sliding-window masks and
280    /// alibi position biases (e.g. in FlashAttn's decomposition), so those
281    /// ops can lower to primitives instead of being opaque. Non-differentiable
282    /// (a constant generator; backward drops gradient like `Op::Const`).
283    Iota { len: usize },
284
285    // --- element-wise binary ---
286    /// Element-wise addition.
287    Add,
288    /// Element-wise subtraction (`a - b`).
289    Sub,
290    /// Element-wise multiplication.
291    Mul,
292    /// Element-wise division (`a / b`).
293    Div,
294
295    // --- element-wise unary ---
296    /// Element-wise negation (`-x`).
297    Neg,
298    /// Element-wise square (`x * x`).
299    Sqr,
300    /// Element-wise square root.
301    Sqrt,
302    /// Element-wise exponential (`e^x`).
303    Exp,
304    /// Element-wise natural logarithm.
305    Log,
306    /// Element-wise sine.
307    Sin,
308    /// Element-wise cosine.
309    Cos,
310    /// Element-wise hyperbolic tangent.
311    Tanh,
312    /// Element-wise logistic sigmoid.
313    Sigmoid,
314    /// SiLU activation (x · sigmoid(x)), also called Swish.
315    Silu,
316    /// GELU activation (tanh approximation).
317    GeluTanh,
318    /// Rectified linear unit (`max(0, x)`), element-wise.
319    Relu,
320    /// Heaviside step function: `1` where `x > 0`, `0` otherwise. Serves
321    /// as the derivative of `Relu` and as a building block for other
322    /// comparison-based gradients.
323    Step,
324    /// Element-wise reciprocal (`1 / x`). On `x = 0` the IEEE-754 result
325    /// is `±inf`; the kernel matches the obvious `1.0 / x` expression
326    /// rather than treating the input as an error.
327    Recip,
328    /// Element-wise absolute value (`|x|`).
329    Abs,
330
331    // --- in-place elementwise unary (Phase 1 of the in-place ops
332    // infrastructure landed 2026-05-30; see
333    // `docs/session-prompts/in-place-ops-infrastructure.md`) ---
334    //
335    // Each variant mutates input 0 in place; output aliases input 0.
336    // Pinned to run after every non-destructive reader of input 0 by
337    // `opt::derive_ordering` via the `destructive_input() -> Some(0)`
338    // contract. Backward integration deferred to Phase 4 (the
339    // mutation-safety pass auto-clones tape-tracked inputs).
340    /// In-place Relu: `x = max(0, x)`. Same semantics as `Op::Relu`,
341    /// mutates input 0. Not yet wired through autograd.
342    ReluInplace,
343    /// In-place Silu: `x = x * sigmoid(x)`. Same semantics as
344    /// `Op::Silu`, mutates input 0. Not yet wired through autograd.
345    SiluInplace,
346    /// In-place GeluTanh (tanh approximation): mutates input 0 with the
347    /// same formula as `Op::GeluTanh`. Its backward is the same as `Op::GeluTanh`'s.
348    GeluTanhInplace,
349    /// In-place Tanh: mutates input 0. Same semantics as `Op::Tanh`.
350    /// Not yet wired through autograd.
351    TanhInplace,
352    /// In-place Sigmoid: mutates input 0. Same semantics as
353    /// `Op::Sigmoid`. Not yet wired through autograd.
354    SigmoidInplace,
355
356    // --- in-place elementwise unary, dtype expansion + op family
357    // expansion shipped 2026-05-30. Same `destructive_input() ->
358    // Some(0)` contract as the 5 above; backward emitters mirror
359    // the non-inplace cousin (chain-rule formulas relying on
360    // Phase 4a view-aware ordering for pre-mutation reads of x).
361    /// In-place Neg: `x = -x`. Same semantics as `Op::Neg`.
362    NegInplace,
363    /// In-place Abs: `x = |x|`. Same semantics as `Op::Abs`.
364    AbsInplace,
365    /// In-place Sqr: `x = x²`. Same semantics as `Op::Sqr`.
366    SqrInplace,
367    /// In-place Sqrt: `x = √x`. Same semantics as `Op::Sqrt`.
368    SqrtInplace,
369    /// In-place Rsqrt: `x = 1/√x`. Same semantics as `Op::Rsqrt`.
370    RsqrtInplace,
371    /// In-place Recip: `x = 1/x`. Same semantics as `Op::Recip`.
372    RecipInplace,
373    /// In-place Exp: `x = exp(x)`. Same semantics as `Op::Exp`.
374    ExpInplace,
375    /// In-place Log: `x = ln(x)`. Same semantics as `Op::Log`.
376    LogInplace,
377    /// In-place Sin: `x = sin(x)`. Same semantics as `Op::Sin`.
378    SinInplace,
379    /// In-place Cos: `x = cos(x)`. Same semantics as `Op::Cos`.
380    CosInplace,
381    /// In-place Sign: `x = sign(x)`. Same semantics as `Op::Sign`.
382    /// Backward drops gradient (mirrors `Op::Sign`).
383    SignInplace,
384    /// In-place Floor: `x = ⌊x⌋`. Same semantics as `Op::Floor`.
385    /// Backward drops gradient (mirrors `Op::Floor`).
386    FloorInplace,
387    /// In-place Ceil: `x = ⌈x⌉`. Same semantics as `Op::Ceil`.
388    /// Backward drops gradient (mirrors `Op::Ceil`).
389    CeilInplace,
390    /// In-place Round: `x = round(x)`. Same semantics as `Op::Round`.
391    /// Backward drops gradient (mirrors `Op::Round`).
392    RoundInplace,
393    /// In-place Erf: `x = erf(x)`. Same semantics as `Op::Erf`.
394    ErfInplace,
395    /// In-place exact-GeLU: `x = 0.5 · x · (1 + erf(x/√2))`. Same
396    /// semantics as `Op::Gelu`.
397    GeluInplace,
398    /// In-place clamp: `x = clamp(x, min, max)`. Same semantics as
399    /// `Op::Clamp`. Backward gates the upstream by `(x ≥ min) ∧
400    /// (x ≤ max)` (mirrors Op::Clamp).
401    ClampInplace { min: f64, max: f64 },
402    /// In-place integer-power: `x = x.powi(exp)`. Same semantics as
403    /// `Op::PowI`. Backward emits `exp · upstream · x.powi(exp-1)`
404    /// (mirrors Op::PowI).
405    PowIInplace(i32),
406
407    // --- element-wise comparison (output is Bool mask) ---
408    /// Element-wise equality (`a == b`) producing a `Bool` mask: `1`
409    /// where the inputs are equal, `0` otherwise. Both operands must
410    /// share dtype and shape. NaN follows IEEE-754 (`NaN == NaN` is
411    /// false). Output dtype is always `Bool`, regardless of input dtype
412    /// — the binding-table key is `[T, T, Bool]`.
413    ///
414    /// Non-differentiable: backward returns `None` for both inputs
415    /// (registered via [`crate::grad::NoGradientBinaryRule`]).
416    Equal,
417    /// Element-wise inequality (`a != b`) producing a `Bool` mask: `1`
418    /// where unequal, `0` otherwise. Same shape/dtype contract as
419    /// [`Op::Equal`]. NaN follows IEEE-754 (`NaN != NaN` is true →
420    /// `1`). Non-differentiable.
421    Ne,
422    /// Element-wise strictly-less (`a < b`) producing a `Bool` mask: `1`
423    /// where lhs is strictly less than rhs, `0` otherwise. Same
424    /// shape/dtype contract as [`Op::Equal`]. NaN-on-either-side is
425    /// always `0` (IEEE-754 unordered comparison). Non-differentiable.
426    Lt,
427    /// Element-wise less-or-equal (`a <= b`) producing a `Bool` mask.
428    /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
429    /// is always `0`. Non-differentiable.
430    Le,
431    /// Element-wise strictly-greater (`a > b`) producing a `Bool` mask.
432    /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
433    /// is always `0`. Non-differentiable.
434    Gt,
435    /// Element-wise greater-or-equal (`a >= b`) producing a `Bool` mask.
436    /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
437    /// is always `0`. Non-differentiable. Final variant of the
438    /// comparison family (`Equal`, `Ne`, `Lt`, `Le`, `Gt`, `Ge`).
439    Ge,
440
441    // --- rounding family (non-differentiable) ---
442    /// Element-wise floor (`⌊x⌋`). Same dtype as input. Backward is
443    /// the zero distribution almost everywhere; gradient is dropped
444    /// silently (treated like `Op::Step`'s no-grad backward).
445    Floor,
446    /// Element-wise ceiling (`⌈x⌉`). Same dtype as input. Backward
447    /// drops gradient (mirrors [`Op::Floor`]).
448    Ceil,
449    /// Element-wise round-to-nearest with **banker's rounding**
450    /// (round-half-to-even, IEEE 754 roundeven). 0.5 → 0, 1.5 → 2,
451    /// 2.5 → 2 (NOT 3), 3.5 → 4. Matches NumPy/PyTorch defaults and
452    /// differs from C99 `round()` (half-away-from-zero) at exact ties.
453    /// Backward drops gradient (mirrors [`Op::Floor`]).
454    Round,
455    /// Element-wise sign (`-1` / `0` / `1`). `sign(0) = 0` by
456    /// subgradient convention (same convention `Op::Abs`'s backward
457    /// uses). Same dtype as input. Backward drops gradient (zero
458    /// almost everywhere).
459    Sign,
460    /// Element-wise Gauss error function (`erf(x)`). Same dtype as
461    /// input. Differentiable: `d/dx erf(x) = (2/√π) * exp(-x²)`.
462    /// Backward emitted via existing primitives (Sqr → Neg → Exp →
463    /// MulScalar(2/√π) → Mul(upstream, .)).
464    Erf,
465    /// Element-wise GELU activation, **exact erf formulation**:
466    /// `0.5 * x * (1 + erf(x/√2))`. Distinct from [`Op::GeluTanh`]
467    /// (tanh approximation, faster but slightly less accurate).
468    /// Differentiable; backward decomposes into the standard-normal
469    /// CDF + `x * φ(x)` (PDF) chain via primitives.
470    Gelu,
471    /// Element-wise binary power: `out = pow(a, b)` with real `b`.
472    /// Both inputs share dtype `T` and shape. Distinct from
473    /// [`Op::PowI`] (scalar `i32` exponent). Backward:
474    ///   d/da pow(a,b) = b * pow(a, b-1)
475    ///   d/db pow(a,b) = pow(a,b) * ln(a)
476    /// NaN follows IEEE-754 (`pow(-2, 0.5) = NaN`); ln of negative `a`
477    /// in the d/db term yields NaN at those positions.
478    Pow,
479    /// Element-wise reciprocal square root: `out = 1 / sqrt(x)`.
480    /// Same dtype as input. Distinct from `Sqrt` followed by `Recip`
481    /// (one op instead of two — saves a kernel launch and matches the
482    /// RMSNorm shape `x * rsqrt(mean(x²)+eps)`). Backward:
483    ///   d/dx (x^(-1/2)) = -0.5 * x^(-3/2) = -0.5 * y³
484    /// where `y = 1/sqrt(x)` is the forward output (so the chain
485    /// reuses the forward node and never touches `x` directly —
486    /// safe near x=0).
487    Rsqrt,
488    /// Element-wise remainder, **PyTorch convention**:
489    /// `out = a - floor(a / b) * b`. The result has the sign of the
490    /// divisor (matches `torch.remainder`). Distinct from C99 fmod
491    /// (sign of dividend) and `f32::rem_euclid` (always non-negative).
492    /// Backward:
493    ///   d/da = 1
494    ///   d/db = -floor(a/b)
495    Rem,
496    /// Reverse the order of elements along `dim`. Materializing op
497    /// (not a view) — `Layout`'s strides are `usize` so the
498    /// negative-stride view path isn't representable. Backward is
499    /// `Flip { dim }` itself (involutive).
500    Flip { dim: usize },
501    /// Cyclic shift along `dim` by `shift` positions (positive
502    /// shifts move elements to higher indices, wrapping around).
503    /// Materializing op. Backward is `Roll { dim, -shift }`.
504    Roll { dim: usize, shift: i64 },
505    /// Running cumulative sum along `dim`. Same shape as input.
506    /// Backward: reverse cumsum, expressed as `Flip → CumSum → Flip`
507    /// on the same dim using existing primitives.
508    CumSum { dim: usize },
509    /// Upper triangular: keep `x[..., i, j]` when `j >= i + diagonal`,
510    /// zero otherwise. Operates on the last two dims; leading dims
511    /// are batched. `diagonal` selects which diagonal is the cutoff
512    /// (0 = main diagonal, positive = above, negative = below).
513    /// Same shape as input. Backward is `Triu { diagonal }` itself
514    /// (linear mask; gradient passes through kept positions).
515    Triu { diagonal: i64 },
516    /// Lower triangular: keep `x[..., i, j]` when `j <= i + diagonal`,
517    /// zero otherwise. Operates on the last two dims; leading dims
518    /// are batched. `diagonal` selects which diagonal is the cutoff
519    /// (0 = main diagonal, positive = above, negative = below). The
520    /// canonical causal-attention mask is `tril(diagonal = 0)`.
521    /// Same shape as input. Backward is `Tril { diagonal }` itself.
522    Tril { diagonal: i64 },
523    /// Numerically-stable log-softmax along the last dimension:
524    /// `y_i = x_i - max_j(x_j) - log(sum_j exp(x_j - max_j(x_j)))`.
525    /// Same shape as input. Used in NLL / cross-entropy loss where
526    /// the explicit `log(softmax(x))` decomposition risks
527    /// over/underflow. Backward: see [`Op::LogSoftmaxLastDimBackward`].
528    LogSoftmaxLastDim,
529    /// MaskedFill: `out = where(mask != 0, value, x)`. Inputs:
530    /// `(x, mask)` where `mask` is U8 (any nonzero counts as "fill").
531    /// `value` is a scalar of the same dtype as `x`, stored on the
532    /// op. Output shape == x shape (mask must broadcast to x but the
533    /// simple-shape case requires identical shapes today). Backward
534    /// passes the upstream gradient through `x` at positions where
535    /// `mask == 0`, and contributes zero to `mask` (U8 anyway).
536    MaskedFill { value: Scalar },
537    /// Backward helper for [`Op::Pad`]. Single input is the upstream
538    /// gradient (shape == padded forward output shape); output is the
539    /// gradient with respect to the original input (shape ==
540    /// `in_shape`). Mode determines accumulation behavior:
541    /// - Constant: gradient at padded slots is dropped; the unpadded
542    ///   region is the input gradient.
543    /// - Reflect / Replicate: gradient accumulates from output
544    ///   positions that map back to each input position via the
545    ///   forward index function.
546    ///
547    /// Carries `in_shape` so the kernel can size the output tensor
548    /// (Op output shape isn't enough — Op::Pad's output shape
549    /// derivation needs reversing).
550    PadBackward {
551        in_shape: Shape,
552        padding: Vec<(usize, usize)>,
553        mode: PadMode,
554    },
555
556    /// Multi-dim Pad: per-axis `(before, after)` extends each
557    /// dimension. Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
558    /// `mode` selects the fill behavior; `value` is the fill
559    /// constant for [`PadMode::Constant`] (ignored otherwise — see
560    /// the variant docs for those modes).
561    ///
562    /// Multi-dim shape is the form PyTorch's `F.pad` exposes — a
563    /// single call covers e.g. "pad an image by 1 px on every side"
564    /// (`padding = [(0,0), (0,0), (1,1), (1,1)]` for `[N,C,H,W]`).
565    /// Single-dim is just the special case `padding[i] = (0,0)`
566    /// everywhere except one axis.
567    ///
568    /// Only Constant mode is fully implemented in v1. Reflect /
569    /// Replicate are accepted at the IR level but the executor
570    /// returns a clean "not yet implemented" error.
571    ///
572    /// Backward (Constant): slice along each padded axis to drop
573    /// the padded regions, restoring the input shape.
574    Pad {
575        padding: Vec<(usize, usize)>,
576        mode: PadMode,
577        value: f64,
578    },
579
580    // --- ternary select ---
581    /// Ternary select: `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
582    /// Inputs `(cond, a, b)`: `cond` is `U8` (typically the output of
583    /// a comparison op), `a` and `b` share dtype `T` and shape with
584    /// `cond`. Output dtype = `T`, shape = `cond.shape()`.
585    ///
586    /// Differentiable through `a` and `b` (gradient flows only to
587    /// the picked positions); `cond` is non-differentiable. Backward
588    /// rule expressed via `Op::Cast` + scalar arithmetic on existing
589    /// primitives, registered in [`crate::grad::WhereRule`].
590    Where,
591
592    // --- linear algebra and shape ---
593    /// Rank-2 matrix multiply.
594    MatMul,
595    /// Rank-2 transpose.
596    Transpose,
597    /// N-dimensional permutation. The parameter is the new axis order:
598    /// `out.shape[i] = in.shape[axes[i]]`. For a rank-3 input `[a, b, c]`
599    /// with `axes = [2, 0, 1]`, output shape is `[c, a, b]`. The axes
600    /// vector must be a permutation of `0..rank`.
601    Permute(Vec<usize>),
602
603    // --- dtype, shape, and broadcasting ---
604    /// Convert a tensor to a different dtype. The target dtype is carried
605    /// on the op itself; the source dtype is whatever the input node's
606    /// dtype is.
607    Cast(DType),
608    /// Broadcast a tensor to a larger shape. The input shape must be
609    /// broadcast-compatible with the target (NumPy rules). Used directly
610    /// by user code and as the backward rule for `SumAll`, `MeanAll`,
611    /// and axis reductions.
612    BroadcastTo(Shape),
613    /// Reshape a tensor to a new shape with the same element count. Data
614    /// is unchanged; only the shape metadata is replaced. Serves as the
615    /// general building block for arbitrary shape changes;
616    /// see [`Op::Unsqueeze`] for the metadata-only-view variant that
617    /// inserts a size-1 dim without ever materializing.
618    Reshape(Shape),
619    /// Materialize a contiguous copy of the input. Output shape and
620    /// dtype match the input; only the layout changes (strides become
621    /// row-major, start_offset becomes 0). Zero-cost when the input
622    /// is already contiguous + zero-offset — the executor adopts the
623    /// input's Storage Arc unchanged in that case.
624    ///
625    /// First-class IR concern so the optimizer (Phase 2.2) can insert
626    /// layout-fixups before kernels that don't advertise
627    /// `crate::KernelCaps::strided_input` without overloading
628    /// [`Op::Reshape`]'s "change shape" semantics. The executor
629    /// compiles this to the same `WorkItemKind::ContiguizeOf` arm
630    /// `Op::Reshape` uses; the only difference is that
631    /// `Op::Contiguize`'s output shape equals its input shape, so
632    /// the executor's element-count sanity check is trivial.
633    Contiguize,
634    /// Insert a size-1 dimension at position `dim` (range `0..=rank`,
635    /// where `dim == rank` appends to the end). Strictly more efficient
636    /// than [`Op::Reshape`] for the size-1-insertion case: this is a
637    /// metadata-only view op that shares bytes with its input via the
638    /// Layout side-table, so it preserves any upstream
639    /// strided/transposed/broadcast layout instead of triggering an
640    /// auto-Contiguize.
641    Unsqueeze { dim: usize },
642    /// Drop a size-1 dimension at position `dim` (range `0..rank`).
643    /// Inverse of [`Op::Unsqueeze`]; metadata-only view that shares
644    /// bytes with its input via the Layout side-table. Panics at build
645    /// time if the dim's size isn't 1 (mirrors Unsqueeze's bounds
646    /// check — graph-builder validation, not runtime).
647    Squeeze { dim: usize },
648    /// Sum-reduce a tensor to a smaller shape by summing along any dims
649    /// where the source was broadcast against the target. This is the
650    /// backward rule for `BroadcastTo` and is symmetric with it: both ops
651    /// are each other's gradient. For a source shape `[2, 3, 4]` being
652    /// reduced to `[3, 4]`, the sum is along dim 0; for `[2, 3, 4]` to
653    /// `[2, 1, 4]`, the sum is along dim 1 while keeping the dim.
654    ReduceSumTo(Shape),
655    /// Max-reduce a tensor to a smaller shape, the maximum-symmetric
656    /// counterpart of [`Op::ReduceSumTo`]. The target shape must be
657    /// broadcast-compatible into the source: along any axis where the
658    /// padded target is 1 (or absent), the input is reduced via max;
659    /// other axes carry through. Used by lowering rules (notably
660    /// SoftmaxLastDim's max-subtract step) and as the keepdim form of
661    /// per-axis max reductions.
662    ///
663    /// Backward through max-selection routes the upstream gradient
664    /// only to the argmax position, which requires holding onto the
665    /// original input and recomputing the argmax. PR 3.5 ships this
666    /// op without a backward rule (panics cleanly on `.backward()`,
667    /// matching `Op::ArgMaxDim`'s precedent); add the backward when a
668    /// real consumer needs it.
669    ReduceMaxTo(Shape),
670
671    // --- reductions to a scalar ---
672    /// Sum of every element, producing a rank-0 tensor.
673    SumAll,
674    /// Maximum of every element, producing a rank-0 tensor.
675    MaxAll,
676    /// Minimum of every element, producing a rank-0 tensor.
677    MinAll,
678    /// Arithmetic mean of every element, producing a rank-0 tensor.
679    MeanAll,
680
681    // --- reductions along one dimension ---
682    /// Sum along the given dim; the reduced dim is removed from the output.
683    SumDim(usize),
684    /// Max along the given dim; the reduced dim is removed from the output.
685    MaxDim(usize),
686    /// Min along the given dim; the reduced dim is removed from the output.
687    MinDim(usize),
688    /// Mean along the given dim; the reduced dim is removed from the output.
689    MeanDim(usize),
690
691    // --- compositions ---
692    //
693    // Phase 7.6 step 5 (2026-05-11): the per-fused-op primitive variants
694    // (SoftmaxLastDim, LayerNormLastDim { eps }, RmsNormLastDim { eps },
695    // Rope, Conv2D { … }, FusedLinear) plus the four backward-helper
696    // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
697    // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
698    // The closed primitive set no longer carries fused-op concepts;
699    // every fused op flows through `Op::Fused(FusedOpId, FusedOpParams)`.
700    // See `docs/fused-op-registry.md` for the migration record.
701
702    // Phase 7.6 step 5 (continued, 2026-05-11): `QMatMul {
703    // quant_type, k, n }` dropped — flows through
704    // `Op::Fused(QMATMUL, FusedOpParams::QMatMul { … })`.
705
706    // --- backward helpers ---
707    //
708    // Phase 7.6 step 5 (2026-05-11): the four migrated backward-helper
709    // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
710    // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
711    // They flow through `Op::Fused(FusedOpId, FusedOpParams)` per the
712    // registry split. LogSoftmaxLastDimBackward is the only remaining
713    // backward-helper primitive variant — its forward primitive
714    // (`Op::LogSoftmaxLastDim`, not in scope for step 5) hasn't migrated
715    // to the registry yet, so the backward stays primitive too.
716    //
717    /// LogSoftmax-last-dim backward. Inputs: `(forward_log_softmax_output,
718    /// upstream)`. Output: the gradient of the input to log-softmax.
719    /// Formula: `g - exp(y) * sum(g, last_dim, keepdim=true)` where
720    /// `y` is the forward log-softmax output and `g` is the upstream
721    /// gradient. Independent of `Op::SoftmaxLastDimBackward` because
722    /// the closed-form rule uses `exp(y) = softmax(x)` directly, not
723    /// the upstream-times-softmax composition.
724    LogSoftmaxLastDimBackward,
725
726    // --- integer-producing reductions ---
727    //
728    // These reduce a float tensor along one dim and emit a U32 tensor of
729    // indices. Non-differentiable — they exist for classification
730    // prediction and similar discrete workloads, not as part of any
731    // training graph. Backward panics cleanly if a user builds these
732    // inside a graph they then differentiate.
733    /// Index of the maximum along `dim`. Output: U32 with the reduced
734    /// dim removed.
735    ArgMaxDim(usize),
736    /// Index of the minimum along `dim`. Output: U32 with the reduced
737    /// dim removed.
738    ArgMinDim(usize),
739
740    // --- shape manipulation ---
741    /// Concatenate two tensors along `dim`. Both must have the same rank,
742    /// same dtype, and equal sizes in every dim except `dim`.
743    Concat { dim: usize },
744    /// Slice (narrow) a tensor along `dim`: take elements `[start, start+len)`.
745    /// Output shape: same as input but with `dim` shrunk to `len`.
746    Slice {
747        dim: usize,
748        start: usize,
749        len: usize,
750    },
751
752    // --- scalar-by-tensor ops ---
753    //
754    // These exist to avoid building a full-shape const just to add or
755    // multiply by a constant. Stored as f64 on the op and converted to
756    // the target dtype at realize time.
757    /// Add a scalar to every element.
758    AddScalar(f64),
759    /// Multiply every element by a scalar.
760    MulScalar(f64),
761    /// Raise every element to an integer power via repeated multiplication.
762    /// Works without an extra `log`/`exp` pair so it's numerically clean
763    /// for small integer exponents like squaring or cubing.
764    PowI(i32),
765    /// Clamp every element to the inclusive range `[min, max]`.
766    Clamp { min: f64, max: f64 },
767
768    // --- element-wise max/min between two tensors ---
769    /// Element-wise maximum of two tensors with matching shape.
770    Maximum,
771    /// Element-wise minimum of two tensors with matching shape.
772    Minimum,
773
774    // --- indexing ops ---
775    //
776    // These take a "data" tensor (floats) as their first input and an
777    // "index" tensor (integer) as their second input. The executor
778    // reads both operands from the cache, dispatches on the data
779    // tensor's dtype for the output, and uses the index tensor as-is.
780    /// Index-select along a single dimension with a 1-D index vector.
781    /// Output shape: same as input, but with `dim` replaced by
782    /// `indices.elem_count()`.
783    IndexSelect { dim: usize },
784    /// N-dimensional gather along `dim`. Output shape matches the index
785    /// tensor's shape. `out[..., k, ...] = data[..., indices[..., k, ...], ...]`
786    /// with `dim` being the position where the index value substitutes
787    /// for the output coordinate.
788    Gather { dim: usize },
789    /// Index-add: the backward of `IndexSelect`. Takes a base tensor,
790    /// a 1-D `U32` index vector, and a src tensor, and adds src to base
791    /// at the indexed positions along `dim`. `out[..., indices[i], ...] +=
792    /// src[..., i, ...]`. Non-indexed positions of base are copied
793    /// through unchanged. Works functionally (returns a new tensor).
794    IndexAdd { dim: usize },
795    /// Scatter-add: the backward of `Gather`. Takes a base tensor, an
796    /// N-D `U32` index tensor matching the src shape, and a src tensor,
797    /// and accumulates src values into base at positions given by
798    /// substituting `indices` at position `dim`. `out[p with dim ←
799    /// indices[p]] += src[p]`.
800    ScatterAdd { dim: usize },
801
802    /// Data-determined nonzero-index extraction — the keystone primitive
803    /// for **data-dependent dynamic shapes** (SSM autoregressive decode,
804    /// MoE sparse dispatch, MLA compressed-KV). Given an input value
805    /// tensor, produces the flat indices of its nonzero elements over a
806    /// **fixed-capacity buffer** plus the true runtime count, using the
807    /// multi-output bundle mechanism ([12-multi-output]):
808    ///
809    /// - slot 0 (primary): `indices`, shape `[capacity]`, dtype `U32`,
810    ///   where `capacity = input.elem_count()` (the static worst-case
811    ///   bound). The first `count` entries are the flat (row-major)
812    ///   indices of the input's nonzero elements in ascending order; the
813    ///   tail `[count..capacity]` is unspecified padding.
814    /// - slot 1: `count`, shape `[1]`, dtype `U32` — the number of
815    ///   nonzero elements found.
816    ///
817    /// "Nonzero" means `!= 0` in the input dtype's arithmetic (a `0.0`
818    /// float, an all-zero integer). The runtime `count` is published into
819    /// the per-pass [`SymEnv`](fuel_ir::SymEnv) under `count_sym` by the
820    /// executor *after* this op realizes, so downstream ops consume it as
821    /// a [`DynScalar::Sym`] / dynamic [`Extent`](fuel_ir::shape::Extent) —
822    /// the same host-scalar-extent pattern the KV-cache `cached_len`
823    /// uses. This is the **first op whose output length is determined by
824    /// its input data**, not by build-time shapes (the [`fuel_ir::symbol::SymEnv`] bind is
825    /// the one net-new realize-time seam). Primitive (in the base map by
826    /// construction — no `decompose`). Non-differentiable: discrete
827    /// indices, backward drops gradient like `Op::Gather`'s index path.
828    NonZeroIndices { count_sym: SymId },
829
830    // --- 2-D convolution + fused linear ---
831    //
832    // Phase 7.6 step 5 (2026-05-11): `Conv2D { stride, padding, groups }`
833    // and `FusedLinear` have been dropped — both flow through
834    // `Op::Fused(FusedOpId, FusedOpParams)` per the registry split.
835    // See `fuel-graph/src/registry/{conv2d,fused_linear}.rs` for the
836    // current entry shapes.
837
838    // Phase 7.6 step 5 (continued, 2026-05-11): `FlashAttn`,
839    // `PagedAttn`, and `ConvTranspose2D` dropped — all three flow
840    // through `Op::Fused(<id>, FusedOpParams::<variant>)` per the
841    // registry split. See `fuel-graph/src/registry/{flash_attn,
842    // paged_attn, conv_transpose_2d}.rs`.
843
844    // --- cross-device transfer ---
845    /// Copy the input tensor to a specific device. Source stays
846    /// resident (non-destructive). Source device is implicit from
847    /// `inputs[0]`'s current residency. When source and target
848    /// devices match, the backend is free to turn this into a cheap
849    /// clone; when they differ, the backend must actually transfer
850    /// the data (today: through a host buffer — Phase 3 has no P2P
851    /// fast path yet).
852    ///
853    /// Phase 3 of the unified scheduler work. The scheduler (Phase 4)
854    /// inserts these nodes automatically; users can also construct
855    /// them explicitly via `NodeHandle::copy_to_device`.
856    Copy { target: DeviceLocation },
857
858    /// Release the input tensor's device-resident storage. Produces a
859    /// zero-element marker output (NodeId placeholder for graph
860    /// bookkeeping; no meaningful data). After this op runs, the
861    /// input's device storage is gone; any subsequent reader of the
862    /// input's NodeId must get its data from a different path (a
863    /// sibling Copy output, or re-execution of the producer).
864    ///
865    /// Destructive on `inputs[0]`. Scheduler must pin `Op::Release`
866    /// to run after every other reader of its input via
867    /// [`opt::derive_ordering`].
868    ///
869    /// **Multi-output bundles** (Option C, Session 3): when
870    /// `inputs[0]` is a multi-output producer (its Storage carries a
871    /// [`fuel_ir::storage::OutputView`] bundle), the bundle
872    /// is the single eviction unit — the Release evicts the whole
873    /// bundle, not a single slot. `opt::collect_alias_set` treats
874    /// every `Op::View` of the producer as part of the producer's
875    /// alias set, so `derive_ordering` pins Release after every
876    /// reader of every View; the bundle drops only when the LAST
877    /// View consumer finishes. Op::ViewOwned consumers may run
878    /// freely after Release: their forward memcpy ran before the
879    /// Release fires (data-dep edge), and the resulting standalone
880    /// Storage is independent of the producer's bundle. Per-slot
881    /// eviction (releasing one slot's bytes while another stays
882    /// live) is intentionally a follow-up — v1 keeps the bundle as
883    /// a single unit.
884    Release,
885
886    /// Transfer the input tensor to `target` device, destroying the
887    /// source in the process. Semantically equivalent to
888    /// `Op::Copy { target }` followed by `Op::Release` on the source,
889    /// with the explicit guarantee that backends MAY fast-path the
890    /// fused form as a single transfer (e.g., a zero-copy handoff if
891    /// source and target are the same memory type).
892    ///
893    /// Output is a fresh tensor on `target` with the input's shape
894    /// and dtype. Destructive on `inputs[0]`; the scheduler pins this
895    /// op to run after every non-destructive reader of the source via
896    /// [`opt::derive_ordering`].
897    Move { target: DeviceLocation },
898
899    /// In-place scatter write: copies `inputs[1]`'s bytes into a
900    /// rectangular slab of `inputs[0]`'s storage, defined per-dim by
901    /// `ranges[i] = (start, end)`. After the op runs, `inputs[0]`'s
902    /// bytes inside the slab are replaced; bytes outside the slab are
903    /// untouched.
904    ///
905    /// Shape contract: `inputs[0].rank() == inputs[1].rank() ==
906    /// ranges.len()`. For each axis `i`,
907    /// `inputs[1].dims()[i] == ranges[i].1 - ranges[i].0`, and
908    /// `ranges[i].1 <= inputs[0].dims()[i]`. Dtypes must match.
909    ///
910    /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
911    /// Layout — same shape, same bytes, post-write. Consumers that
912    /// want a sub-extent of the destination compose an explicit
913    /// `Op::Slice` after the write (WriteSlice does not encode
914    /// post-write extents).
915    ///
916    /// Destructive on `inputs[0]` (the destination is consumed; only
917    /// the write op's output NodeId may read its bytes afterward).
918    /// Non-destructive on `inputs[1]`. The scheduler pins this op to
919    /// run after every other reader of the destination via
920    /// [`opt::derive_ordering`].
921    ///
922    /// Phase E.3.2: introduced to back persistent KV-cache writes
923    /// (`InferenceContext` + `KvCache`). Non-differentiable; backward
924    /// panics — KV-cache writes are forward-only.
925    ///
926    /// `dyn_offset` (Phase D symbolic extents): `None` ⇒ fully static
927    /// (`ranges` alone defines the slab — today's behavior). `Some((axis,
928    /// off))` ⇒ the destination start on `axis` is `off.resolve(env)`
929    /// against the per-pass [`fuel_ir::SymEnv`] at realize,
930    /// overriding `ranges[axis].0`; the slab width on that axis stays
931    /// `ranges[axis].1 - ranges[axis].0`. This is the input-determined
932    /// dynamic-offset path (a [`DynScalar`] over the one `SymEnv`),
933    /// distinct from [`Op::WriteSliceRotating`]'s data-determined
934    /// position (a tensor input). It backs the persistent decode
935    /// KV-cache write, whose append offset (`cached_len`) is a per-token
936    /// runtime value over a fixed-capacity buffer, so the graph
937    /// structure stays identical across tokens and the plan is reused.
938    /// Build a node with this set via [`NodeHandle::write_slice_dyn`]; the
939    /// resolved `offset + width` is bounds-checked against the
940    /// destination capacity at realize (a typed error, never a panic).
941    WriteSlice {
942        ranges: Vec<(usize, usize)>,
943        dyn_offset: Option<(usize, DynScalar)>,
944    },
945
946    /// Like [`Op::WriteSlice`] but the `axis` axis wraps modulo
947    /// `modulus`. The dynamic write position comes through `inputs[2]`
948    /// (rank-0 U32); at realize time the kernel computes
949    /// `start = position % modulus` and writes `inputs[1]` into
950    /// `inputs[0]` at the wrapped offset, splitting across the
951    /// boundary if `start + write_len > modulus`.
952    ///
953    /// Inputs:
954    /// - `inputs[0]`: destination tensor (the rotating buffer). Shape
955    ///   on `axis` is the full storage extent — typically equal to
956    ///   `modulus`.
957    /// - `inputs[1]`: source slice. Shape on non-rotating axes is the
958    ///   slab in `ranges`; shape on `axis` is the write length.
959    /// - `inputs[2]`: dynamic write position, rank-0 `U32`. Wrapped
960    ///   modulo `modulus` inside the kernel — callers pass the
961    ///   monotonic logical position (token index, etc.).
962    ///
963    /// `ranges` describes the destination slab on every axis. For the
964    /// rotating axis `axis`, `ranges[axis].0` is ignored (start is
965    /// dynamic) and `ranges[axis].1 - ranges[axis].0` must equal
966    /// `inputs[1].dims()[axis]` (the write length). For other axes
967    /// the same shape contract as `Op::WriteSlice` applies.
968    ///
969    /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
970    /// Layout, post-write. Destructive on `inputs[0]`; scheduled like
971    /// `Op::WriteSlice`.
972    ///
973    /// Phase C of the eager-NodeHandle retirement program. Backs
974    /// sliding-window KV caches (Mistral / Phi-3 sliding-window /
975    /// sliding-window Qwen). Non-differentiable; backward panics.
976    WriteSliceRotating {
977        axis: usize,
978        modulus: usize,
979        ranges: Vec<(usize, usize)>,
980    },
981
982    /// Like [`Op::WriteSlice`] but the start offset on `axis` is a
983    /// **device-resident** scalar read from `inputs[2]` (rank-0 `I64`)
984    /// at kernel-launch time — NOT host-resolved. This is the CUDA-
985    /// graph-capturable append: under capture, the offset buffer is
986    /// updated by a per-token fixed-address H2D memcpy before each
987    /// replay, so the captured graph is reused across decode steps
988    /// while the write lands at the live position. No modulo wrap
989    /// (unlike [`Op::WriteSliceRotating`]); the offset is the raw
990    /// start (`cached_len`).
991    ///
992    /// Inputs:
993    /// - `inputs[0]`: destination tensor (the fixed-capacity buffer).
994    /// - `inputs[1]`: source slab. Shape on non-`axis` axes is the slab
995    ///   in `ranges`; shape on `axis` is the write width.
996    /// - `inputs[2]`: device offset, rank-0 `I64` — the start on `axis`.
997    ///   Overrides `ranges[axis].0` (which is a placeholder ignored by
998    ///   the kernel).
999    ///
1000    /// `ranges` describes the destination slab on every axis. For the
1001    /// dynamic axis, `ranges[axis].0` is ignored (start is device-
1002    /// resident) and `ranges[axis].1 - ranges[axis].0` must equal
1003    /// `inputs[1].dims()[axis]` (the write width). For other axes the
1004    /// same shape contract as [`Op::WriteSlice`] applies.
1005    ///
1006    /// **Bounds are the caller's contract**: the kernel reads the start
1007    /// device-side and does NOT clamp (clamping would perturb the index
1008    /// math vs the static path). `offset + width <= dest_dims[axis]`
1009    /// must hold — guaranteed by the caller sizing the buffer's
1010    /// capacity (`DecodeSession` sizes `max_seq`).
1011    ///
1012    /// Output adopts `inputs[0]`'s Storage Arc + Layout, post-write.
1013    /// Destructive on `inputs[0]`; scheduled like `Op::WriteSlice`.
1014    /// Non-differentiable; backward panics.
1015    ///
1016    /// CapturedRun (the decode-latency lever, 2026-07): the device-
1017    /// resident-offset WriteSlice is form-B of baracuda's
1018    /// `write_slice_*_doff` launchers.
1019    WriteSliceDoff {
1020        axis: usize,
1021        ranges: Vec<(usize, usize)>,
1022    },
1023
1024    /// Allocate a fresh, zero-initialized Storage of the node's shape +
1025    /// dtype on `target`. Zero inputs — `Op::Alloc` is a *source* op
1026    /// like [`Op::Const`], but its bytes are computed (zeros) rather
1027    /// than seeded from the host.
1028    ///
1029    /// Bridge-retirement Phase 3a (post-9c). Replaces the per-device-
1030    /// location match in `fuel-tensor::inference_context::alloc_zeroed_on`
1031    /// with a graph-level node the optimizer can see + the executor's
1032    /// `WorkItemKind::Alloc` arm dispatches per-backend.
1033    ///
1034    /// **Device-handle requirement**: the executor's Alloc arm takes the
1035    /// per-backend handle (e.g. `&CudaDevice`, `&Arc<VulkanBackend>`)
1036    /// from the `DeviceRegistry` the caller hands the realize (a
1037    /// `*_with_devices` entry point of `fuel-dispatch`'s
1038    /// `PipelinedExecutor`). A non-CPU place nobody registered is a
1039    /// typed error at the Alloc.
1040    Alloc { target: DeviceLocation },
1041
1042    /// Fill the input tensor's bytes with zero, in place. Aliases
1043    /// `inputs[0]`'s Storage Arc as the output (same Storage; the
1044    /// bytes are mutated). Destructive on `inputs[0]` — readers of
1045    /// the input's NodeId after this op see post-fill bytes; new
1046    /// readers should use this op's NodeId.
1047    ///
1048    /// Bridge-retirement Phase 3a follow-up. Paired with
1049    /// [`Op::Alloc`] to give the architecturally clean "alloc uninit +
1050    /// explicit zero" pipeline. Backends with native device-side
1051    /// fills (CUDA `cuMemsetD8Async`, Vulkan `vkCmdFillBuffer`)
1052    /// dispatch through their kernels; CPU does an
1053    /// `Arc::make_mut`-style in-place memset.
1054    ///
1055    /// Future extension: an `Op::Fill { value: u8 }` (or `Scalar`)
1056    /// for non-zero patterns. ZeroFill is the only variant today
1057    /// because zero is the only init pattern any current caller
1058    /// needs.
1059    ZeroFill,
1060
1061    /// Phase 7.6 single-arm delegate to the open
1062    /// [`crate::registry::FusedOpRegistry`]. The id selects which
1063    /// fused op (SoftmaxLastDim, RmsNormLastDim, FlashAttn, ...) and
1064    /// the params carry per-instance data. The registry's metadata
1065    /// side (decompose, backward identity, shape/dtype rules) lives in
1066    /// `fuel-graph::registry`; the kernel side (per-backend `KernelRef`
1067    /// + cost + precision) lives in `fuel-storage::fused`.
1068    ///
1069    /// Adding a new fused op is one registry entry plus one kernel
1070    /// function per backend that supports it — no new `Op` variant.
1071    /// Step 3 of Phase 7.6 migrates SoftmaxLastDim through this arm
1072    /// as the proof of concept.
1073    Fused(FusedOpId, FusedOpParams),
1074
1075    /// Project one logical output out of a multi-output producer node.
1076    /// The producer's realized [`Storage`] carries a
1077    /// [`fuel_ir::storage::OutputView`] side-table; this op
1078    /// reads slot `slot` of that side-table and exposes its
1079    /// dtype/shape/layout as the View node's output.
1080    ///
1081    /// Single input (the multi-output producer). Output shares the
1082    /// producer's `Arc<RwLock<Storage>>` — zero bytes copied. The
1083    /// bundle stays alive as long as any View consumer (or the
1084    /// original producer handle) holds a clone.
1085    ///
1086    /// At graph-build time, the View's shape + dtype + layout come
1087    /// from the producer's slot specs recorded via
1088    /// [`Graph::set_output_views`]; building a `View { slot }` over a
1089    /// producer that hasn't declared slot specs is a typed error
1090    /// surfaced by the View-emitting builder helper. The bundle's
1091    /// per-slot dtype is independent of the producer node's own
1092    /// `Node::dtype` (which is the bundle's primary/slot-0 dtype).
1093    ///
1094    /// Backward (see `fuel-graph::grad`): the per-slot upstream
1095    /// gradient is scattered into a zero-filled bundle of the
1096    /// producer's overall byte shape; the producer's own backward
1097    /// rule then sees a "bundle gradient" as its upstream. Until a
1098    /// real multi-output op author exists (Session 2), the backward
1099    /// rule emits an [`Op::Const`] zero of the producer's primary
1100    /// shape — the scatter-into-slot primitive lands alongside the
1101    /// first differentiable multi-output op.
1102    View { slot: u32 },
1103
1104    /// Like [`Op::View`], but copies the slot's bytes into a fresh
1105    /// standalone Storage. Costs one allocation + one slot-sized
1106    /// memcpy; the producer's bundle Arc can drop as soon as every
1107    /// outstanding `Op::View` over the same producer also drops.
1108    ///
1109    /// The planner promotes a `View` to `ViewOwned` when a slot's
1110    /// liveness substantially outlasts the rest of the bundle (the
1111    /// classic case: Mamba's `last_state` slot retained across an
1112    /// autoregressive step while `y` is consumed immediately). v1
1113    /// emits the same dispatch shape as `Op::Copy` — backend-side it's
1114    /// `Copy` with byte offset + length pulled from the slot spec.
1115    ///
1116    /// Same shape/dtype/layout inference path as `View`; same backward
1117    /// shape too (the forward already paid the copy).
1118    ViewOwned { slot: u32 },
1119
1120    /// Multi-output autograd primitive (Option C, item 4). Takes two
1121    /// inputs:
1122    ///   - `inputs[0]`: a bundled tensor (typically a zero-bundle)
1123    ///   - `inputs[1]`: the slot's gradient
1124    ///
1125    /// Produces a new bundled tensor identical to `inputs[0]` except
1126    /// that slot `slot`'s byte range is overlaid by `inputs[1]`'s
1127    /// bytes. The output is alias-free with respect to `inputs[0]`
1128    /// (a fresh Storage with the new bytes) so multiple
1129    /// `ScatterIntoSlot` operations on the same `bundle_zero` chain
1130    /// sequentially without aliasing pitfalls.
1131    ///
1132    /// Emitted by `Op::View` / `Op::ViewOwned` backward rules: each
1133    /// View consumer scatters its upstream gradient into a fresh
1134    /// zero-bundle, then the producer's backward receives the
1135    /// composed bundle gradient as its upstream.
1136    ///
1137    /// **Status**: IR-level primitive only in this session. No CPU
1138    /// kernel registration yet. The production multi-output SSM ops
1139    /// (SelectiveScan, SsdChunkScan) are now differentiable via the
1140    /// Op::Scan Phase-2 `lower_scans_for_backward` pre-pass (decompose →
1141    /// `Op::Scan` → `unroll_scan` → node-general autograd), which lowers
1142    /// them to primitives BEFORE the reverse walk — so the autograd
1143    /// differentiates the unrolled `View` projections directly and never
1144    /// reaches a `ScatterIntoSlot` realization on the SSM path.
1145    ScatterIntoSlot { slot: u32 },
1146
1147    /// In-place multi-path (phi/merge) node — the arena representation
1148    /// of the optimized form's divergent-then-reconvergent routes.
1149    ///
1150    /// A `Branch` node's divergent "arms" are encoded in the node's
1151    /// existing `inputs: Vec<NodeId>`: each input is the *exit* of one
1152    /// candidate route, and `reconverge_at` names the explicit node at
1153    /// which those routes merge back into a single value. Because the
1154    /// multi-path structure is an arena fact rather than an overlay, it
1155    /// persists, compacts, graph-walks, and path-filters exactly like
1156    /// any other node; a graph with **zero** `Op::Branch` nodes is
1157    /// exactly today's single-route graph (back-compatible by
1158    /// construction).
1159    ///
1160    /// **Inert until PR-A1.** This variant is the PR-A0 scaffold: the
1161    /// closed `Op` enum carries it and every exhaustive match handles
1162    /// it, but nothing constructs it yet. The `open_branch` /
1163    /// `add_arm` / `finalize_branches` builders (with build-time
1164    /// validation: reconverge must descend from the diverge point, arms
1165    /// internally disjoint, cast-to-uniform at reconverge) land in
1166    /// PR-A1. Until then, accessors return a constant ("branch") and
1167    /// fallible paths (shape inference, autograd, lowering) return a
1168    /// descriptive `Err` rather than panicking.
1169    Branch { reconverge_at: NodeId },
1170
1171    /// Fuel's first sub-graph-carrying primitive: a bounded `lax.scan`-shaped
1172    /// recurrence `scan(body, init_carry, xs, consts) -> (final_carry, ys)`.
1173    ///
1174    /// The body is encoded in this node's own `inputs`, exactly like
1175    /// [`Op::Branch`]'s arms. Node layout:
1176    /// `inputs = [ init_carry_0..init_carry_{n_carries-1}, xs_0..xs_{n_xs-1},
1177    ///            consts..., body_new_carry_0..body_new_carry_{n_carries-1}, body_y ]`
1178    /// — the two body-exit NodeIds are the LAST two inputs, so `base_map_hash`,
1179    /// `topo_order_multi`, and reachability see the body for free. The body
1180    /// references `Op::ScanPlaceholder{Carry,0}` for the per-step carry and
1181    /// `Op::ScanPlaceholder{Elem,i}` for the per-step slice of `xs[i]`; consts
1182    /// are referenced by real NodeId. `n_carries` carries are threaded; the
1183    /// body references `ScanPlaceholder{Carry,k}` for carry `k` (GAP-303 —
1184    /// `n_carries = 1` is the v1 single-carry model).
1185    ///
1186    /// An optimization/verification-time node: it never reaches the executor
1187    /// un-lowered (the SSM decompose emits it, but the executor dispatches the
1188    /// fused op to its kernel; `unroll_scan` materializes primitives on demand
1189    /// for the verify oracle / kernel-absent fallback). No `LoweringRule`
1190    /// matches it — it is a terminal in the base map, which is correct: it IS
1191    /// the primitive. Always a 2-slot bundle (slot 0 = stacked `ys`, slot 1 =
1192    /// final carry). `early_exit` is Phase-2 (see [`ScanPredicate`]).
1193    Scan {
1194        /// How many recurrent carries this scan threads. Symmetric with
1195        /// `n_xs`: the carry NODES live in `inputs` (a positional block, see
1196        /// the layout above); this field is only their COUNT, exactly as
1197        /// `n_xs` is only the count of the `xs` block.
1198        ///
1199        /// GAP-303: `1` reproduces the v1 single-carry model exactly.
1200        n_carries: usize,
1201        n_xs: usize,
1202        bound: usize,
1203        emit: ScanEmit,
1204        early_exit: Option<ScanPredicate>,
1205    },
1206
1207    /// Inert body-hole leaf for [`Op::Scan`] (no inputs). Substituted by
1208    /// `unroll_scan` per step. Never directly realized.
1209    ScanPlaceholder { role: ScanRole, index: usize },
1210}
1211
1212/// What a [`Op::Scan`] emits. `All` stacks the per-step `body_y` over the
1213/// bound (slot 0); `Final` returns only the final carry (slot 1). The op
1214/// always produces the 2-slot bundle; `emit` selects the builder's default
1215/// projection. (`Op::Reduce` is `Op::Scan { emit: Final }` conceptually —
1216/// no separate variant.)
1217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1218pub enum ScanEmit {
1219    All,
1220    Final,
1221}
1222
1223/// Which body hole a [`Op::ScanPlaceholder`] stands in for. `Carry` is the
1224/// per-step recurrent carry (always index 0 in v1's single-carry model);
1225/// `Elem` is the per-step slice of `xs[index]`.
1226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1227pub enum ScanRole {
1228    Carry,
1229    Elem,
1230}
1231
1232/// Phase-1 placeholder for [`Op::Scan`]'s `early_exit` field. The FIELD is
1233/// defined now so the enum shape is final (one `03-ir` MAJOR bump); the
1234/// data-dependent early-exit MECHANISM is Phase 2. It is never `Some` on any
1235/// live Phase-1 path; if a realize/lowering path sees `Some`, that path
1236/// returns a clear `Err` (a surfaced Phase-2 gap), never a panic.
1237#[derive(Debug, Clone, PartialEq)]
1238pub struct ScanPredicate;
1239
1240impl Op {
1241    /// Index into `inputs` that this op destroys on execution. `None`
1242    /// means the op is non-destructive — every input remains readable
1243    /// after the op completes. Destructive ops need the scheduler to
1244    /// pin them to run after all other readers of the destroyed input,
1245    /// via ordering edges derived by [`opt::derive_ordering`].
1246    pub fn destructive_input(&self) -> Option<usize> {
1247        match self {
1248            // --- Destructive: the op writes through input 0 in place, so every
1249            // reader of input 0 (and its view-aliases) must be scheduled BEFORE
1250            // it (`opt::derive_ordering`). ---
1251            Op::Release
1252            | Op::Move { .. }
1253            | Op::WriteSlice { .. }
1254            | Op::WriteSliceRotating { .. }
1255            | Op::WriteSliceDoff { .. }
1256            | Op::ZeroFill
1257            | Op::ReluInplace
1258            | Op::SiluInplace
1259            | Op::GeluTanhInplace
1260            | Op::TanhInplace
1261            | Op::SigmoidInplace
1262            | Op::NegInplace
1263            | Op::AbsInplace
1264            | Op::SqrInplace
1265            | Op::SqrtInplace
1266            | Op::RsqrtInplace
1267            | Op::RecipInplace
1268            | Op::ExpInplace
1269            | Op::LogInplace
1270            | Op::SinInplace
1271            | Op::CosInplace
1272            | Op::SignInplace
1273            | Op::FloorInplace
1274            | Op::CeilInplace
1275            | Op::RoundInplace
1276            | Op::ErfInplace
1277            | Op::GeluInplace
1278            | Op::ClampInplace { .. }
1279            | Op::PowIInplace(_) => Some(0),
1280
1281            // --- Fused ops declare destructiveness as a MANDATORY
1282            // `FusedOpEntry::destructive_input` field (registry-declared, not
1283            // hardcoded here), so the fact lives with the thing and cannot drift.
1284            // Total by construction: a compile-time fused op cannot be registered
1285            // without the field; a runtime-registered fused id is not in the
1286            // compile-time registry and its region is a functional recipe (the
1287            // PatternNode grammar cannot express a destructive op), so `entry` is
1288            // `None` there and the op is non-destructive. GAP-076. ---
1289            Op::Fused(id, _) => crate::registry::default_registry()
1290                .entry(*id)
1291                .and_then(|e| e.destructive_input),
1292
1293            // --- Non-destructive primitives, listed EXHAUSTIVELY (no wildcard)
1294            // so adding an `Op` variant fails to compile here until it is
1295            // classified (`Op` is EXHAUSTIVE-BY-DESIGN — see the marker on
1296            // `enum Op`). A silent `_ => None` was the GAP-076 hazard: a future
1297            // destructive op would read as non-destructive and the scheduler
1298            // would drop its ordering edges — an intermittent data race that
1299            // points nowhere near this function. ---
1300            Op::Const
1301            | Op::Iota { .. }
1302            | Op::Add
1303            | Op::Sub
1304            | Op::Mul
1305            | Op::Div
1306            | Op::Neg
1307            | Op::Sqr
1308            | Op::Sqrt
1309            | Op::Exp
1310            | Op::Log
1311            | Op::Sin
1312            | Op::Cos
1313            | Op::Tanh
1314            | Op::Sigmoid
1315            | Op::Silu
1316            | Op::GeluTanh
1317            | Op::Relu
1318            | Op::Step
1319            | Op::Recip
1320            | Op::Abs
1321            | Op::Equal
1322            | Op::Ne
1323            | Op::Lt
1324            | Op::Le
1325            | Op::Gt
1326            | Op::Ge
1327            | Op::Where
1328            | Op::Floor
1329            | Op::Ceil
1330            | Op::Round
1331            | Op::Sign
1332            | Op::Erf
1333            | Op::Gelu
1334            | Op::Pow
1335            | Op::Rsqrt
1336            | Op::Rem
1337            | Op::Flip { .. }
1338            | Op::Roll { .. }
1339            | Op::CumSum { .. }
1340            | Op::Triu { .. }
1341            | Op::Tril { .. }
1342            | Op::LogSoftmaxLastDim
1343            | Op::MaskedFill { .. }
1344            | Op::Pad { .. }
1345            | Op::PadBackward { .. }
1346            | Op::MatMul
1347            | Op::Transpose
1348            | Op::Permute(_)
1349            | Op::Cast(_)
1350            | Op::BroadcastTo(_)
1351            | Op::Reshape(_)
1352            | Op::Contiguize
1353            | Op::Unsqueeze { .. }
1354            | Op::Squeeze { .. }
1355            | Op::ReduceSumTo(_)
1356            | Op::ReduceMaxTo(_)
1357            | Op::SumAll
1358            | Op::MaxAll
1359            | Op::MinAll
1360            | Op::MeanAll
1361            | Op::SumDim(_)
1362            | Op::MaxDim(_)
1363            | Op::MinDim(_)
1364            | Op::MeanDim(_)
1365            | Op::LogSoftmaxLastDimBackward
1366            | Op::ArgMaxDim(_)
1367            | Op::ArgMinDim(_)
1368            | Op::Concat { .. }
1369            | Op::Slice { .. }
1370            | Op::AddScalar(_)
1371            | Op::MulScalar(_)
1372            | Op::PowI(_)
1373            | Op::Clamp { .. }
1374            | Op::Maximum
1375            | Op::Minimum
1376            | Op::IndexSelect { .. }
1377            | Op::Gather { .. }
1378            | Op::IndexAdd { .. }
1379            | Op::ScatterAdd { .. }
1380            | Op::NonZeroIndices { .. }
1381            | Op::Copy { .. }
1382            | Op::Alloc { .. }
1383            | Op::View { .. }
1384            | Op::ViewOwned { .. }
1385            | Op::ScatterIntoSlot { .. }
1386            | Op::Branch { .. }
1387            | Op::Scan { .. }
1388            | Op::ScanPlaceholder { .. } => None,
1389        }
1390    }
1391
1392    /// Short human-readable name for this op — used by executor error
1393    /// messages to identify the offending graph node without spilling
1394    /// all of `Debug`'s field contents. Keeps panic messages one-liner-
1395    /// friendly while still telling you which kind of op blew up.
1396    pub fn short_name(&self) -> &'static str {
1397        op_short_name(self)
1398    }
1399
1400    /// Whether this op is a metadata-only view: its output shares bytes
1401    /// with its single input, reinterpreting them through new strides
1402    /// and/or offset. Executors realize these without allocating new
1403    /// storage — they wrap the input's Storage in a fresh Layout.
1404    ///
1405    /// Note that `Op::Reshape` is *not* a view op. Reshape produces
1406    /// contiguous output: zero-copy when its input is contiguous, but
1407    /// it materializes via auto-Contiguize when the input is strided.
1408    /// The other shape-altering ops in this set are always view-shaped
1409    /// regardless of the input layout.
1410    pub fn is_view_op(&self) -> bool {
1411        matches!(
1412            self,
1413            Op::Transpose
1414                | Op::Permute(_)
1415                | Op::BroadcastTo(_)
1416                | Op::Slice { .. }
1417                | Op::Unsqueeze { .. }
1418                | Op::Squeeze { .. }
1419                | Op::Flip { .. }
1420        )
1421    }
1422}
1423
1424/// Compute the output [`Layout`] of a metadata-only view op from its
1425/// input layout + the op variant. Returns `Err` if the op variant
1426/// isn't a view op (caller's contract — typically guarded by
1427/// [`Op::is_view_op`]).
1428///
1429/// Used by [`Graph::push`] to auto-populate the layout side-table for
1430/// view-op nodes at construction time, and by lowering rules in
1431/// [`opt`] that emit view-op nodes and need to populate the side-table
1432/// for them. The compiler reads the resulting layouts via
1433/// [`Graph::layout`] without re-deriving.
1434pub fn derive_view_output_layout(op: &Op, input_layout: &Layout) -> Result<Layout, fuel_ir::Error> {
1435    match op {
1436        Op::Transpose => {
1437            let rank = input_layout.shape().rank();
1438            if rank < 2 {
1439                return Err(fuel_ir::Error::Msg(format!(
1440                    "Op::Transpose requires rank >= 2, input rank is {rank}",
1441                ))
1442                .bt());
1443            }
1444            input_layout.transpose(rank - 2, rank - 1)
1445        }
1446        Op::Permute(axes) => input_layout.permute(axes),
1447        Op::BroadcastTo(target_shape) => input_layout.broadcast_as(target_shape.clone()),
1448        Op::Slice { dim, start, len } => input_layout.narrow(*dim, *start, *len),
1449        Op::Unsqueeze { dim } => input_layout.unsqueeze(*dim),
1450        Op::Squeeze { dim } => input_layout.squeeze(*dim),
1451        Op::Flip { dim } => input_layout.flip(*dim),
1452        other => Err(fuel_ir::Error::Msg(format!(
1453            "derive_view_output_layout called with non-view op {other:?}",
1454        ))
1455        .bt()),
1456    }
1457}
1458
1459fn op_short_name(op: &Op) -> &'static str {
1460    match op {
1461        Op::Const => "Const",
1462        Op::Iota { .. } => "Iota",
1463        Op::Add => "Add",
1464        Op::Sub => "Sub",
1465        Op::Mul => "Mul",
1466        Op::Div => "Div",
1467        Op::Neg => "Neg",
1468        Op::Sqr => "Sqr",
1469        Op::Sqrt => "Sqrt",
1470        Op::Exp => "Exp",
1471        Op::Log => "Log",
1472        Op::Sin => "Sin",
1473        Op::Cos => "Cos",
1474        Op::Tanh => "Tanh",
1475        Op::Sigmoid => "Sigmoid",
1476        Op::Silu => "Silu",
1477        Op::GeluTanh => "GeluTanh",
1478        Op::Relu => "Relu",
1479        Op::Step => "Step",
1480        Op::Recip => "Recip",
1481        Op::Abs => "Abs",
1482        Op::ReluInplace => "ReluInplace",
1483        Op::SiluInplace => "SiluInplace",
1484        Op::GeluTanhInplace => "GeluTanhInplace",
1485        Op::TanhInplace => "TanhInplace",
1486        Op::SigmoidInplace => "SigmoidInplace",
1487        Op::NegInplace => "NegInplace",
1488        Op::AbsInplace => "AbsInplace",
1489        Op::SqrInplace => "SqrInplace",
1490        Op::SqrtInplace => "SqrtInplace",
1491        Op::RsqrtInplace => "RsqrtInplace",
1492        Op::RecipInplace => "RecipInplace",
1493        Op::ExpInplace => "ExpInplace",
1494        Op::LogInplace => "LogInplace",
1495        Op::SinInplace => "SinInplace",
1496        Op::CosInplace => "CosInplace",
1497        Op::SignInplace => "SignInplace",
1498        Op::FloorInplace => "FloorInplace",
1499        Op::CeilInplace => "CeilInplace",
1500        Op::RoundInplace => "RoundInplace",
1501        Op::ErfInplace => "ErfInplace",
1502        Op::GeluInplace => "GeluInplace",
1503        Op::ClampInplace { .. } => "ClampInplace",
1504        Op::PowIInplace(_) => "PowIInplace",
1505        Op::Equal => "Equal",
1506        Op::Ne => "Ne",
1507        Op::Lt => "Lt",
1508        Op::Le => "Le",
1509        Op::Gt => "Gt",
1510        Op::Ge => "Ge",
1511        Op::Where => "Where",
1512        Op::Floor => "Floor",
1513        Op::Ceil => "Ceil",
1514        Op::Round => "Round",
1515        Op::Sign => "Sign",
1516        Op::Erf => "Erf",
1517        Op::Gelu => "Gelu",
1518        Op::Pow => "Pow",
1519        Op::Rsqrt => "Rsqrt",
1520        Op::Rem => "Rem",
1521        Op::Flip { .. } => "Flip",
1522        Op::Roll { .. } => "Roll",
1523        Op::CumSum { .. } => "CumSum",
1524        Op::Triu { .. } => "Triu",
1525        Op::Tril { .. } => "Tril",
1526        Op::LogSoftmaxLastDim => "LogSoftmaxLastDim",
1527        Op::MaskedFill { .. } => "MaskedFill",
1528        Op::Pad { .. } => "Pad",
1529        Op::PadBackward { .. } => "PadBackward",
1530        Op::MatMul => "MatMul",
1531        Op::Transpose => "Transpose",
1532        Op::Permute(_) => "Permute",
1533        Op::Cast(_) => "Cast",
1534        Op::BroadcastTo(_) => "BroadcastTo",
1535        Op::Reshape(_) => "Reshape",
1536        Op::Contiguize => "Contiguize",
1537        Op::Unsqueeze { .. } => "Unsqueeze",
1538        Op::Squeeze { .. } => "Squeeze",
1539        Op::ReduceSumTo(_) => "ReduceSumTo",
1540        Op::ReduceMaxTo(_) => "ReduceMaxTo",
1541        Op::SumAll => "SumAll",
1542        Op::MaxAll => "MaxAll",
1543        Op::MinAll => "MinAll",
1544        Op::MeanAll => "MeanAll",
1545        Op::SumDim(_) => "SumDim",
1546        Op::MaxDim(_) => "MaxDim",
1547        Op::MinDim(_) => "MinDim",
1548        Op::MeanDim(_) => "MeanDim",
1549        Op::LogSoftmaxLastDimBackward => "LogSoftmaxLastDimBackward",
1550        Op::ArgMaxDim(_) => "ArgMaxDim",
1551        Op::ArgMinDim(_) => "ArgMinDim",
1552        Op::Concat { .. } => "Concat",
1553        Op::Slice { .. } => "Slice",
1554        Op::AddScalar(_) => "AddScalar",
1555        Op::MulScalar(_) => "MulScalar",
1556        Op::PowI(_) => "PowI",
1557        Op::Clamp { .. } => "Clamp",
1558        Op::Maximum => "Maximum",
1559        Op::Minimum => "Minimum",
1560        Op::IndexSelect { .. } => "IndexSelect",
1561        Op::Gather { .. } => "Gather",
1562        Op::IndexAdd { .. } => "IndexAdd",
1563        Op::ScatterAdd { .. } => "ScatterAdd",
1564        Op::NonZeroIndices { .. } => "NonZeroIndices",
1565        Op::Copy { .. } => "Copy",
1566        Op::Release => "Release",
1567        Op::Move { .. } => "Move",
1568        Op::WriteSlice { .. } => "WriteSlice",
1569        Op::WriteSliceRotating { .. } => "WriteSliceRotating",
1570        Op::WriteSliceDoff { .. } => "WriteSliceDoff",
1571        Op::Alloc { .. } => "Alloc",
1572        Op::ZeroFill => "ZeroFill",
1573        // Phase 7.6: registry-extended fused ops. Step 3 wires per-id
1574        // names through a static lookup; until then, all fused ops
1575        // share one short name. Distinguishing in error messages is
1576        // future work — `id` is in the Debug repr.
1577        Op::Fused(_, _) => "Fused",
1578        Op::View { .. } => "View",
1579        Op::ViewOwned { .. } => "ViewOwned",
1580        Op::ScatterIntoSlot { .. } => "ScatterIntoSlot",
1581        // PR-A0 inert scaffold (the multi-path phi/merge node).
1582        Op::Branch { .. } => "Branch",
1583        Op::Scan { .. } => "Scan",
1584        Op::ScanPlaceholder { .. } => "ScanPlaceholder",
1585    }
1586}
1587
1588/// G2 helper: element count of a `HostBuffer`. Used by NodeHandle's
1589/// constructors to validate that the supplied data matches the
1590/// declared shape's `elem_count` before allocating Storage.
1591fn host_buffer_elem_count(buf: &fuel_ir::HostBuffer) -> usize {
1592    use fuel_ir::HostBuffer;
1593    match buf {
1594        HostBuffer::F32(v) => v.len(),
1595        HostBuffer::F64(v) => v.len(),
1596        HostBuffer::BF16(v) => v.len(),
1597        HostBuffer::F16(v) => v.len(),
1598        HostBuffer::U8(v) => v.len(),
1599        HostBuffer::U32(v) => v.len(),
1600        HostBuffer::I64(v) => v.len(),
1601        other => panic!(
1602            "NodeHandle::from_*: unsupported host-buffer dtype {:?}",
1603            other.dtype(),
1604        ),
1605    }
1606}
1607
1608/// A single node in the graph: an operation and the IDs of its inputs.
1609/// The node also caches its output shape and dtype so downstream builders
1610/// can validate without walking back through the graph.
1611#[derive(Debug, Clone)]
1612pub struct Node {
1613    pub op: Op,
1614    pub inputs: Vec<NodeId>,
1615    pub shape: Shape,
1616    pub dtype: DType,
1617}
1618
1619/// How a node's storage is shared and how long it lives — its **storage
1620/// class** ([03-ir §"Storage classes and sessions"]). A node is a
1621/// structural fact and does not need storage to exist; when storage *is*
1622/// attached, its class governs sharing and lifetime so one optimized graph
1623/// can serve many concurrent sessions (weights shared, session state
1624/// `SessionId`-keyed, activations per-realize scratch).
1625///
1626/// The class is **inferred from the op** ([`infer_storage_class`]) with an
1627/// **explicit override** recorded in the graph's `storage_class` side-table
1628/// — e.g. KV-cache placeholder `Op::Const`s, which are session state, not
1629/// shared weights.
1630///
1631/// Phase D substrate (PR-D1): the classification is recorded but not yet
1632/// consumed by realize. Session keying (D2) and the persistent decode graph
1633/// (D3–D5) build on it.
1634#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1635pub enum StorageClass {
1636    /// Weights / constants: one storage for the whole model, identical
1637    /// across all sessions; keyed by `NodeId`. The op-inferred default for
1638    /// `Op::Const`.
1639    Shared,
1640    /// Per-session durable buffers (KV-caches + explicit cache-write
1641    /// targets): one storage per session, keyed by `(NodeId, SessionId)`.
1642    /// The op-inferred default for the in-place cache-write ops
1643    /// (`Op::WriteSlice` / `Op::WriteSliceRotating`); KV-cache placeholder
1644    /// `Op::Const`s take it via an explicit override.
1645    SessionState,
1646    /// Activations / scratch: ephemeral, allocated per realize and freed
1647    /// after use; never persisted. The op-inferred default for everything
1648    /// else. A transient value may cross devices mid-realize (a D2D
1649    /// `Op::Copy`) but never crosses to disk.
1650    Transient,
1651}
1652
1653/// The op-inferred storage class for a node, **before** any explicit
1654/// override (see [`StorageClass`] and [`Graph::storage_class`]):
1655/// - `Op::Const` → [`StorageClass::Shared`] (weights);
1656/// - `Op::WriteSlice` / `Op::WriteSliceRotating` → [`StorageClass::SessionState`]
1657///   (they write into a per-session durable buffer);
1658/// - everything else → [`StorageClass::Transient`].
1659pub fn infer_storage_class(op: &Op) -> StorageClass {
1660    match op {
1661        Op::Const => StorageClass::Shared,
1662        Op::WriteSlice { .. } | Op::WriteSliceRotating { .. } | Op::WriteSliceDoff { .. } => {
1663            StorageClass::SessionState
1664        }
1665        _ => StorageClass::Transient,
1666    }
1667}
1668
1669/// Identity of the shared host array a weight `Const` was built from: the data pointer, the element
1670/// count and the dtype of the `Arc<[T]>` its constructor was handed.
1671///
1672/// Two `Const`s on different graphs built from the SAME `Arc` have the same key, which is what lets a
1673/// caller that holds realized device copies of weights recognise a weight it has already uploaded
1674/// (ROADMAP row 172). The key alone proves nothing about liveness (a freed allocation's address can be
1675/// reused): use [`ConstOrigin::pin`], which succeeds only while the source `Arc` is alive, and keep the
1676/// returned pin for as long as the key is trusted.
1677#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1678pub struct ConstOriginKey {
1679    /// Address of the first element of the source array.
1680    pub ptr: usize,
1681    /// Element count of the source array.
1682    pub len: usize,
1683    /// Element dtype of the source array.
1684    pub dtype: DType,
1685}
1686
1687/// A weak handle on the shared host array a `Const` was built from (see [`ConstOriginKey`]).
1688///
1689/// Holds only a `Weak`, so recording an origin never extends the array's life: a per-call array
1690/// (a token-id table, a RoPE table, a mask) has no live source by the time anyone asks and
1691/// [`Self::pin`] returns `None` for it, while a model weight, still held by the model, pins.
1692#[derive(Clone)]
1693pub struct ConstOrigin {
1694    key: ConstOriginKey,
1695    pin: Arc<dyn Fn() -> Option<Box<dyn std::any::Any + Send + Sync>> + Send + Sync>,
1696    strong: Arc<dyn Fn() -> usize + Send + Sync>,
1697}
1698
1699impl ConstOrigin {
1700    fn of<T: Send + Sync + 'static>(data: &Arc<[T]>, dtype: DType) -> Self {
1701        let weak = Arc::downgrade(data);
1702        let counter = weak.clone();
1703        Self {
1704            key: ConstOriginKey {
1705                ptr: data.as_ptr() as usize,
1706                len: data.len(),
1707                dtype,
1708            },
1709            pin: Arc::new(move || {
1710                weak.upgrade()
1711                    .map(|a| Box::new(a) as Box<dyn std::any::Any + Send + Sync>)
1712            }),
1713            strong: Arc::new(move || counter.strong_count()),
1714        }
1715    }
1716
1717    /// The identity of the source array.
1718    pub fn key(&self) -> ConstOriginKey {
1719        self.key
1720    }
1721
1722    /// A strong handle that keeps the source array alive, or `None` if it is already gone (the
1723    /// `Const` was built from a per-call array). Hold it for as long as [`Self::key`] is trusted.
1724    pub fn pin(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
1725        (self.pin)()
1726    }
1727
1728    /// How many strong handles the source array has right now, pins included. A holder of one pin
1729    /// sees `1` when nothing else (no model) holds the array any more, which is its cue to let go.
1730    pub fn strong_count(&self) -> usize {
1731        (self.strong)()
1732    }
1733}
1734
1735impl std::fmt::Debug for ConstOrigin {
1736    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1737        f.debug_struct("ConstOrigin")
1738            .field("key", &self.key)
1739            .finish_non_exhaustive()
1740    }
1741}
1742
1743/// The graph arena. Stores every node added during a computation-building
1744/// session. Nodes are append-only and indexed by [`NodeId`].
1745///
1746/// Placement metadata (`DeviceLocation` per node) lives in a side-table
1747/// so existing `Node { ... }` construction sites don't need to be
1748/// modified. This is the Phase-1 shape: placements are opt-in, inert
1749/// hints that the executor may validate but does not yet act on.
1750/// `Default` is implemented **manually** (not derived) so that every graph —
1751/// however it is created — mints a fresh [`GraphId`] from the monotonic
1752/// counter. A derived `Default` would hand out a zeroed id, so two
1753/// `Graph::default()` graphs would claim the same identity and affinity
1754/// diagnostics would report nonsense.
1755#[derive(Debug)]
1756pub struct Graph {
1757    nodes: Vec<Node>,
1758    /// Sparse map of per-node placement hints. Entries are only present
1759    /// when explicitly set via [`Graph::set_placement`]. Absent entries
1760    /// mean "inherit from the executor's default device."
1761    placements: HashMap<NodeId, DeviceLocation>,
1762    /// NodeIds the executor must schedule even when their outputs are
1763    /// unreachable from the user's roots. Populated by graph-mutating
1764    /// rules that emit side-effecting ops (e.g. `Op::Release` for
1765    /// residency eviction). See [`Graph::add_side_effect_root`].
1766    side_effect_roots: Vec<NodeId>,
1767    /// Phase 7.5 work item G: graph-owned realized-storage map.
1768    /// Slots are populated for `Op::Const` leaves at construction
1769    /// time and for non-leaf nodes at realize time. Values are
1770    /// `Arc<RwLock<Storage>>` so consumers (NodeHandle handles, executor
1771    /// caches, residency machinery) share Storage cheaply via Arc
1772    /// clones. Lifetime is tied to the Graph; when the graph drops,
1773    /// any slots not held by external Arc clones are freed.
1774    storage_map: HashMap<NodeId, Arc<RwLock<Storage>>>,
1775    /// Phase 7.5 storage-unification B2: per-node dispatch
1776    /// resolution result. Set by the dispatch resolver (Phase B3+)
1777    /// when DAG construction picks which backend will execute the
1778    /// node's op given its inputs' dtype + residency. Sparse like
1779    /// `placements`: absent entries mean "not yet resolved" and the
1780    /// executor falls back to per-op-eval dispatch (today's
1781    /// behavior). After full migration, every Node has an entry.
1782    ///
1783    /// Note: this is a *side-table*, not a `Node` field, so that
1784    /// existing `Node { ... }` constructors don't need to change
1785    /// during the migration. Mirrors the `placements` pattern.
1786    target_backends: HashMap<NodeId, BackendId>,
1787    /// Phase 7.5 storage-unification — Layout-on-Node side-table.
1788    /// Sparse: every Node has a logical [`Layout`], but for the
1789    /// common case (contiguous result of a kernel) we don't store
1790    /// it explicitly — [`Graph::layout`] returns
1791    /// `Layout::contiguous(node.shape)` as the fallback. Entries
1792    /// are written here exclusively by metadata-only view ops
1793    /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1794    /// 0-copy `Op::Reshape`) where the output is a strided view
1795    /// over an upstream node's Storage.
1796    ///
1797    /// Coherence rule: if `layouts[id]` is present, its
1798    /// `shape()` must equal `nodes[id].shape` — Layout adds
1799    /// strides + offset; the visible shape is identical.
1800    layouts: HashMap<NodeId, Layout>,
1801    /// Per-node multi-output side-table. Populated only for nodes
1802    /// whose op produces a bundled [`Storage`] with N>1 logical
1803    /// outputs (Session 1 of the multi-output-nodes design — see
1804    /// [`OutputView`](fuel_ir::storage::OutputView)). `Op::View`
1805    /// and `Op::ViewOwned` builders read this side-table to derive
1806    /// their own output shape/dtype/layout from the producer's
1807    /// declared slot specs.
1808    ///
1809    /// Coherence rule: when present, slot 0's `dtype` must equal the
1810    /// producer node's `Node::dtype` (which the multi-output op's
1811    /// allocator also uses as the inner backend storage's dtype).
1812    /// The producer's `Node::shape` reflects slot 0's logical shape
1813    /// for back-compat with single-output infrastructure; non-primary
1814    /// slots may have unrelated shapes and dtypes.
1815    node_output_views: HashMap<NodeId, Arc<[fuel_ir::storage::OutputView]>>,
1816    /// Per-node **storage-class override** ([`StorageClass`]). Sparse:
1817    /// entries are present only where the class differs from the op-inferred
1818    /// default ([`infer_storage_class`]) — chiefly KV-cache placeholder
1819    /// `Op::Const`s, which are session state, not shared weights.
1820    /// [`Graph::storage_class`] returns the override if present, else the
1821    /// inferred default, so every node has a well-defined class.
1822    /// Phase D substrate (PR-D1); not yet consumed by realize.
1823    storage_class: HashMap<NodeId, StorageClass>,
1824    /// Per-node **data-determined matmul row count** — the sparse-MoE
1825    /// capacity-buffer support. Present only on `Op::MatMul` nodes whose
1826    /// M (row count) is a runtime value: the node's `Node::shape` carries
1827    /// the row **capacity**, and this side-table carries the [`DynScalar`]
1828    /// that resolves (at compile if input-determined, else at execute from
1829    /// the producer-bound `SymEnv`) to how many rows to actually compute.
1830    /// Absent ⇒ a normal, static-M matmul. A side-table (not an `Op::MatMul`
1831    /// field) so the dense-matmul enum + its every match arm stay untouched.
1832    node_matmul_row_count: HashMap<NodeId, DynScalar>,
1833    /// Per-`Const` source identity ([`ConstOrigin`]), recorded by the `Arc`-taking `Const` constructors
1834    /// (`from_f32`, `const_u32_like`, and their dtype and `_on` siblings). Sparse: a `Const` built from
1835    /// an owned buffer has none. Weak: it never keeps a source array alive.
1836    const_origins: HashMap<NodeId, ConstOrigin>,
1837    /// Process-unique identity for this graph, minted at construction.
1838    ///
1839    /// Tensors are **graph-affine**: every binary op requires both operands to
1840    /// live on the same `Graph`, checked by `Arc::ptr_eq`. Pointer identity is
1841    /// the right *check* but a useless thing to *report* — so each graph also
1842    /// carries a small monotonic id, letting an affinity failure say "lhs is on
1843    /// graph #1, rhs on graph #2" instead of only that the two differ. That
1844    /// turns an abstract invariant into an observation the caller can act on:
1845    /// *you made two graphs.*
1846    id: GraphId,
1847}
1848
1849/// Process-unique identifier for a [`Graph`], minted monotonically by
1850/// [`Graph::new`]. Exists so affinity diagnostics can name *which* graphs
1851/// disagree; it is not a stable address, an index, or anything to persist.
1852#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1853pub struct GraphId(u64);
1854
1855impl std::fmt::Display for GraphId {
1856    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1857        write!(f, "{}", self.0)
1858    }
1859}
1860
1861/// Monotonic source for [`GraphId`]. Starts at 1 so `#0` never appears and a
1862/// zeroed/defaulted id is visibly wrong.
1863static NEXT_GRAPH_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1864
1865impl Default for Graph {
1866    fn default() -> Self {
1867        Self::new()
1868    }
1869}
1870
1871impl Graph {
1872    /// Create an empty graph.
1873    pub fn new() -> Self {
1874        Self {
1875            id: GraphId(NEXT_GRAPH_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)),
1876            nodes: Vec::new(),
1877            placements: HashMap::new(),
1878            side_effect_roots: Vec::new(),
1879            storage_map: HashMap::new(),
1880            target_backends: HashMap::new(),
1881            layouts: HashMap::new(),
1882            node_output_views: HashMap::new(),
1883            storage_class: HashMap::new(),
1884            node_matmul_row_count: HashMap::new(),
1885            const_origins: HashMap::new(),
1886        }
1887    }
1888
1889    /// This graph's process-unique [`GraphId`]. Used by affinity diagnostics to
1890    /// name *which* graphs disagree; see [`NodeHandle::graph_id`].
1891    pub fn id(&self) -> GraphId {
1892        self.id
1893    }
1894
1895    /// Record where `id`'s `Const` data came from (see [`ConstOrigin`]).
1896    pub fn set_const_origin(&mut self, id: NodeId, origin: ConstOrigin) {
1897        self.const_origins.insert(id, origin);
1898    }
1899
1900    /// Every `Const` of this graph with a recorded source identity.
1901    pub fn const_origins(&self) -> impl Iterator<Item = (NodeId, &ConstOrigin)> {
1902        self.const_origins.iter().map(|(id, o)| (*id, o))
1903    }
1904
1905    /// Look up the resolved target backend for a node, if any has
1906    /// been set. Returns `None` if dispatch resolution hasn't
1907    /// happened yet for this node — common during the migration
1908    /// because old op-builder paths don't call the resolver.
1909    ///
1910    /// Phase 7.5 B2.
1911    pub fn target_backend(&self, id: NodeId) -> Option<BackendId> {
1912        self.target_backends.get(&id).copied()
1913    }
1914
1915    /// Record the resolved target backend for `id`. Set once at DAG
1916    /// construction time (or first-realize time, depending on the
1917    /// dispatch policy chosen in Phase B3). Idempotent: calling
1918    /// twice with the same value is fine; calling twice with
1919    /// different values overwrites.
1920    ///
1921    /// Phase 7.5 B2.
1922    pub fn set_target_backend(&mut self, id: NodeId, backend: BackendId) {
1923        assert!(
1924            id.0 < self.nodes.len(),
1925            "set_target_backend: id out of bounds",
1926        );
1927        self.target_backends.insert(id, backend);
1928    }
1929
1930    /// Number of nodes with a resolved target backend. Mostly for
1931    /// tests and diagnostics.
1932    pub fn target_backend_count(&self) -> usize {
1933        self.target_backends.len()
1934    }
1935
1936    /// The storage class of `id`: the explicit override if one was set via
1937    /// [`Graph::set_storage_class`], else the op-inferred default
1938    /// ([`infer_storage_class`]). Every node has a well-defined class.
1939    ///
1940    /// Phase D substrate (PR-D1).
1941    pub fn storage_class(&self, id: NodeId) -> StorageClass {
1942        if let Some(c) = self.storage_class.get(&id).copied() {
1943            return c;
1944        }
1945        infer_storage_class(&self.nodes[id.0].op)
1946    }
1947
1948    /// Record an explicit storage-class override for `id`, replacing the
1949    /// op-inferred default. Used for nodes whose op does not determine the
1950    /// class — chiefly KV-cache placeholder `Op::Const`s, which are session
1951    /// state rather than shared weights.
1952    ///
1953    /// Phase D substrate (PR-D1).
1954    pub fn set_storage_class(&mut self, id: NodeId, class: StorageClass) {
1955        assert!(
1956            id.0 < self.nodes.len(),
1957            "set_storage_class: id out of bounds",
1958        );
1959        self.storage_class.insert(id, class);
1960    }
1961
1962    /// Whether `id` carries an explicit storage-class override (as opposed
1963    /// to relying on the op-inferred default).
1964    pub fn has_storage_class_override(&self, id: NodeId) -> bool {
1965        self.storage_class.contains_key(&id)
1966    }
1967
1968    /// Number of explicit storage-class overrides. Mostly for tests and
1969    /// diagnostics.
1970    pub fn storage_class_override_count(&self) -> usize {
1971        self.storage_class.len()
1972    }
1973
1974    /// The [`Layout`] associated with `id`. If the side-table has
1975    /// no explicit entry, returns `Layout::contiguous(shape)` —
1976    /// every Node logically has a Layout; the side-table is just
1977    /// the sparse storage for the strided / offset cases.
1978    ///
1979    /// Phase 7.5 storage-unification: metadata-only view ops
1980    /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1981    /// 0-copy `Op::Reshape`) populate this side-table during
1982    /// graph construction. Kernel ops produce contiguous results
1983    /// and rely on the fallback.
1984    pub fn layout(&self, id: NodeId) -> Layout {
1985        if let Some(l) = self.layouts.get(&id) {
1986            return l.clone();
1987        }
1988        Layout::contiguous(self.node(id).shape.clone())
1989    }
1990
1991    /// Record an explicit [`Layout`] for `id`. The Layout's
1992    /// `shape()` must equal `nodes[id].shape` — otherwise the
1993    /// graph becomes incoherent (downstream ops were validated
1994    /// against `node.shape`). Panics in `debug_assertions` mode
1995    /// on mismatch; in release the mismatch is silently kept
1996    /// because the alternative would require this method to
1997    /// return `Result`, which would break call ergonomics in
1998    /// graph-construction code.
1999    ///
2000    /// Set this exactly when an op produces a strided / offset
2001    /// view over upstream Storage. For the common case
2002    /// (contiguous kernel output), don't call this at all —
2003    /// [`Graph::layout`] returns `Layout::contiguous(shape)`
2004    /// as the implicit fallback.
2005    pub fn set_layout(&mut self, id: NodeId, layout: Layout) {
2006        assert!(id.0 < self.nodes.len(), "set_layout: id out of bounds");
2007        debug_assert_eq!(
2008            layout.shape(),
2009            &self.nodes[id.0].shape,
2010            "set_layout: Layout shape disagrees with Node shape \
2011             (Layout sets strides/offset, not the visible shape)",
2012        );
2013        self.layouts.insert(id, layout);
2014    }
2015
2016    /// Whether `id` has an explicit Layout entry in the side-table
2017    /// (i.e. it's a strided / offset view; not the default
2018    /// contiguous case).
2019    pub fn has_explicit_layout(&self, id: NodeId) -> bool {
2020        self.layouts.contains_key(&id)
2021    }
2022
2023    /// Number of nodes with an explicit (non-contiguous) Layout.
2024    /// Mostly for tests and diagnostics.
2025    pub fn explicit_layout_count(&self) -> usize {
2026        self.layouts.len()
2027    }
2028
2029    // -------------------------------------------------------------------
2030    // Multi-output side-table (Op::View / Op::ViewOwned)
2031    // -------------------------------------------------------------------
2032
2033    /// Borrow the per-slot output-view specs for `id`, if it's been
2034    /// declared as a multi-output producer. Returns `None` for
2035    /// single-output nodes (the common case).
2036    ///
2037    /// `Op::View` and `Op::ViewOwned` builders read this to derive
2038    /// the slot's shape/dtype/layout at graph-build time.
2039    pub fn output_views(&self, id: NodeId) -> Option<&[fuel_ir::storage::OutputView]> {
2040        self.node_output_views.get(&id).map(|a| a.as_ref())
2041    }
2042
2043    /// Clone the `Arc` handle to `id`'s per-slot output-view specs.
2044    /// Used by the realization path to attach the same bundle metadata
2045    /// to the realized [`Storage`] without copying the slice.
2046    pub fn output_views_arc(&self, id: NodeId) -> Option<Arc<[fuel_ir::storage::OutputView]>> {
2047        self.node_output_views.get(&id).cloned()
2048    }
2049
2050    /// Declare `id` as a multi-output producer with the given per-slot
2051    /// specs. Validates at graph-build time:
2052    /// 1. `id` is in bounds.
2053    /// 2. `views` is non-empty (a "multi-output" node with zero slots
2054    ///    is a contract bug — use single-output if there's nothing to
2055    ///    project).
2056    /// 3. Slot 0's dtype equals `nodes[id].dtype` (the bundle's
2057    ///    primary dtype convention).
2058    /// 4. Slot 0's shape equals `nodes[id].shape` (slot 0 is the
2059    ///    "primary" slot whose shape the single-output infrastructure
2060    ///    already sees).
2061    /// 5. Each slot's `layout.shape()` equals the slot's `shape`
2062    ///    (Layout adds strides/offset; the visible shape is identical).
2063    ///
2064    /// Idempotent on (id, views). Replacing an existing declaration
2065    /// asserts the new specs are byte-identical to the old in debug
2066    /// builds; in release the last write wins (matches the layouts
2067    /// side-table pattern).
2068    pub fn set_output_views(
2069        &mut self,
2070        id: NodeId,
2071        views: Arc<[fuel_ir::storage::OutputView]>,
2072    ) -> Result<(), fuel_ir::Error> {
2073        if id.0 >= self.nodes.len() {
2074            return Err(fuel_ir::Error::Msg(format!(
2075                "set_output_views: NodeId({}) out of bounds (len={})",
2076                id.0,
2077                self.nodes.len(),
2078            ))
2079            .bt());
2080        }
2081        if views.is_empty() {
2082            return Err(fuel_ir::Error::Msg(
2083                "set_output_views: slot list must be non-empty".into(),
2084            )
2085            .bt());
2086        }
2087        let node = &self.nodes[id.0];
2088        let slot0 = &views[0];
2089        if slot0.dtype != node.dtype {
2090            return Err(fuel_ir::Error::Msg(format!(
2091                "set_output_views: slot 0 dtype {:?} disagrees with \
2092                 Node::dtype {:?} on Node#{} (slot 0 is the primary; \
2093                 dtypes must match)",
2094                slot0.dtype, node.dtype, id.0,
2095            ))
2096            .bt());
2097        }
2098        if slot0.shape != node.shape {
2099            return Err(fuel_ir::Error::Msg(format!(
2100                "set_output_views: slot 0 shape {:?} disagrees with \
2101                 Node::shape {:?} on Node#{} (slot 0 is the primary)",
2102                slot0.shape, node.shape, id.0,
2103            ))
2104            .bt());
2105        }
2106        for (i, v) in views.iter().enumerate() {
2107            if v.layout.shape() != &v.shape {
2108                return Err(fuel_ir::Error::Msg(format!(
2109                    "set_output_views: slot {i} layout.shape() = {:?} \
2110                     disagrees with declared slot shape {:?}",
2111                    v.layout.shape(),
2112                    v.shape,
2113                ))
2114                .bt());
2115            }
2116        }
2117        self.node_output_views.insert(id, views);
2118        Ok(())
2119    }
2120
2121    /// Whether `id` has been declared as a multi-output producer.
2122    pub fn is_multi_output(&self, id: NodeId) -> bool {
2123        self.node_output_views.contains_key(&id)
2124    }
2125
2126    /// Number of nodes declared as multi-output producers. Mostly for
2127    /// tests and diagnostics.
2128    pub fn multi_output_count(&self) -> usize {
2129        self.node_output_views.len()
2130    }
2131
2132    /// Whether some node in this graph *produces* (binds mid-realize) the
2133    /// runtime value `sym` — i.e. `sym` is **data-determined**, computed by
2134    /// an op during the pass rather than supplied up front. Used to tell a
2135    /// data-determined `DynScalar::Sym` (which is legitimately unbound in
2136    /// the compile-time `SymEnv` and must be resolved at *execute* time)
2137    /// apart from a caller error (a truly-unbound input-determined sym,
2138    /// which must surface as an error at realize). Today the only producer
2139    /// of a data-determined symbol is [`Op::NonZeroIndices`] (its
2140    /// `count_sym`); extend this match as more data-determined producers
2141    /// land.
2142    pub fn binds_data_determined_sym(&self, sym: SymId) -> bool {
2143        self.nodes.iter().any(|n| match &n.op {
2144            Op::NonZeroIndices { count_sym } => *count_sym == sym,
2145            _ => false,
2146        })
2147    }
2148
2149    /// The next data-determined [`SymId`] not yet used by any producer in
2150    /// this graph — one past the max `Op::NonZeroIndices` `count_sym`, or
2151    /// `SymId(0)` if none exist. Lets a builder that emits several
2152    /// data-determined producers (e.g. one `NonZeroIndices` per MoE expert,
2153    /// across several stacked layers on the same graph) allocate
2154    /// non-colliding count syms without threading an external
2155    /// [`fuel_ir::SymGen`]: each call reflects the producers already added,
2156    /// so successive layers claim strictly higher ranges.
2157    ///
2158    /// This covers the data-determined space (the only producers of which
2159    /// are `NonZeroIndices` nodes). A graph that *also* mixes
2160    /// input-determined symbolic extents in the same low sym range should
2161    /// thread a shared `SymGen` instead — those live in a separate
2162    /// compile-time `SymEnv` this scan does not see.
2163    pub fn next_data_determined_sym(&self) -> SymId {
2164        let max = self
2165            .nodes
2166            .iter()
2167            .filter_map(|n| match &n.op {
2168                Op::NonZeroIndices { count_sym } => Some(count_sym.0),
2169                _ => None,
2170            })
2171            .max();
2172        match max {
2173            Some(m) => SymId(m + 1),
2174            None => SymId(0),
2175        }
2176    }
2177
2178    /// Attach a data-determined row count to an `Op::MatMul` node — the
2179    /// sparse-MoE capacity-buffer support. The node's `Node::shape` stays
2180    /// the row-capacity output shape; `row_count` (a [`DynScalar`]) is how
2181    /// many rows to actually compute. See [`NodeHandle::matmul_dyn_m`].
2182    pub fn set_matmul_row_count(&mut self, id: NodeId, row_count: DynScalar) {
2183        assert!(
2184            id.0 < self.nodes.len(),
2185            "set_matmul_row_count: id out of bounds"
2186        );
2187        self.node_matmul_row_count.insert(id, row_count);
2188    }
2189
2190    /// The data-determined row count for `id`, if it carries one (i.e. it
2191    /// is a dynamic-M matmul). `None` ⇒ an ordinary static-M matmul.
2192    pub fn matmul_row_count(&self, id: NodeId) -> Option<DynScalar> {
2193        self.node_matmul_row_count.get(&id).copied()
2194    }
2195
2196    /// Look up the realized storage for a node, if any has been
2197    /// registered. Returns an Arc clone — the slot stays in the map
2198    /// after this call.
2199    pub fn storage_for(&self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2200        self.storage_map.get(&id).cloned()
2201    }
2202
2203    /// Register a realized-storage slot for `id`. Replaces any
2204    /// existing entry (callers responsible for ensuring this is the
2205    /// intended semantics — e.g. re-realization after eviction).
2206    pub fn set_storage(&mut self, id: NodeId, storage: Arc<RwLock<Storage>>) {
2207        assert!(id.0 < self.nodes.len(), "set_storage: id out of bounds");
2208        self.storage_map.insert(id, storage);
2209    }
2210
2211    /// Convenience: register an owned `Storage` directly. Wraps in
2212    /// `Arc<RwLock<...>>`.
2213    pub fn set_storage_owned(&mut self, id: NodeId, storage: Storage) {
2214        self.set_storage(id, Arc::new(RwLock::new(storage)));
2215    }
2216
2217    /// Remove a slot. Used by eviction / `Op::Release` paths.
2218    /// Returns the Arc if present so callers that want to keep the
2219    /// bytes alive can hold it; otherwise drops on the floor and any
2220    /// outstanding Arc clones still see the bytes.
2221    pub fn remove_storage(&mut self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2222        self.storage_map.remove(&id)
2223    }
2224
2225    /// Whether a slot is currently registered for `id`.
2226    pub fn has_storage(&self, id: NodeId) -> bool {
2227        self.storage_map.contains_key(&id)
2228    }
2229
2230    /// Number of registered storage slots.
2231    pub fn storage_len(&self) -> usize {
2232        self.storage_map.len()
2233    }
2234
2235    /// Register a NodeId as a side-effect root — a node whose output
2236    /// isn't reachable from any user-requested root but whose
2237    /// execution the executor must still schedule. Used for
2238    /// destructive ops (e.g. `Op::Release`) emitted by graph-mutating
2239    /// rules: the rule needs Release to run (freeing device memory),
2240    /// but Release's zero-element marker has no consumer.
2241    ///
2242    /// The executor's realize paths walk the user's roots AND these
2243    /// side-effect roots via a single combined `execution_plan` call.
2244    pub fn add_side_effect_root(&mut self, id: NodeId) {
2245        assert!(
2246            id.0 < self.nodes.len(),
2247            "add_side_effect_root: id out of bounds"
2248        );
2249        if !self.side_effect_roots.contains(&id) {
2250            self.side_effect_roots.push(id);
2251        }
2252    }
2253
2254    /// Snapshot the registered side-effect roots. Executor concatenates
2255    /// these with the user's requested roots before computing the plan.
2256    pub fn side_effect_roots(&self) -> &[NodeId] {
2257        &self.side_effect_roots
2258    }
2259
2260    /// The number of nodes currently in the graph.
2261    pub fn len(&self) -> usize {
2262        self.nodes.len()
2263    }
2264
2265    /// Whether the graph has any nodes.
2266    pub fn is_empty(&self) -> bool {
2267        self.nodes.is_empty()
2268    }
2269
2270    /// Borrow a node by ID. Panics if the ID is out of bounds — it should
2271    /// not be possible for a valid `NodeHandle` handle to produce an invalid
2272    /// ID, so any such panic indicates a bug in graph construction.
2273    pub fn node(&self, id: NodeId) -> &Node {
2274        &self.nodes[id.0]
2275    }
2276
2277    /// Produce a one-line human-readable description of a node and its
2278    /// immediate inputs — the identifier string that executor panics
2279    /// prepend so realize-time failures can be localized to the exact
2280    /// graph position that blew up. Format is stable enough for grep
2281    /// but explicitly intended for humans reading panic output, not for
2282    /// parsing.
2283    pub fn describe_node(&self, id: NodeId) -> String {
2284        let n = self.node(id);
2285        // GAP-303: `short_name()` renders every scan as the bare string "Scan",
2286        // so a body built from the WRONG scan was invisible in every dump and
2287        // every executor panic. Baracuda's requirement, adopted verbatim: make
2288        // something PRINT the carry count on the path that constructs the body —
2289        // not assert it. "A control tells you the encoding is sound; only the
2290        // subject's identity tells you what it encoded."
2291        let scan_params = match n.op {
2292            Op::Scan {
2293                n_carries,
2294                n_xs,
2295                bound,
2296                emit,
2297                ref early_exit,
2298            } => format!(
2299                " n_carries={n_carries} n_xs={n_xs} bound={bound} emit={emit:?} early_exit={}",
2300                early_exit.is_some()
2301            ),
2302            Op::ScanPlaceholder { role, index } => format!(" role={role:?} index={index}"),
2303            _ => String::new(),
2304        };
2305        let op_short = n.op.short_name();
2306        if n.inputs.is_empty() {
2307            return format!(
2308                "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?})",
2309                id.0, n.shape, n.dtype,
2310            );
2311        }
2312        let inputs: Vec<String> = n
2313            .inputs
2314            .iter()
2315            .map(|&inp| {
2316                let ni = self.node(inp);
2317                let ip = ni.op.short_name();
2318                format!("Node#{}[{ip}, {:?}, {:?}]", inp.0, ni.shape, ni.dtype)
2319            })
2320            .collect();
2321        format!(
2322            "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?}, inputs=[{}])",
2323            id.0,
2324            n.shape,
2325            n.dtype,
2326            inputs.join(", "),
2327        )
2328    }
2329
2330    /// Append a node and return its fresh ID. Used by the `NodeHandle`
2331    /// builders, by `opt` passes that canonicalize or rewrite the
2332    /// graph by appending fresh nodes, and by external consumers
2333    /// (fuel-storage's pipelined executor tests, custom-op authors)
2334    /// that need direct graph construction.
2335    ///
2336    /// For metadata-only view ops (`Op::Transpose`, `Op::Permute`,
2337    /// `Op::BroadcastTo`, `Op::Slice`) this also populates the
2338    /// [`layouts`](Self::layout) side-table by deriving the output
2339    /// layout from the input's layout via
2340    /// [`derive_view_output_layout`]. After this call,
2341    /// `graph.layout(new_id)` returns the strided/offset view layout
2342    /// without any further work — the side-table is the single source
2343    /// of truth for layout, with [`Layout::contiguous`] as the
2344    /// fallback for kernel-output nodes.
2345    ///
2346    /// Misuse (malformed Node, dangling input ids, etc.) is caught
2347    /// at execute time as a typed error, not a panic — per project's
2348    /// no-panic-in-production rule.
2349    pub fn push(&mut self, node: Node) -> NodeId {
2350        let id = NodeId(self.nodes.len());
2351        let is_view = node.op.is_view_op();
2352        let view_input = if is_view {
2353            node.inputs.first().copied()
2354        } else {
2355            None
2356        };
2357        let op_for_derive = if is_view { Some(node.op.clone()) } else { None };
2358        self.nodes.push(node);
2359        if let (Some(input_id), Some(op)) = (view_input, op_for_derive)
2360            && input_id.0 < self.nodes.len()
2361        {
2362            let input_layout = self.layout(input_id);
2363            if let Ok(out_layout) = derive_view_output_layout(&op, &input_layout) {
2364                self.set_layout(id, out_layout);
2365            }
2366        }
2367        id
2368    }
2369
2370    /// Rewrite every occurrence of `old_input` in `node`'s input list to
2371    /// `new_input`. In-place mutation — the *only* exception to the
2372    /// otherwise append-only invariant.
2373    ///
2374    /// Callers are responsible for ensuring `new_input` is semantically
2375    /// equivalent to `old_input` at this edge: same shape, same dtype,
2376    /// and produces data the consumer can read without error on the
2377    /// relevant device. Used by transform passes (residency eviction,
2378    /// fusion) that need to redirect a specific consumer's edge.
2379    pub(crate) fn rewrite_input(&mut self, node: NodeId, old_input: NodeId, new_input: NodeId) {
2380        assert!(
2381            node.0 < self.nodes.len(),
2382            "rewrite_input: node out of bounds"
2383        );
2384        let inputs = &mut self.nodes[node.0].inputs;
2385        for inp in inputs.iter_mut() {
2386            if *inp == old_input {
2387                *inp = new_input;
2388            }
2389        }
2390    }
2391
2392    /// **Collapse a decision point to a single baked arm** — the graph-side
2393    /// half of *optimize-time kernel-variant baking* (04-optimization:
2394    /// "kernel-variant choice is largely baked at optimize time"). Given a
2395    /// finalized [`Op::Branch`] and the arm the optimizer chose (`winner_arm`,
2396    /// an index into the branch's `inputs`), this rewrites the graph so the
2397    /// chosen arm is the **realized route** and the branch is no longer a
2398    /// decision point:
2399    ///
2400    /// 1. The `reconverge_at` merge is rewired to read the **winner's exit**
2401    ///    (`inputs[winner_arm]`) in place of arm 0's exit (`inputs[0]`). For
2402    ///    `winner_arm == 0` this is a no-op (the merge already reads arm 0,
2403    ///    the runnability fallback).
2404    /// 2. The branch's `inputs` are reduced to `[winner_exit]` — a **single-arm
2405    ///    branch**, which [`run::extract_runs_multi`] / `non_chosen_arm_nodes` /
2406    ///    the route picker all treat as *no decision* (`arms.len() < 2`), so the
2407    ///    winner's region lowers inline and the non-chosen arms become
2408    ///    orphaned (pruned from the reachable set — nothing reads them once the
2409    ///    merge is rewired). The arm-0 runnability invariant is preserved:
2410    ///    after the reduce, `inputs[0]` is the winner and the merge reads it.
2411    ///
2412    /// This is the "the Branch collapses" resolution the constitution names for
2413    /// same-device **kernel-variant** choices (decomposed-region vs. a fused
2414    /// kernel on the *same* device), as distinct from **placement** choices
2415    /// (arms on *different* devices) which stay live `Op::Branch` decision
2416    /// points for the runtime route picker (06-runtime). The optimizer decides
2417    /// *which* branches are variant branches and computes `winner_arm`; this
2418    /// method only performs the structural collapse.
2419    ///
2420    /// Never-panic: returns [`fuel_ir::Error::InvalidBranch`] on a
2421    /// non-`Op::Branch` node or an out-of-range `winner_arm`, mutating nothing.
2422    /// Idempotent on an already-collapsed (single-arm) branch when
2423    /// `winner_arm == 0`.
2424    pub fn collapse_variant_branch(
2425        &mut self,
2426        branch: NodeId,
2427        winner_arm: usize,
2428    ) -> std::result::Result<(), fuel_ir::Error> {
2429        let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2430        if branch.0 >= self.nodes.len() {
2431            return Err(invalid(format!(
2432                "collapse_variant_branch: branch Node#{} is out of bounds \
2433                 (graph has {} nodes)",
2434                branch.0,
2435                self.nodes.len(),
2436            )));
2437        }
2438        let reconverge_at = match self.nodes[branch.0].op {
2439            Op::Branch { reconverge_at } => reconverge_at,
2440            ref other => {
2441                return Err(invalid(format!(
2442                    "collapse_variant_branch: Node#{} is not an Op::Branch (got \
2443                     {other:?})",
2444                    branch.0,
2445                )));
2446            }
2447        };
2448        let arms = &self.nodes[branch.0].inputs;
2449        if arms.is_empty() {
2450            return Err(invalid(format!(
2451                "collapse_variant_branch: branch Node#{} has no arms",
2452                branch.0,
2453            )));
2454        }
2455        if winner_arm >= arms.len() {
2456            return Err(invalid(format!(
2457                "collapse_variant_branch: winner_arm {winner_arm} is out of range \
2458                 (branch Node#{} has {} arms)",
2459                branch.0,
2460                arms.len(),
2461            )));
2462        }
2463        let old_arm0 = arms[0];
2464        let winner = arms[winner_arm];
2465
2466        // (1) Rewire the merge to read the winner's exit (no-op for arm 0).
2467        if winner != old_arm0 {
2468            self.rewrite_input(reconverge_at, old_arm0, winner);
2469        }
2470        // (2) Reduce the branch to the single winning arm (now arm 0). A
2471        //     single-arm branch is inert: the run extractor / picker skip it,
2472        //     so the non-chosen arms are pruned and the winner lowers inline.
2473        self.nodes[branch.0].inputs = vec![winner];
2474        Ok(())
2475    }
2476
2477    /// Tag a node with a target device. The executor will validate
2478    /// (post-Phase-1) that the node's op can be evaluated on that
2479    /// device. In Phase 1 the tag is informational only.
2480    pub fn set_placement(&mut self, id: NodeId, loc: DeviceLocation) {
2481        assert!(id.0 < self.nodes.len(), "set_placement: id out of bounds");
2482        self.placements.insert(id, loc);
2483    }
2484
2485    /// Read a node's placement hint, or `None` if the node inherits from
2486    /// the executor default.
2487    pub fn placement(&self, id: NodeId) -> Option<DeviceLocation> {
2488        self.placements.get(&id).copied()
2489    }
2490
2491    /// Open a [`BranchBuilder`] rooted at a shared `diverge` point — the
2492    /// first half of the `open_branch` / `add_arm` / `finalize_branches`
2493    /// trio that constructs an [`Op::Branch`] (phi/merge) node with
2494    /// build-time validation (Phase A PR-A1 of the "plan IS the graph"
2495    /// rebuild).
2496    ///
2497    /// `diverge` names the single node from which every candidate route
2498    /// (arm) departs; each arm's *exit* (added via
2499    /// [`BranchBuilder::add_arm`]) becomes one `inputs[i]` of the emitted
2500    /// `Op::Branch`. The builder borrows nothing — it is a pure
2501    /// accumulator of `NodeId`s — so the graph stays free to keep building
2502    /// arms between `open_branch` and `finalize_branches`. All validation
2503    /// (descendant `reconverge_at`, internally-disjoint arms,
2504    /// cast-to-uniform shape/dtype, arm-0 runnability) happens in
2505    /// [`BranchBuilder::finalize_branches`], which returns a typed
2506    /// [`fuel_ir::error::Error::InvalidBranch`] rather than panicking.
2507    pub fn open_branch(&self, diverge: NodeId) -> BranchBuilder {
2508        BranchBuilder {
2509            diverge,
2510            arms: Vec::new(),
2511        }
2512    }
2513
2514    /// Forward-reachable set (the node and all its transitive *consumers*)
2515    /// from `from`, computed against a precomputed consumer adjacency.
2516    /// Used by branch validation to test descendant-hood and arm
2517    /// containment without re-scanning the whole arena per query.
2518    fn forward_reachable(
2519        consumers: &HashMap<NodeId, Vec<NodeId>>,
2520        from: NodeId,
2521    ) -> HashSet<NodeId> {
2522        let mut seen: HashSet<NodeId> = HashSet::new();
2523        let mut stack = vec![from];
2524        while let Some(n) = stack.pop() {
2525            if !seen.insert(n) {
2526                continue;
2527            }
2528            if let Some(cs) = consumers.get(&n) {
2529                for &c in cs {
2530                    if !seen.contains(&c) {
2531                        stack.push(c);
2532                    }
2533                }
2534            }
2535        }
2536        seen
2537    }
2538
2539    /// Backward-reachable set (the node and all its transitive *inputs*)
2540    /// from `from`. Used to bound an arm to the nodes that actually lie
2541    /// on a path `diverge → exit`.
2542    fn backward_reachable(&self, from: NodeId) -> HashSet<NodeId> {
2543        let mut seen: HashSet<NodeId> = HashSet::new();
2544        let mut stack = vec![from];
2545        while let Some(n) = stack.pop() {
2546            if !seen.insert(n) {
2547                continue;
2548            }
2549            for &inp in &self.nodes[n.0].inputs {
2550                if !seen.contains(&inp) {
2551                    stack.push(inp);
2552                }
2553            }
2554        }
2555        seen
2556    }
2557
2558    // -------------------------------------------------------------------
2559    // Compaction of the append-only arena (PR-B4)
2560    // -------------------------------------------------------------------
2561
2562    /// The set of nodes that constitute the **live structure** of the
2563    /// graph relative to `roots`: everything reachable, following node
2564    /// `inputs`, from the union of
2565    ///
2566    /// - the caller's `roots`,
2567    /// - the `side_effect_roots` (nodes the executor must schedule even
2568    ///   when no output reads them — e.g. `Op::Release` eviction), and
2569    /// - the full multi-path structure: for every reachable `Op::Branch`,
2570    ///   its `reconverge_at` and **all its arms** (the arm exits, which
2571    ///   are the Branch node's `inputs`, and transitively their interiors).
2572    ///   Phase C's route picker needs every arm, so the alternative arms
2573    ///   must survive even though nothing downstream reads them directly
2574    ///   (the `reconverge_at` node reads only arm 0).
2575    ///
2576    /// A finalized `Op::Branch` is itself typically orphaned — nothing
2577    /// downstream reads it (PR-A1's runnability invariant has the merge
2578    /// read arm 0 directly, not the Branch). So a plain forward walk from
2579    /// `roots` would miss it. We therefore mirror [`run::extract_runs_multi`]'s
2580    /// `effective_roots` discipline: scan the arena and seed any Branch
2581    /// whose `reconverge_at` (or any arm exit) is already reachable, to a
2582    /// fixpoint, then take the input-closure of all seeds. The result is
2583    /// the exact set compaction must keep.
2584    fn live_set(&self, roots: &[NodeId]) -> HashSet<NodeId> {
2585        // Seeds: roots + side-effect roots. We grow this set with the
2586        // Branch nodes that participate in the reachable computation, then
2587        // take its full input-closure.
2588        let mut seeds: Vec<NodeId> = Vec::new();
2589        let mut seed_set: HashSet<NodeId> = HashSet::new();
2590        let push_seed = |id: NodeId, seeds: &mut Vec<NodeId>, seed_set: &mut HashSet<NodeId>| {
2591            if id.0 < self.nodes.len() && seed_set.insert(id) {
2592                seeds.push(id);
2593            }
2594        };
2595        for &r in roots {
2596            push_seed(r, &mut seeds, &mut seed_set);
2597        }
2598        for &r in &self.side_effect_roots {
2599            push_seed(r, &mut seeds, &mut seed_set);
2600        }
2601
2602        // Grow the seed set with participating Branch nodes to a fixpoint.
2603        // A Branch "participates" when its merge target or any arm exit is
2604        // already reachable from the current seeds (following inputs). Each
2605        // newly-seeded Branch may pull in further arms whose interiors then
2606        // make another Branch participate, hence the fixpoint.
2607        loop {
2608            let reachable = self.input_closure(&seeds);
2609            let mut added = false;
2610            for idx in 0..self.nodes.len() {
2611                let id = NodeId(idx);
2612                if seed_set.contains(&id) {
2613                    continue;
2614                }
2615                let Op::Branch { reconverge_at } = self.nodes[idx].op else {
2616                    continue;
2617                };
2618                let participates = reachable.contains(&reconverge_at)
2619                    || self.nodes[idx].inputs.iter().any(|a| reachable.contains(a));
2620                if participates {
2621                    seed_set.insert(id);
2622                    seeds.push(id);
2623                    added = true;
2624                }
2625            }
2626            if !added {
2627                break;
2628            }
2629        }
2630
2631        // The live set is the full input-closure of the (roots + side-effect
2632        // + participating-Branch) seeds, plus each reachable Branch's
2633        // explicit `reconverge_at` (which is downstream of the arms, so it
2634        // is not pulled in by following inputs from the Branch). The merge
2635        // node is normally reachable from `roots` already, but seeding it
2636        // explicitly makes the live set self-consistent — a Branch never
2637        // outlives its merge target.
2638        let mut live = self.input_closure(&seeds);
2639        let recon_seeds: Vec<NodeId> = live
2640            .iter()
2641            .filter_map(|&id| match self.nodes[id.0].op {
2642                Op::Branch { reconverge_at } => Some(reconverge_at),
2643                _ => None,
2644            })
2645            .collect();
2646        if !recon_seeds.is_empty() {
2647            for n in self.input_closure(&recon_seeds) {
2648                live.insert(n);
2649            }
2650        }
2651        live
2652    }
2653
2654    /// Every node reachable from any of `from`, following node `inputs`
2655    /// transitively (the backward / input cone). Mirrors
2656    /// [`topo_order_multi`] but returns just the set.
2657    fn input_closure(&self, from: &[NodeId]) -> HashSet<NodeId> {
2658        let mut seen: HashSet<NodeId> = HashSet::new();
2659        let mut stack: Vec<NodeId> = from.to_vec();
2660        while let Some(n) = stack.pop() {
2661            if n.0 >= self.nodes.len() || !seen.insert(n) {
2662                continue;
2663            }
2664            for &inp in &self.nodes[n.0].inputs {
2665                if !seen.contains(&inp) {
2666                    stack.push(inp);
2667                }
2668            }
2669        }
2670        seen
2671    }
2672
2673    /// **Required compaction of the append-only arena** (PR-B4).
2674    ///
2675    /// Drops every node *not* in the live structure relative to `roots`
2676    /// (the exploration debris that pathfinders leave) and rebuilds the
2677    /// arena with contiguous, renumbered [`NodeId`]s, remapping **every**
2678    /// `NodeId` reference in the graph. Returns the [`NodeRemap`] from old
2679    /// to new ids so callers can fix up their own `NodeHandle` handles / roots.
2680    ///
2681    /// The live set follows node `inputs` from: `roots`, the
2682    /// `side_effect_roots`, and the full multi-path structure — for every
2683    /// reachable [`Op::Branch`], its `reconverge_at` **and all its arms**
2684    /// (so the route picker's alternatives survive). See [`Graph::live_set`].
2685    ///
2686    /// What is remapped (the correctness crux — a missed remap is silent
2687    /// corruption). Every NodeId-bearing structure in the graph:
2688    /// - each surviving [`Node`]'s `inputs`;
2689    /// - the `NodeId` carried *inside* an op variant — [`Op::Branch`]'s
2690    ///   `reconverge_at` (the only `Op` variant carrying a `NodeId`);
2691    /// - every NodeId-keyed side-table on [`Graph`]: `placements`,
2692    ///   `target_backends`, `layouts`, `storage_map`, `node_output_views`;
2693    /// - the `side_effect_roots` vector.
2694    ///
2695    /// # Not in the per-realize hot path
2696    ///
2697    /// Compaction renumbers `NodeId`s, which would invalidate a realize
2698    /// already built around the current ids (the dispatch order and the
2699    /// `StorageCache` key are `NodeId`). It is therefore a **standalone
2700    /// pass**, deliberately **not** registered as an `Optimizer` in the
2701    /// per-realize driver / `optimize_graph` loop. It runs at load-time
2702    /// **between optimization rounds** (Phase D) and is **required before
2703    /// finalize-to-disk** (Phase E) so the persisted `.fuel` holds the lean
2704    /// result, not exploration debris. Neither caller exists yet.
2705    ///
2706    /// Orphans never change results, so this is a *size* pass, not a
2707    /// *correctness* one — but the remap it performs must be exhaustive or
2708    /// it would itself introduce corruption, which is the property the
2709    /// born-red tests + [`Graph::verify_no_dangling`] guard.
2710    ///
2711    /// This is the implementation behind the free function [`compact`];
2712    /// call that.
2713    fn compact_in_place(&mut self, roots: &[NodeId]) -> NodeRemap {
2714        let live = self.live_set(roots);
2715        let n = self.nodes.len();
2716
2717        // Assign new contiguous ids in ascending old-id order, so the
2718        // relative order of surviving nodes (and hence any topological
2719        // property over them) is preserved.
2720        let mut old_to_new: Vec<Option<NodeId>> = vec![None; n];
2721        let mut next = 0usize;
2722        #[expect(
2723            clippy::needless_range_loop,
2724            reason = "`idx` is an id-space counter: it builds `NodeId(idx)` for the membership check and indexes `old_to_new` by that id; the bound `n` is the old-id count, not an array to enumerate"
2725        )]
2726        for idx in 0..n {
2727            if live.contains(&NodeId(idx)) {
2728                old_to_new[idx] = Some(NodeId(next));
2729                next += 1;
2730            }
2731        }
2732        let remap = NodeRemap { old_to_new };
2733
2734        // Rebuild the node arena, remapping each surviving node's inputs and
2735        // any op-carried NodeId. Surviving nodes' inputs are themselves
2736        // always live (the live set is input-closed), so every `map` here
2737        // resolves.
2738        let mut new_nodes: Vec<Node> = Vec::with_capacity(next);
2739        for idx in 0..n {
2740            if remap.old_to_new[idx].is_none() {
2741                continue;
2742            }
2743            let mut node = self.nodes[idx].clone();
2744            for inp in node.inputs.iter_mut() {
2745                *inp = remap.expect(*inp);
2746            }
2747            if let Op::Branch { reconverge_at } = &mut node.op {
2748                *reconverge_at = remap.expect(*reconverge_at);
2749            }
2750            new_nodes.push(node);
2751        }
2752        self.nodes = new_nodes;
2753
2754        // Remap every NodeId-keyed side-table. Drop entries for dropped
2755        // nodes; rekey survivors to their new id.
2756        self.placements = remap.rekey(std::mem::take(&mut self.placements));
2757        self.target_backends = remap.rekey(std::mem::take(&mut self.target_backends));
2758        self.layouts = remap.rekey(std::mem::take(&mut self.layouts));
2759        self.storage_map = remap.rekey(std::mem::take(&mut self.storage_map));
2760        self.node_output_views = remap.rekey(std::mem::take(&mut self.node_output_views));
2761        self.storage_class = remap.rekey(std::mem::take(&mut self.storage_class));
2762        self.node_matmul_row_count = remap.rekey(std::mem::take(&mut self.node_matmul_row_count));
2763        self.const_origins = remap.rekey(std::mem::take(&mut self.const_origins));
2764
2765        // Remap the side-effect-roots vector (every entry is live — they
2766        // were reachability seeds — so each maps).
2767        self.side_effect_roots = self
2768            .side_effect_roots
2769            .iter()
2770            .map(|&id| remap.expect(id))
2771            .collect();
2772
2773        debug_assert!(
2774            self.verify_no_dangling().is_ok(),
2775            "compact left a dangling NodeId reference: {:?}",
2776            self.verify_no_dangling().err(),
2777        );
2778        remap
2779    }
2780
2781    /// Verify that **no** `NodeId` reference in the graph points outside
2782    /// the arena — the post-compaction safety net for a missed remap.
2783    /// Checks every node's `inputs`, the op-carried `Op::Branch`
2784    /// `reconverge_at`, every NodeId-keyed side-table, and the
2785    /// `side_effect_roots` vector. Returns the first offending reference as
2786    /// a typed error (never panics); used by [`crate::compact`]'s
2787    /// `debug_assert` and by tests.
2788    pub fn verify_no_dangling(&self) -> std::result::Result<(), fuel_ir::Error> {
2789        let n = self.nodes.len();
2790        let bad = |what: String| {
2791            Err(fuel_ir::Error::Msg(format!(
2792                "dangling NodeId reference: {what} (arena has {n} nodes)",
2793            )))
2794        };
2795        for (idx, node) in self.nodes.iter().enumerate() {
2796            for &inp in &node.inputs {
2797                if inp.0 >= n {
2798                    return bad(format!("Node#{idx} input Node#{}", inp.0));
2799                }
2800            }
2801            if let Op::Branch { reconverge_at } = node.op
2802                && reconverge_at.0 >= n
2803            {
2804                return bad(format!(
2805                    "Node#{idx} Branch.reconverge_at Node#{}",
2806                    reconverge_at.0
2807                ));
2808            }
2809        }
2810        for id in self.placements.keys() {
2811            if id.0 >= n {
2812                return bad(format!("placements key Node#{}", id.0));
2813            }
2814        }
2815        for id in self.target_backends.keys() {
2816            if id.0 >= n {
2817                return bad(format!("target_backends key Node#{}", id.0));
2818            }
2819        }
2820        for id in self.layouts.keys() {
2821            if id.0 >= n {
2822                return bad(format!("layouts key Node#{}", id.0));
2823            }
2824        }
2825        for id in self.storage_map.keys() {
2826            if id.0 >= n {
2827                return bad(format!("storage_map key Node#{}", id.0));
2828            }
2829        }
2830        for id in self.node_output_views.keys() {
2831            if id.0 >= n {
2832                return bad(format!("node_output_views key Node#{}", id.0));
2833            }
2834        }
2835        for id in self.storage_class.keys() {
2836            if id.0 >= n {
2837                return bad(format!("storage_class key Node#{}", id.0));
2838            }
2839        }
2840        for &id in &self.side_effect_roots {
2841            if id.0 >= n {
2842                return bad(format!("side_effect_root Node#{}", id.0));
2843            }
2844        }
2845        Ok(())
2846    }
2847}
2848
2849/// **Required compaction of the append-only arena** (PR-B4).
2850///
2851/// Drops every node *not* in the live structure relative to `roots` (the
2852/// exploration debris that pathfinders leave) and rebuilds the arena with
2853/// contiguous, renumbered [`NodeId`]s, remapping **every** `NodeId`
2854/// reference in the graph. Returns the [`NodeRemap`] from old → new ids so
2855/// callers can fix up their own roots / `NodeHandle` handles.
2856///
2857/// The live set follows node `inputs` from `roots`, the
2858/// `side_effect_roots`, and the full multi-path structure — for every
2859/// reachable [`Op::Branch`], its `reconverge_at` **and all its arms** (so
2860/// Phase C's route picker keeps its alternatives). Everything else is
2861/// dropped.
2862///
2863/// **Not in the per-realize hot path.** Compaction renumbers `NodeId`s,
2864/// which would invalidate a realize built around the current ids (the
2865/// dispatch order + the `StorageCache` key are `NodeId`). It is a
2866/// standalone pass — deliberately **not** registered as an `Optimizer` in
2867/// the per-realize driver / `optimize_graph` loop — run at load-time
2868/// **between optimization rounds** (Phase D) and **required before
2869/// finalize-to-disk** (Phase E). Neither caller exists yet.
2870///
2871/// See [`Graph::verify_no_dangling`] for the post-condition the
2872/// `debug_assert` checks: no `NodeId` reference (node inputs, the
2873/// op-carried `Op::Branch.reconverge_at`, any side-table, or
2874/// `side_effect_roots`) points outside the new arena.
2875pub fn compact(graph: &mut Graph, roots: &[NodeId]) -> NodeRemap {
2876    graph.compact_in_place(roots)
2877}
2878
2879/// The old → new `NodeId` mapping produced by [`compact`].
2880///
2881/// Indexed by the *old* `NodeId`: `old_to_new[old.0]` is `Some(new)` if the
2882/// node survived compaction, or `None` if it was dropped as unreachable
2883/// debris. Callers use [`NodeRemap::get`] to translate roots / `NodeHandle`
2884/// ids they still hold; passes that know a node must have survived use
2885/// `NodeRemap::expect`.
2886#[derive(Debug, Clone)]
2887pub struct NodeRemap {
2888    old_to_new: Vec<Option<NodeId>>,
2889}
2890
2891impl NodeRemap {
2892    /// The new id for `old`, or `None` if `old` was dropped (or is out of
2893    /// range of the pre-compaction arena).
2894    pub fn get(&self, old: NodeId) -> Option<NodeId> {
2895        self.old_to_new.get(old.0).copied().flatten()
2896    }
2897
2898    /// Whether `old` survived compaction.
2899    pub fn survived(&self, old: NodeId) -> bool {
2900        self.get(old).is_some()
2901    }
2902
2903    /// The new id for `old`, asserting it survived. Used internally when
2904    /// remapping a reference that is known-live (a surviving node's input,
2905    /// a reachable Branch's `reconverge_at`, a side-effect root) — a `None`
2906    /// here would mean the live-set computation was unsound.
2907    fn expect(&self, old: NodeId) -> NodeId {
2908        self.get(old).unwrap_or_else(|| {
2909            panic!(
2910                "NodeRemap::expect: Node#{} was expected to survive compaction \
2911                 but was dropped — the live set is unsound (a referenced node \
2912                 was not kept)",
2913                old.0,
2914            )
2915        })
2916    }
2917
2918    /// Rekey a `NodeId`-keyed side-table: drop entries whose key was
2919    /// dropped, rewrite surviving keys to their new id. Values are moved,
2920    /// not cloned.
2921    fn rekey<V>(&self, table: HashMap<NodeId, V>) -> HashMap<NodeId, V> {
2922        let mut out = HashMap::with_capacity(table.len());
2923        for (old, v) in table {
2924            if let Some(new) = self.get(old) {
2925                out.insert(new, v);
2926            }
2927        }
2928        out
2929    }
2930}
2931
2932/// Accumulates the arms of an in-construction [`Op::Branch`] (phi/merge)
2933/// node before [`finalize_branches`](Self::finalize_branches) validates
2934/// them and emits the node. Created by [`Graph::open_branch`].
2935///
2936/// The multi-path structure is an **arena fact, not an overlay**: a
2937/// `Branch` node's divergent arms are its `inputs` (each input is one
2938/// route's *exit*), and the op carries an explicit `reconverge_at`. The
2939/// builder is a pure `NodeId` accumulator — it holds no graph reference —
2940/// so the graph remains free to keep appending nodes (further arms) while
2941/// the builder is open. Nothing mutates the arena until
2942/// `finalize_branches`, which is the single validation gate.
2943#[derive(Debug, Clone)]
2944pub struct BranchBuilder {
2945    /// The shared node every arm departs from.
2946    diverge: NodeId,
2947    /// Each arm's *exit* node, in priority order. `arms[0]` is the
2948    /// runnability fallback (arm 0): the route a finalized-but-unpicked
2949    /// graph realizes on.
2950    arms: Vec<NodeId>,
2951}
2952
2953impl BranchBuilder {
2954    /// Append one arm by its *exit* node — the node whose value the merge
2955    /// reads for this route. The first arm added is **arm 0**, the
2956    /// runnability fallback: `reconverge_at` must read arm 0's exit so a
2957    /// finalized-but-not-yet-route-picked graph still realizes (validated
2958    /// in [`finalize_branches`](Self::finalize_branches)).
2959    ///
2960    /// Returns `&mut Self` for chaining. Validation is deferred to
2961    /// finalize — `add_arm` never inspects the graph and never fails.
2962    pub fn add_arm(&mut self, exit: NodeId) -> &mut Self {
2963        self.arms.push(exit);
2964        self
2965    }
2966
2967    /// The shared diverge point this branch departs from.
2968    pub fn diverge(&self) -> NodeId {
2969        self.diverge
2970    }
2971
2972    /// The arm exits accumulated so far, in add order (arm 0 first).
2973    pub fn arms(&self) -> &[NodeId] {
2974        &self.arms
2975    }
2976
2977    /// Validate and emit the [`Op::Branch`] node, returning its fresh
2978    /// `NodeId`. This is the single build-time gate; it **never panics**,
2979    /// surfacing every rejection as [`fuel_ir::error::Error::InvalidBranch`].
2980    ///
2981    /// Returns:
2982    /// - `Ok(Some(branch_id))` — a multi-arm branch was emitted.
2983    /// - `Ok(None)` — a **single-arm branch collapsed** to that arm (no
2984    ///   real decision point), leaving the arena untouched.
2985    /// - `Err(Error::InvalidBranch { .. })` — a validation rule failed.
2986    ///
2987    /// Validation rules (all checked before any mutation):
2988    /// 1. At least one arm; `diverge`, `reconverge_at`, and every arm
2989    ///    exit are in-bounds.
2990    /// 2. **Descendant `reconverge_at`** — the merge must be a forward
2991    ///    descendant of (and distinct from) `diverge`.
2992    /// 3. **Internally-disjoint arms** — each arm's interior nodes (the
2993    ///    nodes on paths `diverge → exit`, excluding the shared `diverge`)
2994    ///    must neither be shared with another arm nor read by any node
2995    ///    outside the branch (`reconverge_at` reading an arm exit is the
2996    ///    one allowed external consumer).
2997    /// 4. **Cast-to-uniform** — all arm exits agree on shape & dtype.
2998    ///    PR-A1 *validates* uniformity and errors on mismatch (it does not
2999    ///    insert `Cast` nodes); dtype-lowered alternatives must therefore
3000    ///    cast back to the merge dtype *inside* their arm before the exit.
3001    /// 5. **Arm-0 runnability** — `reconverge_at` must read arm 0's exit,
3002    ///    so a finalized-but-unpicked graph still realizes on arm 0.
3003    pub fn finalize_branches(
3004        self,
3005        graph: &mut Graph,
3006        reconverge_at: NodeId,
3007    ) -> std::result::Result<Option<NodeId>, fuel_ir::Error> {
3008        let n = graph.nodes.len();
3009        let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
3010
3011        // (1a) At least one arm.
3012        if self.arms.is_empty() {
3013            return Err(invalid(
3014                "branch has no arms; at least one route is required".to_string(),
3015            ));
3016        }
3017        // (1b) Bounds-check every referenced node up front so later
3018        // arena indexing cannot panic.
3019        let in_bounds = |id: NodeId| id.0 < n;
3020        if !in_bounds(self.diverge) {
3021            return Err(invalid(format!(
3022                "diverge Node#{} is out of bounds (graph has {n} nodes)",
3023                self.diverge.0,
3024            )));
3025        }
3026        if !in_bounds(reconverge_at) {
3027            return Err(invalid(format!(
3028                "reconverge_at Node#{} is out of bounds (graph has {n} nodes)",
3029                reconverge_at.0,
3030            )));
3031        }
3032        for &arm in &self.arms {
3033            if !in_bounds(arm) {
3034                return Err(invalid(format!(
3035                    "arm exit Node#{} is out of bounds (graph has {n} nodes)",
3036                    arm.0,
3037                )));
3038            }
3039        }
3040
3041        // (d) Single-arm branches collapse back to that arm — no real
3042        // decision point, so no Op::Branch is emitted and the arena is
3043        // left untouched.
3044        if self.arms.len() == 1 {
3045            return Ok(None);
3046        }
3047
3048        // Build a consumer (reverse) adjacency once for the reachability
3049        // queries below.
3050        let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
3051        for (idx, node) in graph.nodes.iter().enumerate() {
3052            let consumer = NodeId(idx);
3053            for &inp in &node.inputs {
3054                consumers.entry(inp).or_default().push(consumer);
3055            }
3056        }
3057
3058        // (2) reconverge_at must be a forward descendant of diverge and
3059        // distinct from it.
3060        if reconverge_at == self.diverge {
3061            return Err(invalid(format!(
3062                "reconverge_at Node#{} must be a strict descendant of the \
3063                 diverge point, not the diverge point itself",
3064                reconverge_at.0,
3065            )));
3066        }
3067        let fwd_from_diverge = Graph::forward_reachable(&consumers, self.diverge);
3068        if !fwd_from_diverge.contains(&reconverge_at) {
3069            return Err(invalid(format!(
3070                "reconverge_at Node#{} is not a descendant of diverge Node#{}",
3071                reconverge_at.0, self.diverge.0,
3072            )));
3073        }
3074
3075        // (4) Cast-to-uniform: every arm exit must agree on shape & dtype
3076        // with arm 0 (PR-A1 validates uniformity rather than inserting
3077        // Cast nodes).
3078        let arm0 = self.arms[0];
3079        let (want_shape, want_dtype) = {
3080            let a0 = &graph.nodes[arm0.0];
3081            (a0.shape.clone(), a0.dtype)
3082        };
3083        for &arm in &self.arms[1..] {
3084            let node = &graph.nodes[arm.0];
3085            if node.shape != want_shape || node.dtype != want_dtype {
3086                return Err(invalid(format!(
3087                    "arm exit Node#{} ({:?} {:?}) disagrees with arm 0 Node#{} \
3088                     ({:?} {:?}); arms must cast to a uniform shape & dtype at \
3089                     reconverge",
3090                    arm.0, node.shape, node.dtype, arm0.0, want_shape, want_dtype,
3091                )));
3092            }
3093        }
3094
3095        // (5) Arm-0 runnability: reconverge_at must read arm 0's exit, so
3096        // an unpicked graph realizes on arm 0.
3097        if !graph.nodes[reconverge_at.0].inputs.contains(&arm0) {
3098            return Err(invalid(format!(
3099                "reconverge_at Node#{} does not read arm-0 exit Node#{}; the \
3100                 arm-0 runnability invariant requires the merge to read arm 0 \
3101                 so a not-yet-route-picked graph still realizes",
3102                reconverge_at.0, arm0.0,
3103            )));
3104        }
3105
3106        // (3) Internal disjointness. Each arm's node set is the nodes on
3107        // paths diverge → exit: backward-reachable from the exit AND
3108        // forward-reachable from diverge. The arm *interior* excludes the
3109        // shared diverge point.
3110        let mut arm_interiors: Vec<HashSet<NodeId>> = Vec::with_capacity(self.arms.len());
3111        for &exit in &self.arms {
3112            let back = graph.backward_reachable(exit);
3113            let mut interior: HashSet<NodeId> =
3114                back.intersection(&fwd_from_diverge).copied().collect();
3115            interior.remove(&self.diverge);
3116            // The exit itself is always part of the arm even if (for a
3117            // degenerate arm) it equals the diverge point — but a
3118            // diverge-equals-exit arm has an empty interior, which would
3119            // make the arm indistinguishable from "no route", so reject.
3120            if interior.is_empty() {
3121                return Err(invalid(format!(
3122                    "arm exit Node#{} has no interior strictly after diverge \
3123                     Node#{}; an arm must add at least one node between the \
3124                     diverge point and its exit",
3125                    exit.0, self.diverge.0,
3126                )));
3127            }
3128            arm_interiors.push(interior);
3129        }
3130
3131        // (3a) Arms must not share interior nodes.
3132        for i in 0..arm_interiors.len() {
3133            for j in (i + 1)..arm_interiors.len() {
3134                if let Some(shared) = arm_interiors[i].intersection(&arm_interiors[j]).next() {
3135                    return Err(invalid(format!(
3136                        "arms {i} and {j} share interior Node#{}; arms must be \
3137                         internally disjoint",
3138                        shared.0,
3139                    )));
3140                }
3141            }
3142        }
3143
3144        // (3b) No arm-interior node may be read from outside the branch.
3145        // The branch's universe is the union of all arm interiors plus
3146        // the merge node; reconverge_at reading an arm exit is the one
3147        // legitimate "external" consumer.
3148        let mut branch_universe: HashSet<NodeId> = HashSet::new();
3149        for interior in &arm_interiors {
3150            branch_universe.extend(interior.iter().copied());
3151        }
3152        branch_universe.insert(reconverge_at);
3153        for (i, interior) in arm_interiors.iter().enumerate() {
3154            for &m in interior {
3155                if let Some(cs) = consumers.get(&m) {
3156                    for &c in cs {
3157                        if !branch_universe.contains(&c) {
3158                            return Err(invalid(format!(
3159                                "arm {i} interior Node#{} is read from outside \
3160                                 the branch by Node#{}; arm interiors must not be \
3161                                 reachable from outside the branch",
3162                                m.0, c.0,
3163                            )));
3164                        }
3165                    }
3166                }
3167            }
3168        }
3169
3170        // All validation passed — emit the Branch node. Its inputs ARE the
3171        // arm exits, in priority order (arm 0 first); reconverge_at is
3172        // carried on the op. Shape/dtype mirror arm 0 (the uniform merge
3173        // type validated above).
3174        let branch = graph.push(Node {
3175            op: Op::Branch { reconverge_at },
3176            inputs: self.arms.clone(),
3177            shape: want_shape,
3178            dtype: want_dtype,
3179        });
3180        Ok(Some(branch))
3181    }
3182}
3183
3184/// A shared, mutable graph. Builders clone this cheaply and hand it to
3185/// every derived tensor so that all tensors in one computation point to
3186/// the same arena.
3187pub type SharedGraph = Arc<RwLock<Graph>>;
3188
3189/// A handle to a node in a shared graph. Cheap to clone. Carries the
3190/// graph reference so builder methods have everything they need to append
3191/// a new node.
3192#[derive(Debug, Clone)]
3193pub struct NodeHandle {
3194    graph: SharedGraph,
3195    id: NodeId,
3196}
3197
3198impl NodeHandle {
3199    /// Wrap an existing `(graph, node_id)` pair as a NodeHandle handle.
3200    /// Used by graph-rewriting passes (e.g., `opt::insert_copies`)
3201    /// that produce new root `NodeId`s and need to hand them back to
3202    /// call sites as Tensors.
3203    pub fn from_existing(graph: SharedGraph, id: NodeId) -> Self {
3204        Self { graph, id }
3205    }
3206
3207    /// The node ID this handle points to.
3208    pub fn id(&self) -> NodeId {
3209        self.id
3210    }
3211
3212    /// The shared graph this handle belongs to. Exposed so executors and
3213    /// tests can walk the underlying arena.
3214    pub fn graph(&self) -> &SharedGraph {
3215        &self.graph
3216    }
3217
3218    /// This tensor's graph identity — see [`GraphId`].
3219    ///
3220    /// Two tensors can be combined **iff** their `graph_id`s match. Affinity is
3221    /// still *checked* by pointer identity (`Arc::ptr_eq`, which cannot alias);
3222    /// this is the human-readable form, so a failure can say *which* graphs are
3223    /// involved rather than only that they differ.
3224    pub fn graph_id(&self) -> GraphId {
3225        self.graph.read().unwrap().id()
3226    }
3227
3228    /// The shape of this tensor, read from the underlying node.
3229    pub fn shape(&self) -> Shape {
3230        self.graph.read().unwrap().node(self.id).shape.clone()
3231    }
3232
3233    /// The dtype of this tensor, read from the underlying node.
3234    pub fn dtype(&self) -> DType {
3235        self.graph.read().unwrap().node(self.id).dtype
3236    }
3237
3238    /// Phase 7.5 work item G: look up the realized-storage slot for
3239    /// this tensor's node, if any. Returns an Arc clone so the slot
3240    /// stays in the map after this call and the caller's Arc keeps
3241    /// the bytes alive even if a later eviction removes the map
3242    /// entry. `None` means "not realized yet" — the caller should
3243    /// realize the graph first.
3244    pub fn storage_for(&self) -> Option<Arc<RwLock<Storage>>> {
3245        self.graph.read().unwrap().storage_for(self.id)
3246    }
3247
3248    /// The placement hint for this tensor's node, if one was set. `None`
3249    /// means "inherit from the executor's default device."
3250    pub fn placement(&self) -> Option<DeviceLocation> {
3251        self.graph.read().unwrap().placement(self.id)
3252    }
3253
3254    /// Tag this tensor's node with a target device. The executor will
3255    /// validate (post-Phase-1) that the node's op can be evaluated on
3256    /// that device. Returns the same `NodeHandle` handle so this composes
3257    /// with builder-style graph construction:
3258    ///
3259    /// ```ignore
3260    /// let y = a.matmul(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3261    /// ```
3262    pub fn on_device(self, loc: DeviceLocation) -> Self {
3263        self.graph.write().unwrap().set_placement(self.id, loc);
3264        self
3265    }
3266
3267    /// Release this tensor's device-resident storage. Appends an
3268    /// `Op::Release` node whose output is a zero-element marker (shape
3269    /// `[0]`, same dtype as self). Destructive on `self` — after this
3270    /// op runs, `self`'s storage is gone.
3271    ///
3272    /// The ordering-analysis pass (`opt::derive_ordering`, arriving in
3273    /// a follow-up PR) automatically pins the Release to run after
3274    /// every non-destructive reader of `self`. Callers should NOT
3275    /// invoke this directly in a graph that has other readers of
3276    /// `self` until that pass is in place — today's executor has no
3277    /// mechanism to stop them running in the wrong order.
3278    pub fn release(&self) -> Self {
3279        let dtype = self.dtype();
3280        let id = self.graph.write().unwrap().push(Node {
3281            op: Op::Release,
3282            inputs: vec![self.id],
3283            shape: Shape::from_dims(&[0]),
3284            dtype,
3285        });
3286        NodeHandle {
3287            graph: Arc::clone(&self.graph),
3288            id,
3289        }
3290    }
3291
3292    /// Move this tensor's data to `target` device — destroying the
3293    /// source in the process. Appends an `Op::Move` node. The output
3294    /// has the same shape and dtype as the input and lives on
3295    /// `target`; the source's device storage is freed once the op
3296    /// runs.
3297    ///
3298    /// Semantically equivalent to `copy_to_device(target)` followed
3299    /// by dropping the source. Use this when you KNOW the source
3300    /// won't be needed after the transfer — it lets backends skip
3301    /// the intermediate alloc in fast-path cases and lets the
3302    /// scheduler free the source's device memory immediately.
3303    ///
3304    /// If the source may still be read by other ops, use
3305    /// [`Self::copy_to_device`] instead — Copy leaves the source
3306    /// resident.
3307    ///
3308    /// The ordering-analysis pass (`opt::derive_ordering`)
3309    /// automatically pins this op to run after every non-destructive
3310    /// reader of the source. The caller does NOT need to worry about
3311    /// topo ordering — just emit the Move wherever the data-flow
3312    /// says it should go.
3313    pub fn move_to_device(&self, target: DeviceLocation) -> Self {
3314        let shape = self.shape();
3315        let dtype = self.dtype();
3316        let id = self.graph.write().unwrap().push(Node {
3317            op: Op::Move { target },
3318            inputs: vec![self.id],
3319            shape,
3320            dtype,
3321        });
3322        NodeHandle {
3323            graph: Arc::clone(&self.graph),
3324            id,
3325        }
3326    }
3327
3328    /// Copy this tensor's data to `target` device. Source stays
3329    /// resident. Appends an `Op::Copy` node. The output has the same
3330    /// shape and dtype as the input; only residency changes.
3331    ///
3332    /// Same-device copies are still a legal thing to ask for — the
3333    /// backend can optimize them into a cheap clone (or the scheduler
3334    /// can elide the Copy node entirely). Cross-device copies resolve
3335    /// through the pipelined executor's Copy arm (kernel lookup at
3336    /// `(OpKind::Copy, [dt, dt], source backend)`) — today a host
3337    /// round-trip; P2P comes later.
3338    pub fn copy_to_device(&self, target: DeviceLocation) -> Self {
3339        let shape = self.shape();
3340        let dtype = self.dtype();
3341        let id = self.graph.write().unwrap().push(Node {
3342            op: Op::Copy { target },
3343            inputs: vec![self.id],
3344            shape,
3345            dtype,
3346        });
3347        NodeHandle {
3348            graph: Arc::clone(&self.graph),
3349            id,
3350        }
3351    }
3352
3353    /// Project one logical output out of a multi-output producer node.
3354    ///
3355    /// `self` must have been declared as a multi-output producer via
3356    /// [`Graph::set_output_views`] (Session 2's authoring contract will
3357    /// drive this for real fused ops; Session 1 tests drive it
3358    /// directly). The View's output shape, dtype, and layout come from
3359    /// `output_views(self.id)[slot]`. Zero bytes are moved at
3360    /// realization time — the View shares the producer's bundled
3361    /// `Arc<RwLock<Storage>>` and exposes the slot's typed window.
3362    ///
3363    /// **Returns `Result`**: the producer must have declared its slot
3364    /// specs; `slot` must be in range. Errors at graph-build time
3365    /// (per the `validate-at-graph-build-time` rule); the executor
3366    /// never sees a malformed View node.
3367    pub fn view(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3368        let mut graph_w = self.graph.write().unwrap();
3369        let (slot_shape, slot_dtype, slot_byte_offset, slot_layout) = {
3370            let views = graph_w.output_views(self.id).ok_or_else(|| {
3371                fuel_ir::Error::Msg(format!(
3372                    "NodeHandle::view: Node#{} is not a multi-output \
3373                     producer (no output_views registered)",
3374                    self.id.0,
3375                ))
3376                .bt()
3377            })?;
3378            let idx = slot as usize;
3379            let v = views.get(idx).ok_or_else(|| {
3380                fuel_ir::Error::Msg(format!(
3381                    "NodeHandle::view: slot {idx} out of range \
3382                     (producer has {} slots)",
3383                    views.len(),
3384                ))
3385                .bt()
3386            })?;
3387            (v.shape.clone(), v.dtype, v.byte_offset, v.layout.clone())
3388        };
3389        let id = graph_w.push(Node {
3390            op: Op::View { slot },
3391            inputs: vec![self.id],
3392            shape: slot_shape.clone(),
3393            dtype: slot_dtype,
3394        });
3395        // Compose the slot's intrinsic layout (which carries
3396        // slot-relative strides + start_offset) with the slot's
3397        // byte_offset inside the bundle. The result is the layout a
3398        // downstream kernel sees when treating the producer's bundle
3399        // bytes as `slot_dtype` elements: start_offset is in slot-
3400        // dtype-element units; bundle byte_offset is divided by the
3401        // dtype's size_in_bytes to land at the slot's first byte. The
3402        // bundled allocator (`compose_bundle`) aligns each slot's
3403        // byte_offset to its dtype size — so the division is exact.
3404        let dtype_bytes = slot_dtype.size_in_bytes().max(1);
3405        let extra_offset = slot_byte_offset / dtype_bytes;
3406        let effective_layout = if extra_offset == 0 {
3407            slot_layout
3408        } else {
3409            Layout::new(
3410                slot_layout.shape().clone(),
3411                slot_layout.stride().to_vec().into_iter().collect(),
3412                slot_layout.start_offset() + extra_offset,
3413            )
3414        };
3415        // The side-table is set whenever the effective layout differs
3416        // from `Layout::contiguous(slot_shape)` — i.e. whenever the
3417        // slot has a strided layout OR a non-zero composed offset
3418        // (slot 1+ in any bundle).
3419        if effective_layout != Layout::contiguous(slot_shape) {
3420            graph_w.set_layout(id, effective_layout);
3421        }
3422        drop(graph_w);
3423        Ok(NodeHandle {
3424            graph: Arc::clone(&self.graph),
3425            id,
3426        })
3427    }
3428
3429    /// Owned variant of [`Self::view`] — the slot's bytes are copied
3430    /// into a fresh contiguous Storage at realization time, so the
3431    /// producer's bundle Arc can drop independently. Output layout
3432    /// is always contiguous.
3433    ///
3434    /// Same validation as `view`; same error surface.
3435    pub fn view_owned(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3436        let mut graph_w = self.graph.write().unwrap();
3437        let (slot_shape, slot_dtype) = {
3438            let views = graph_w.output_views(self.id).ok_or_else(|| {
3439                fuel_ir::Error::Msg(format!(
3440                    "NodeHandle::view_owned: Node#{} is not a multi-output \
3441                     producer (no output_views registered)",
3442                    self.id.0,
3443                ))
3444                .bt()
3445            })?;
3446            let idx = slot as usize;
3447            let v = views.get(idx).ok_or_else(|| {
3448                fuel_ir::Error::Msg(format!(
3449                    "NodeHandle::view_owned: slot {idx} out of range \
3450                     (producer has {} slots)",
3451                    views.len(),
3452                ))
3453                .bt()
3454            })?;
3455            (v.shape.clone(), v.dtype)
3456        };
3457        let id = graph_w.push(Node {
3458            op: Op::ViewOwned { slot },
3459            inputs: vec![self.id],
3460            shape: slot_shape,
3461            dtype: slot_dtype,
3462        });
3463        drop(graph_w);
3464        Ok(NodeHandle {
3465            graph: Arc::clone(&self.graph),
3466            id,
3467        })
3468    }
3469
3470    /// Append an `Op::WriteSlice` node — copies `source`'s bytes into
3471    /// `self` at the rectangular slab defined by `ranges`. Per-axis,
3472    /// `ranges[i] = (start, end)` is the half-open destination range;
3473    /// `source.dims()[i]` must equal `end - start`, and `end` must
3474    /// not exceed `self.dims()[i]`. Dtypes must match.
3475    ///
3476    /// Destructive on `self`: after the write, `self`'s NodeId is no
3477    /// longer readable (the scheduler pins this op to run after every
3478    /// other reader of `self` via [`opt::derive_ordering`]). The
3479    /// returned tensor adopts `self`'s Storage and Layout; downstream
3480    /// consumers read post-write bytes through this NodeId.
3481    ///
3482    /// Phase E.3.2: introduced to back persistent KV-cache writes
3483    /// (`InferenceContext` + `KvCache`). Non-differentiable.
3484    ///
3485    /// **Returns `Result`**: rank/shape/range mismatches surface as a
3486    /// typed error.
3487    pub fn write_slice(
3488        &self,
3489        source: &NodeHandle,
3490        ranges: Vec<(usize, usize)>,
3491    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3492        self.require_same_graph(source, "write_slice", "source")?;
3493        let dest_shape = self.shape();
3494        let dest_dims = dest_shape.dims();
3495        let src_shape = source.shape();
3496        let src_dims = src_shape.dims();
3497        let rank = dest_dims.len();
3498        if ranges.len() != rank {
3499            return Err(fuel_ir::Error::Msg(format!(
3500                "write_slice: ranges.len() ({}) must equal destination rank ({rank})",
3501                ranges.len(),
3502            ))
3503            .bt());
3504        }
3505        if src_dims.len() != rank {
3506            return Err(fuel_ir::Error::Msg(format!(
3507                "write_slice: source rank ({}) must equal destination rank ({rank})",
3508                src_dims.len(),
3509            ))
3510            .bt());
3511        }
3512        for (i, &(start, end)) in ranges.iter().enumerate() {
3513            if end < start {
3514                return Err(fuel_ir::Error::Msg(format!(
3515                    "write_slice: ranges[{i}] = ({start}, {end}) has end < start"
3516                ))
3517                .bt());
3518            }
3519            if end > dest_dims[i] {
3520                return Err(fuel_ir::Error::Msg(format!(
3521                    "write_slice: ranges[{i}].end ({end}) > destination dim {i} ({})",
3522                    dest_dims[i],
3523                ))
3524                .bt());
3525            }
3526            let slab = end - start;
3527            if src_dims[i] != slab {
3528                return Err(fuel_ir::Error::Msg(format!(
3529                    "write_slice: source dim {i} ({}) must equal slab width ({slab}) \
3530                     = ranges[{i}].end - ranges[{i}].start",
3531                    src_dims[i],
3532                ))
3533                .bt());
3534            }
3535        }
3536        if self.dtype() != source.dtype() {
3537            return Err(fuel_ir::Error::Msg(format!(
3538                "write_slice: dtype mismatch — destination {:?} vs source {:?}",
3539                self.dtype(),
3540                source.dtype(),
3541            ))
3542            .bt());
3543        }
3544        let dtype = self.dtype();
3545        let id = self.graph.write().unwrap().push(Node {
3546            op: Op::WriteSlice {
3547                ranges,
3548                dyn_offset: None,
3549            },
3550            inputs: vec![self.id, source.id],
3551            shape: dest_shape,
3552            dtype,
3553        });
3554        Ok(NodeHandle {
3555            graph: Arc::clone(&self.graph),
3556            id,
3557        })
3558    }
3559
3560    /// Append an `Op::WriteSlice` whose start on `dyn_axis` is a runtime
3561    /// value resolved through the per-pass [`fuel_ir::SymEnv`] at
3562    /// realize, rather than the build-time `ranges[dyn_axis].0`.
3563    ///
3564    /// This is the **input-determined** dynamic-offset path (a
3565    /// [`DynScalar`] over the one `SymEnv`), distinct from
3566    /// [`Self::write_slice_rotating`]'s **data-determined** position (a
3567    /// tensor input read mid-pass). It backs the persistent decode
3568    /// KV-cache write: the append offset is `cached_len`, a per-token
3569    /// runtime value over a fixed-capacity buffer, so the graph
3570    /// structure (and every shape) stays identical across tokens and the
3571    /// plan is reused (Phase D symbolic extents).
3572    ///
3573    /// On `dyn_axis`, `ranges[dyn_axis].0` is ignored (the start is
3574    /// dynamic) and `ranges[dyn_axis].1 - ranges[dyn_axis].0` is the slab
3575    /// width, which must equal `source.dims()[dyn_axis]` and not exceed
3576    /// the destination capacity on that axis. On every other axis the
3577    /// same shape contract as [`Self::write_slice`] applies. The runtime
3578    /// `offset + width` is bounds-checked against the destination
3579    /// capacity at realize (a typed error, never a panic).
3580    ///
3581    /// **Returns `Result`**: rank/dtype/axis-bound/width mismatches
3582    /// surface as a typed error at build time.
3583    pub fn write_slice_dyn(
3584        &self,
3585        source: &NodeHandle,
3586        ranges: Vec<(usize, usize)>,
3587        dyn_axis: usize,
3588        offset: DynScalar,
3589    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3590        self.require_same_graph(source, "write_slice_dyn", "source")?;
3591        let dest_shape = self.shape();
3592        let dest_dims = dest_shape.dims();
3593        let src_shape = source.shape();
3594        let src_dims = src_shape.dims();
3595        let rank = dest_dims.len();
3596        if ranges.len() != rank {
3597            return Err(fuel_ir::Error::Msg(format!(
3598                "write_slice_dyn: ranges.len() ({}) must equal destination rank ({rank})",
3599                ranges.len(),
3600            ))
3601            .bt());
3602        }
3603        if src_dims.len() != rank {
3604            return Err(fuel_ir::Error::Msg(format!(
3605                "write_slice_dyn: source rank ({}) must equal destination rank ({rank})",
3606                src_dims.len(),
3607            ))
3608            .bt());
3609        }
3610        if dyn_axis >= rank {
3611            return Err(fuel_ir::Error::Msg(format!(
3612                "write_slice_dyn: dyn_axis ({dyn_axis}) out of bounds for rank {rank}",
3613            ))
3614            .bt());
3615        }
3616        for (i, &(start, end)) in ranges.iter().enumerate() {
3617            if end < start {
3618                return Err(fuel_ir::Error::Msg(format!(
3619                    "write_slice_dyn: ranges[{i}] = ({start}, {end}) has end < start"
3620                ))
3621                .bt());
3622            }
3623            let slab = end - start;
3624            if src_dims[i] != slab {
3625                return Err(fuel_ir::Error::Msg(format!(
3626                    "write_slice_dyn: source dim {i} ({}) must equal slab width ({slab}) \
3627                     = ranges[{i}].end - ranges[{i}].start",
3628                    src_dims[i],
3629                ))
3630                .bt());
3631            }
3632            if i == dyn_axis {
3633                // The start on `dyn_axis` is dynamic, so `ranges[i].0`/`.1`
3634                // are not bounded by `dest_dims[i]` here — only the slab
3635                // WIDTH must fit the capacity. The runtime `offset + width`
3636                // is bounds-checked against `dest_dims[i]` at realize.
3637                if slab > dest_dims[i] {
3638                    return Err(fuel_ir::Error::Msg(format!(
3639                        "write_slice_dyn: dynamic-axis slab width ({slab}) > destination capacity \
3640                         dim {i} ({})",
3641                        dest_dims[i],
3642                    ))
3643                    .bt());
3644                }
3645            } else if end > dest_dims[i] {
3646                return Err(fuel_ir::Error::Msg(format!(
3647                    "write_slice_dyn: ranges[{i}].end ({end}) > destination dim {i} ({})",
3648                    dest_dims[i],
3649                ))
3650                .bt());
3651            }
3652        }
3653        if self.dtype() != source.dtype() {
3654            return Err(fuel_ir::Error::Msg(format!(
3655                "write_slice_dyn: dtype mismatch — destination {:?} vs source {:?}",
3656                self.dtype(),
3657                source.dtype(),
3658            ))
3659            .bt());
3660        }
3661        let dtype = self.dtype();
3662        let id = self.graph.write().unwrap().push(Node {
3663            op: Op::WriteSlice {
3664                ranges,
3665                dyn_offset: Some((dyn_axis, offset)),
3666            },
3667            inputs: vec![self.id, source.id],
3668            shape: dest_shape,
3669            dtype,
3670        });
3671        Ok(NodeHandle {
3672            graph: Arc::clone(&self.graph),
3673            id,
3674        })
3675    }
3676
3677    /// Append an [`Op::WriteSliceRotating`] node — copies `source`'s
3678    /// bytes into `self` at the rectangular slab defined by `ranges`,
3679    /// with the `axis` axis wrapping modulo `modulus`. The dynamic
3680    /// write position comes through `position` (a rank-0 `U32`
3681    /// tensor); the kernel computes `start = position % modulus` and
3682    /// splits the write across the ring boundary if needed.
3683    ///
3684    /// `ranges[axis].0` is ignored (the rotating-axis start is
3685    /// dynamic). `ranges[axis].1 - ranges[axis].0` is the write
3686    /// length on the rotating axis and must equal `source.dims()[axis]`.
3687    /// On every other axis the same shape contract as `write_slice`
3688    /// applies.
3689    ///
3690    /// Destructive on `self`; scheduled like `write_slice`. Backward
3691    /// panics — sliding-window KV-cache writes are forward-only.
3692    ///
3693    /// **Returns `Result`**: rank/dtype/axis-bound/modulus/range
3694    /// mismatches surface as a typed error at build time.
3695    pub fn write_slice_rotating(
3696        &self,
3697        source: &NodeHandle,
3698        position: &NodeHandle,
3699        axis: usize,
3700        modulus: usize,
3701        ranges: Vec<(usize, usize)>,
3702    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3703        self.require_same_graph(source, "write_slice_rotating", "source")?;
3704        self.require_same_graph(position, "write_slice_rotating", "position")?;
3705        let dest_shape = self.shape();
3706        let dest_dims = dest_shape.dims();
3707        let src_shape = source.shape();
3708        let src_dims = src_shape.dims();
3709        let rank = dest_dims.len();
3710        if ranges.len() != rank {
3711            return Err(fuel_ir::Error::Msg(format!(
3712                "write_slice_rotating: ranges.len() ({}) must equal destination rank ({rank})",
3713                ranges.len(),
3714            ))
3715            .bt());
3716        }
3717        if src_dims.len() != rank {
3718            return Err(fuel_ir::Error::Msg(format!(
3719                "write_slice_rotating: source rank ({}) must equal destination rank ({rank})",
3720                src_dims.len(),
3721            ))
3722            .bt());
3723        }
3724        if axis >= rank {
3725            return Err(fuel_ir::Error::Msg(format!(
3726                "write_slice_rotating: axis {axis} out of bounds for rank {rank}",
3727            ))
3728            .bt());
3729        }
3730        if modulus == 0 {
3731            return Err(
3732                fuel_ir::Error::Msg("write_slice_rotating: modulus must be >= 1".into()).bt(),
3733            );
3734        }
3735        if modulus > dest_dims[axis] {
3736            return Err(fuel_ir::Error::Msg(format!(
3737                "write_slice_rotating: modulus ({modulus}) must not exceed destination dim {axis} ({})",
3738                dest_dims[axis],
3739            )).bt());
3740        }
3741        for (i, &(start, end)) in ranges.iter().enumerate() {
3742            if end < start {
3743                return Err(fuel_ir::Error::Msg(format!(
3744                    "write_slice_rotating: ranges[{i}] = ({start}, {end}) has end < start"
3745                ))
3746                .bt());
3747            }
3748            let slab = end - start;
3749            if i == axis {
3750                if slab == 0 {
3751                    return Err(fuel_ir::Error::Msg(format!(
3752                        "write_slice_rotating: ranges[axis={axis}] slab is 0",
3753                    ))
3754                    .bt());
3755                }
3756                if slab > modulus {
3757                    return Err(fuel_ir::Error::Msg(format!(
3758                        "write_slice_rotating: rotating-axis write length ({slab}) > modulus ({modulus})",
3759                    )).bt());
3760                }
3761                if src_dims[i] != slab {
3762                    return Err(fuel_ir::Error::Msg(format!(
3763                        "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3764                        src_dims[i],
3765                    ))
3766                    .bt());
3767                }
3768                // ranges[axis].1 itself isn't bounded by dest_dims[axis] —
3769                // the kernel wraps the start, so the logical end is meaningless.
3770                // We still require .1 <= modulus to make the slab description
3771                // self-consistent inside the window.
3772                if end > modulus {
3773                    return Err(fuel_ir::Error::Msg(format!(
3774                        "write_slice_rotating: ranges[axis={axis}].end ({end}) > modulus ({modulus})",
3775                    )).bt());
3776                }
3777            } else {
3778                if end > dest_dims[i] {
3779                    return Err(fuel_ir::Error::Msg(format!(
3780                        "write_slice_rotating: ranges[{i}].end ({end}) > destination dim {i} ({})",
3781                        dest_dims[i],
3782                    ))
3783                    .bt());
3784                }
3785                if src_dims[i] != slab {
3786                    return Err(fuel_ir::Error::Msg(format!(
3787                        "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3788                        src_dims[i],
3789                    ))
3790                    .bt());
3791                }
3792            }
3793        }
3794        if self.dtype() != source.dtype() {
3795            return Err(fuel_ir::Error::Msg(format!(
3796                "write_slice_rotating: dtype mismatch — destination {:?} vs source {:?}",
3797                self.dtype(),
3798                source.dtype(),
3799            ))
3800            .bt());
3801        }
3802        if position.dtype() != DType::U32 {
3803            return Err(fuel_ir::Error::Msg(format!(
3804                "write_slice_rotating: position must be U32, got {:?}",
3805                position.dtype(),
3806            ))
3807            .bt());
3808        }
3809        if !position.shape().dims().is_empty() {
3810            return Err(fuel_ir::Error::Msg(format!(
3811                "write_slice_rotating: position must be rank-0 scalar, got {:?}",
3812                position.shape().dims(),
3813            ))
3814            .bt());
3815        }
3816        let dtype = self.dtype();
3817        let id = self.graph.write().unwrap().push(Node {
3818            op: Op::WriteSliceRotating {
3819                axis,
3820                modulus,
3821                ranges,
3822            },
3823            inputs: vec![self.id, source.id, position.id],
3824            shape: dest_shape,
3825            dtype,
3826        });
3827        Ok(NodeHandle {
3828            graph: Arc::clone(&self.graph),
3829            id,
3830        })
3831    }
3832
3833    /// Append an [`Op::WriteSliceDoff`] node — copies `source`'s bytes
3834    /// into `self` at the rectangular slab defined by `ranges`, with
3835    /// the start on `axis` read from `offset` (a rank-0 `I64` tensor)
3836    /// **device-side** at kernel launch. No modulo wrap: `offset` is
3837    /// the raw start on `axis`.
3838    ///
3839    /// `ranges[axis].0` is ignored (the dynamic-axis start is device-
3840    /// resident). `ranges[axis].1 - ranges[axis].0` is the write width
3841    /// on `axis` and must equal `source.dims()[axis]`. On every other
3842    /// axis the same shape contract as [`write_slice`](Self::write_slice)
3843    /// applies.
3844    ///
3845    /// **Bounds are the caller's contract**: `offset` is device-only at
3846    /// build time, so `offset + width <= dest_dims[axis]` cannot be
3847    /// checked here and the kernel does NOT clamp. The caller must size
3848    /// `self`'s capacity on `axis` to cover the largest offset (this is
3849    /// the CUDA-graph-capturable KV-cache append; `DecodeSession` sizes
3850    /// `max_seq`). The static slab width IS checked against capacity.
3851    ///
3852    /// Destructive on `self`; scheduled like `write_slice`. Backward
3853    /// panics — decode-time KV-cache appends are forward-only.
3854    ///
3855    /// **Returns `Result`**: rank / dtype / axis-bound / static-width /
3856    /// offset-dtype mismatches surface as a typed error at build time.
3857    pub fn write_slice_doff(
3858        &self,
3859        source: &NodeHandle,
3860        offset: &NodeHandle,
3861        axis: usize,
3862        ranges: Vec<(usize, usize)>,
3863    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3864        self.require_same_graph(source, "write_slice_doff", "source")?;
3865        self.require_same_graph(offset, "write_slice_doff", "offset")?;
3866        let dest_shape = self.shape();
3867        let dest_dims = dest_shape.dims();
3868        let src_dims = source.shape().dims().to_vec();
3869        let rank = dest_dims.len();
3870        if ranges.len() != rank {
3871            return Err(fuel_ir::Error::Msg(format!(
3872                "write_slice_doff: ranges.len() ({}) must equal destination rank ({rank})",
3873                ranges.len(),
3874            ))
3875            .bt());
3876        }
3877        if src_dims.len() != rank {
3878            return Err(fuel_ir::Error::Msg(format!(
3879                "write_slice_doff: source rank ({}) must equal destination rank ({rank})",
3880                src_dims.len(),
3881            ))
3882            .bt());
3883        }
3884        if axis >= rank {
3885            return Err(fuel_ir::Error::Msg(format!(
3886                "write_slice_doff: axis {axis} out of bounds for rank {rank}",
3887            ))
3888            .bt());
3889        }
3890        for (i, &(start, end)) in ranges.iter().enumerate() {
3891            if end < start {
3892                return Err(fuel_ir::Error::Msg(format!(
3893                    "write_slice_doff: ranges[{i}] = ({start}, {end}) has end < start"
3894                ))
3895                .bt());
3896            }
3897            let slab = end - start;
3898            if i == axis {
3899                if slab == 0 {
3900                    return Err(fuel_ir::Error::Msg(format!(
3901                        "write_slice_doff: ranges[axis={axis}] slab is 0",
3902                    ))
3903                    .bt());
3904                }
3905                // The write width can't exceed the buffer capacity on
3906                // `axis` even at offset 0 (the offset itself is dynamic
3907                // and bounds-checked device-side by the caller's sizing).
3908                if slab > dest_dims[axis] {
3909                    return Err(fuel_ir::Error::Msg(format!(
3910                        "write_slice_doff: dynamic-axis write width ({slab}) > destination dim {axis} ({})",
3911                        dest_dims[axis],
3912                    )).bt());
3913                }
3914                if src_dims[i] != slab {
3915                    return Err(fuel_ir::Error::Msg(format!(
3916                        "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3917                        src_dims[i],
3918                    ))
3919                    .bt());
3920                }
3921            } else {
3922                if end > dest_dims[i] {
3923                    return Err(fuel_ir::Error::Msg(format!(
3924                        "write_slice_doff: ranges[{i}].end ({end}) > destination dim {i} ({})",
3925                        dest_dims[i],
3926                    ))
3927                    .bt());
3928                }
3929                if src_dims[i] != slab {
3930                    return Err(fuel_ir::Error::Msg(format!(
3931                        "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3932                        src_dims[i],
3933                    ))
3934                    .bt());
3935                }
3936            }
3937        }
3938        if self.dtype() != source.dtype() {
3939            return Err(fuel_ir::Error::Msg(format!(
3940                "write_slice_doff: dtype mismatch — destination {:?} vs source {:?}",
3941                self.dtype(),
3942                source.dtype(),
3943            ))
3944            .bt());
3945        }
3946        if offset.dtype() != DType::I64 {
3947            return Err(fuel_ir::Error::Msg(format!(
3948                "write_slice_doff: offset must be I64 (device-resident start), got {:?}",
3949                offset.dtype(),
3950            ))
3951            .bt());
3952        }
3953        if !offset.shape().dims().is_empty() {
3954            return Err(fuel_ir::Error::Msg(format!(
3955                "write_slice_doff: offset must be rank-0 scalar, got {:?}",
3956                offset.shape().dims(),
3957            ))
3958            .bt());
3959        }
3960        let dtype = self.dtype();
3961        let id = self.graph.write().unwrap().push(Node {
3962            op: Op::WriteSliceDoff { axis, ranges },
3963            inputs: vec![self.id, source.id, offset.id],
3964            shape: dest_shape,
3965            dtype,
3966        });
3967        Ok(NodeHandle {
3968            graph: Arc::clone(&self.graph),
3969            id,
3970        })
3971    }
3972
3973    /// Build a `Const` tensor from an `f32` slice and shape on a fresh
3974    /// graph. The new graph is returned via the tensor's `graph` handle.
3975    ///
3976    /// `data` takes `impl Into<Arc<[f32]>>` so both `Vec<f32>` (one-time
3977    /// conversion at the call site) and `Arc<[f32]>` (free clone that
3978    /// shares buffers across forward passes) work.
3979    ///
3980    /// Phase 7.5 work item G2: `device` is the device on which the
3981    /// realized Storage is allocated. The graph's storage_map slot is
3982    /// populated with that Storage and `Op::Const` is emitted —
3983    /// no host-side `ConstData` payload rides on the node.
3984    pub fn from_f32(
3985        data: impl Into<Arc<[f32]>>,
3986        shape: impl Into<Shape>,
3987        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3988    ) -> Result<Self, fuel_ir::Error> {
3989        let v: Arc<[f32]> = data.into();
3990        let buf = fuel_ir::HostBuffer::F32(v.to_vec());
3991        let origin = ConstOrigin::of(&v, DType::F32);
3992        Self::from_host_buffer(buf, DType::F32, shape, device).map(|h| h.with_origin(origin))
3993    }
3994
3995    /// Build a `Const` tensor from an `f64` slice and shape on a fresh graph.
3996    /// `device` selects where the realized Storage is allocated.
3997    pub fn from_f64(
3998        data: impl Into<Arc<[f64]>>,
3999        shape: impl Into<Shape>,
4000        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4001    ) -> Result<Self, fuel_ir::Error> {
4002        let v: Arc<[f64]> = data.into();
4003        let buf = fuel_ir::HostBuffer::F64(v.to_vec());
4004        Self::from_host_buffer(buf, DType::F64, shape, device)
4005    }
4006
4007    /// Build a `Const` tensor from a `bf16` slice and shape on a fresh graph.
4008    /// `device` selects where the realized Storage is allocated.
4009    pub fn from_bf16(
4010        data: impl Into<Arc<[bf16]>>,
4011        shape: impl Into<Shape>,
4012        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4013    ) -> Result<Self, fuel_ir::Error> {
4014        let v: Arc<[bf16]> = data.into();
4015        let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
4016        let origin = ConstOrigin::of(&v, DType::BF16);
4017        Self::from_host_buffer(buf, DType::BF16, shape, device).map(|h| h.with_origin(origin))
4018    }
4019
4020    /// Build a `Const` tensor from an `f16` slice and shape on a fresh graph.
4021    /// `device` selects where the realized Storage is allocated.
4022    pub fn from_f16(
4023        data: impl Into<Arc<[f16]>>,
4024        shape: impl Into<Shape>,
4025        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4026    ) -> Result<Self, fuel_ir::Error> {
4027        let v: Arc<[f16]> = data.into();
4028        let buf = fuel_ir::HostBuffer::F16(v.to_vec());
4029        let origin = ConstOrigin::of(&v, DType::F16);
4030        Self::from_host_buffer(buf, DType::F16, shape, device).map(|h| h.with_origin(origin))
4031    }
4032
4033    /// Build a `Const` tensor from a `u32` slice and shape on a fresh
4034    /// graph. Primarily used to construct index tensors for gather /
4035    /// scatter / index_select. `u32` is the index type all real fuel
4036    /// backends use (Candle CPU, CUDA, Metal), so keeping the reference
4037    /// on the same type means oracle-equivalence tests do not need any
4038    /// index-type translation. `device` selects where the realized
4039    /// Storage is allocated.
4040    pub fn from_u32(
4041        data: impl Into<Arc<[u32]>>,
4042        shape: impl Into<Shape>,
4043        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4044    ) -> Result<Self, fuel_ir::Error> {
4045        let v: Arc<[u32]> = data.into();
4046        let buf = fuel_ir::HostBuffer::U32(v.to_vec());
4047        let origin = ConstOrigin::of(&v, DType::U32);
4048        Self::from_host_buffer(buf, DType::U32, shape, device).map(|h| h.with_origin(origin))
4049    }
4050
4051    /// G2 internal funnel: allocate Storage on `device` from `buf`,
4052    /// register the slot, emit `Op::Const`. Per-dtype `from_*` methods
4053    /// delegate here.
4054    fn from_host_buffer(
4055        buf: fuel_ir::HostBuffer,
4056        dtype: DType,
4057        shape: impl Into<Shape>,
4058        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4059    ) -> Result<Self, fuel_ir::Error> {
4060        let graph = Arc::new(RwLock::new(Graph::new()));
4061        Self::from_host_buffer_on(&graph, buf, dtype, shape, device)
4062    }
4063
4064    /// `from_host_buffer` against an **existing** graph — the shared body of the
4065    /// `from_*_on` family. Identical to `from_host_buffer` except that the caller
4066    /// supplies the graph instead of one being minted.
4067    fn from_host_buffer_on(
4068        graph: &SharedGraph,
4069        buf: fuel_ir::HostBuffer,
4070        dtype: DType,
4071        shape: impl Into<Shape>,
4072        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4073    ) -> Result<Self, fuel_ir::Error> {
4074        let shape = shape.into();
4075        let n = host_buffer_elem_count(&buf);
4076        // GAP-003: was `assert_eq!`. The message is preserved VERBATIM because
4077        // `docs/gaps.md` and `CLAUDE.md` both anchor on it -- a prose anchor is
4078        // rename-proof, so changing the words here would orphan two citations
4079        // that no identifier rename could have touched.
4080        if n != shape.elem_count() {
4081            return Err(fuel_ir::Error::Msg(format!(
4082                "NodeHandle::from_*: data length {n} does not match shape element count {}",
4083                shape.elem_count(),
4084            )));
4085        }
4086        // GAP-003: was `.expect(...)`. This is the sibling panic the row's
4087        // anchor could not see -- it carries a DIFFERENT message, and a
4088        // message-specific anchor is blind to exactly that.
4089        let backend_storage = device
4090            .storage_from_host_buffer_owned_dyn(buf)
4091            .map_err(|e| {
4092                fuel_ir::Error::Msg(format!(
4093                    "NodeHandle::from_*: device.storage_from_host_buffer_owned_dyn failed: {e}"
4094                ))
4095            })?;
4096        let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
4097        let id = {
4098            let mut g = graph.write().unwrap();
4099            let id = g.push(Node {
4100                op: Op::Const,
4101                inputs: vec![],
4102                shape,
4103                dtype,
4104            });
4105            g.set_storage(id, storage_arc);
4106            id
4107        };
4108        Ok(Self {
4109            graph: Arc::clone(graph),
4110            id,
4111        })
4112    }
4113
4114    /// Build an `f32` `Const` leaf **on the graph you pass in**, rather than on a
4115    /// fresh one.
4116    ///
4117    /// This is the non-anchor route for adding a tensor to an existing graph.
4118    /// `NodeHandle::from_f32` mints a NEW graph, so two `from_*` tensors can never be
4119    /// combined; `from_f32_on` puts the new leaf on `graph`, and
4120    /// [`const_f32_like`](Self::const_f32_like) does the same thing when what you
4121    /// have to hand is a sibling *tensor* rather than the graph itself.
4122    ///
4123    /// ```ignore
4124    /// let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
4125    /// let a = NodeHandle::from_f32_on(&g, a_data, [2, 3], &device);
4126    /// let w = NodeHandle::from_f32_on(&g, w_data, [3, 2], &device);
4127    /// let y = a.matmul(&w);   // same graph ✓
4128    /// ```
4129    pub fn from_f32_on(
4130        graph: &SharedGraph,
4131        data: impl Into<Arc<[f32]>>,
4132        shape: impl Into<Shape>,
4133        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4134    ) -> Result<Self, fuel_ir::Error> {
4135        let v: Arc<[f32]> = data.into();
4136        let buf = fuel_ir::HostBuffer::F32(v.to_vec());
4137        let origin = ConstOrigin::of(&v, DType::F32);
4138        Self::from_host_buffer_on(graph, buf, DType::F32, shape, device)
4139            .map(|h| h.with_origin(origin))
4140    }
4141
4142    /// `f64` sibling of [`from_f32_on`](Self::from_f32_on) — builds on the given
4143    /// graph rather than a fresh one.
4144    pub fn from_f64_on(
4145        graph: &SharedGraph,
4146        data: impl Into<Arc<[f64]>>,
4147        shape: impl Into<Shape>,
4148        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4149    ) -> Result<Self, fuel_ir::Error> {
4150        let v: Arc<[f64]> = data.into();
4151        let buf = fuel_ir::HostBuffer::F64(v.to_vec());
4152        Self::from_host_buffer_on(graph, buf, DType::F64, shape, device)
4153    }
4154
4155    /// `bf16` sibling of [`from_f32_on`](Self::from_f32_on). The common
4156    /// mixed-precision shape — f32 activations, bf16 weights — is exactly this
4157    /// plus [`from_f32_on`](Self::from_f32_on) against one shared graph.
4158    pub fn from_bf16_on(
4159        graph: &SharedGraph,
4160        data: impl Into<Arc<[half::bf16]>>,
4161        shape: impl Into<Shape>,
4162        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4163    ) -> Result<Self, fuel_ir::Error> {
4164        let v: Arc<[half::bf16]> = data.into();
4165        let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
4166        let origin = ConstOrigin::of(&v, DType::BF16);
4167        Self::from_host_buffer_on(graph, buf, DType::BF16, shape, device)
4168            .map(|h| h.with_origin(origin))
4169    }
4170
4171    /// `f16` sibling of [`from_f32_on`](Self::from_f32_on).
4172    pub fn from_f16_on(
4173        graph: &SharedGraph,
4174        data: impl Into<Arc<[half::f16]>>,
4175        shape: impl Into<Shape>,
4176        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4177    ) -> Result<Self, fuel_ir::Error> {
4178        let v: Arc<[half::f16]> = data.into();
4179        let buf = fuel_ir::HostBuffer::F16(v.to_vec());
4180        let origin = ConstOrigin::of(&v, DType::F16);
4181        Self::from_host_buffer_on(graph, buf, DType::F16, shape, device)
4182            .map(|h| h.with_origin(origin))
4183    }
4184
4185    /// `u32` sibling of [`from_f32_on`](Self::from_f32_on) — index tensors for
4186    /// gather/index_select built straight onto the graph they will be used on.
4187    pub fn from_u32_on(
4188        graph: &SharedGraph,
4189        data: impl Into<Arc<[u32]>>,
4190        shape: impl Into<Shape>,
4191        device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4192    ) -> Result<Self, fuel_ir::Error> {
4193        let v: Arc<[u32]> = data.into();
4194        let buf = fuel_ir::HostBuffer::U32(v.to_vec());
4195        let origin = ConstOrigin::of(&v, DType::U32);
4196        Self::from_host_buffer_on(graph, buf, DType::U32, shape, device)
4197            .map(|h| h.with_origin(origin))
4198    }
4199
4200    /// Phase 7.5 work item G2: build a `Const` leaf on a fresh graph
4201    /// whose realized bytes already live in `storage`. The graph's
4202    /// storage_map slot for the new node is populated with `storage`
4203    /// directly. The executor's slot-first dispatch returns the slot's
4204    /// Arc on realize.
4205    pub fn from_storage(
4206        storage: Arc<RwLock<Storage>>,
4207        shape: impl Into<Shape>,
4208        dtype: DType,
4209    ) -> Self {
4210        let shape = shape.into();
4211        // Sanity-check the slot's dtype matches the declared dtype.
4212        // The slot's bytes don't carry a logical shape — that's the
4213        // node's job — so we don't validate elem_count here.
4214        debug_assert_eq!(
4215            storage.read().unwrap().dtype(),
4216            dtype,
4217            "NodeHandle::from_storage: declared dtype {:?} does not match storage dtype {:?}",
4218            dtype,
4219            storage.read().unwrap().dtype(),
4220        );
4221        let graph = Arc::new(RwLock::new(Graph::new()));
4222        let id = {
4223            let mut g = graph.write().unwrap();
4224            let id = g.push(Node {
4225                op: Op::Const,
4226                inputs: vec![],
4227                shape,
4228                dtype,
4229            });
4230            g.set_storage(id, storage);
4231            id
4232        };
4233        Self { graph, id }
4234    }
4235
4236    /// Build a second `Const` tensor that lives on the same graph as
4237    /// `self`. Use this to add more inputs to an existing computation.
4238    ///
4239    /// Phase 7.5 G2: the realized Storage is allocated on the device
4240    /// derived from `self`'s graph (any existing slot's device — the
4241    /// graph always has at least one slot-bearing leaf by the time
4242    /// const_*_like is called). For cross-device const construction,
4243    /// build a fresh graph with [`NodeHandle::from_f32`] and link via
4244    /// [`Op::Move`] / [`Op::Copy`].
4245    pub fn const_f32_like(
4246        &self,
4247        data: impl Into<Arc<[f32]>>,
4248        shape: impl Into<Shape>,
4249    ) -> Result<Self, fuel_ir::Error> {
4250        let v: Arc<[f32]> = data.into();
4251        let origin = ConstOrigin::of(&v, DType::F32);
4252        self.const_like_host_buffer(fuel_ir::HostBuffer::F32(v.to_vec()), DType::F32, shape)
4253            .map(|h| h.with_origin(origin))
4254    }
4255
4256    /// Build a second `Const f64` tensor on the same graph as `self`.
4257    pub fn const_f64_like(
4258        &self,
4259        data: impl Into<Arc<[f64]>>,
4260        shape: impl Into<Shape>,
4261    ) -> Result<Self, fuel_ir::Error> {
4262        let v: Arc<[f64]> = data.into();
4263        self.const_like_host_buffer(fuel_ir::HostBuffer::F64(v.to_vec()), DType::F64, shape)
4264    }
4265
4266    /// Build a second `Const bf16` tensor on the same graph as `self`.
4267    pub fn const_bf16_like(
4268        &self,
4269        data: impl Into<Arc<[bf16]>>,
4270        shape: impl Into<Shape>,
4271    ) -> Result<Self, fuel_ir::Error> {
4272        let v: Arc<[bf16]> = data.into();
4273        let origin = ConstOrigin::of(&v, DType::BF16);
4274        self.const_like_host_buffer(fuel_ir::HostBuffer::BF16(v.to_vec()), DType::BF16, shape)
4275            .map(|h| h.with_origin(origin))
4276    }
4277
4278    /// Build a second `Const f16` tensor on the same graph as `self`.
4279    pub fn const_f16_like(
4280        &self,
4281        data: impl Into<Arc<[f16]>>,
4282        shape: impl Into<Shape>,
4283    ) -> Result<Self, fuel_ir::Error> {
4284        let v: Arc<[f16]> = data.into();
4285        let origin = ConstOrigin::of(&v, DType::F16);
4286        self.const_like_host_buffer(fuel_ir::HostBuffer::F16(v.to_vec()), DType::F16, shape)
4287            .map(|h| h.with_origin(origin))
4288    }
4289
4290    /// Build a second `Const u32` (index) tensor on the same graph as `self`.
4291    pub fn const_u32_like(
4292        &self,
4293        data: impl Into<Arc<[u32]>>,
4294        shape: impl Into<Shape>,
4295    ) -> Result<Self, fuel_ir::Error> {
4296        let v: Arc<[u32]> = data.into();
4297        let origin = ConstOrigin::of(&v, DType::U32);
4298        self.const_like_host_buffer(fuel_ir::HostBuffer::U32(v.to_vec()), DType::U32, shape)
4299            .map(|h| h.with_origin(origin))
4300    }
4301
4302    /// Build a sibling U8 `Const` on the same graph. Used by
4303    /// byte-stream inputs (e.g. NF4 quantized weights packed two
4304    /// codes per byte).
4305    pub fn const_u8_like(
4306        &self,
4307        data: impl Into<Arc<[u8]>>,
4308        shape: impl Into<Shape>,
4309    ) -> Result<Self, fuel_ir::Error> {
4310        let v: Arc<[u8]> = data.into();
4311        let origin = ConstOrigin::of(&v, DType::U8);
4312        self.const_like_host_buffer(fuel_ir::HostBuffer::U8(v.to_vec()), DType::U8, shape)
4313            .map(|h| h.with_origin(origin))
4314    }
4315
4316    /// Build a sibling I64 `Const` on the same graph. Used by
4317    /// integer-target ops (e.g. cross-entropy with class indices in
4318    /// PyTorch convention).
4319    pub fn const_i64_like(
4320        &self,
4321        data: impl Into<Arc<[i64]>>,
4322        shape: impl Into<Shape>,
4323    ) -> Result<Self, fuel_ir::Error> {
4324        let v: Arc<[i64]> = data.into();
4325        self.const_like_host_buffer(fuel_ir::HostBuffer::I64(v.to_vec()), DType::I64, shape)
4326    }
4327
4328    /// G2 internal funnel for the per-graph const_*_like family. The
4329    /// device is derived from `self`'s graph slot (any existing one)
4330    /// so callers don't have to thread a device through hot paths
4331    /// like RoPE table construction or LoRA application — the const
4332    /// goes on the same device as the graph it joins.
4333    /// Record this `Const`'s source array identity (see [`ConstOrigin`]).
4334    fn with_origin(self, origin: ConstOrigin) -> Self {
4335        self.graph
4336            .write()
4337            .unwrap()
4338            .set_const_origin(self.id, origin);
4339        self
4340    }
4341
4342    fn const_like_host_buffer(
4343        &self,
4344        buf: fuel_ir::HostBuffer,
4345        dtype: DType,
4346        shape: impl Into<Shape>,
4347    ) -> Result<Self, fuel_ir::Error> {
4348        let shape = shape.into();
4349        let n = host_buffer_elem_count(&buf);
4350        // GAP-003: was `assert_eq!`. The message is preserved VERBATIM -- gaps.md
4351        // and CLAUDE.md both anchor on this prose, and a prose anchor is the one
4352        // an identifier rename cannot reach.
4353        if n != shape.elem_count() {
4354            return Err(fuel_ir::Error::Msg(format!(
4355                "const_*_like: data length {n} does not match shape element count {}",
4356                shape.elem_count(),
4357            )));
4358        }
4359        let device = pick_device_from_graph(&self.graph);
4360        // GAP-003: the sibling panic, converted with it -- the same pair
4361        // `from_host_buffer_on` had, and the second anchor the row named.
4362        let backend_storage = device
4363            .storage_from_host_buffer_owned_dyn(buf)
4364            .map_err(|e| {
4365                fuel_ir::Error::Msg(format!(
4366                    "NodeHandle::const_like: device.storage_from_host_buffer_owned_dyn failed: {e}"
4367                ))
4368            })?;
4369        let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
4370        let id = {
4371            let mut g = self.graph.write().unwrap();
4372            let id = g.push(Node {
4373                op: Op::Const,
4374                inputs: vec![],
4375                shape,
4376                dtype,
4377            });
4378            g.set_storage(id, storage_arc);
4379            id
4380        };
4381        Ok(Self {
4382            graph: self.graph.clone(),
4383            id,
4384        })
4385    }
4386
4387    /// Push a `Const` node on the same graph as `self` **without**
4388    /// populating the graph's storage_map. The caller is responsible
4389    /// for binding the storage Arc into the realize call's initial
4390    /// StorageCache, typically via
4391    /// [`InferenceContext::insert`](../fuel_core/inference_context/struct.InferenceContext.html#method.insert).
4392    ///
4393    /// Used by the Phase 7.6 step 9c E.3.3 forward path to bind
4394    /// pre-allocated KV-cache storage Arcs (held as the new
4395    /// `Arc<RwLock<fuel_memory::Storage>>` type, not the legacy
4396    /// `fuel_backend_contract::Storage` that `const_like_from_storage` takes)
4397    /// into a per-step graph without re-uploading or type-converting.
4398    ///
4399    /// **Caller contract**: the same NodeId must appear in the
4400    /// `initial` StorageCache passed to the realize call. If not, the
4401    /// executor surfaces a clean error pointing at the missing slot
4402    /// — there's no implicit fallback to `graph.storage_map`.
4403    pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: DType) -> Self {
4404        let shape = shape.into();
4405        let id = {
4406            let mut g = self.graph.write().unwrap();
4407            g.push(Node {
4408                op: Op::Const,
4409                inputs: vec![],
4410                shape,
4411                dtype,
4412            })
4413        };
4414        Self {
4415            graph: self.graph.clone(),
4416            id,
4417        }
4418    }
4419
4420    /// Phase 7.5 work item G2: build a second `Const` leaf on the same
4421    /// graph as `self` whose realized bytes already live in `storage`.
4422    /// Companion to [`NodeHandle::from_storage`] for the multi-input case.
4423    pub fn const_like_from_storage(
4424        &self,
4425        storage: Arc<RwLock<Storage>>,
4426        shape: impl Into<Shape>,
4427        dtype: DType,
4428    ) -> Self {
4429        let shape = shape.into();
4430        debug_assert_eq!(
4431            storage.read().unwrap().dtype(),
4432            dtype,
4433            "NodeHandle::const_like_from_storage: declared dtype {:?} does not match storage dtype {:?}",
4434            dtype,
4435            storage.read().unwrap().dtype(),
4436        );
4437        let id = {
4438            let mut g = self.graph.write().unwrap();
4439            let id = g.push(Node {
4440                op: Op::Const,
4441                inputs: vec![],
4442                shape,
4443                dtype,
4444            });
4445            g.set_storage(id, storage);
4446            id
4447        };
4448        Self {
4449            graph: self.graph.clone(),
4450            id,
4451        }
4452    }
4453
4454    /// Append an `Add` node `self + other` to the shared graph and return
4455    /// a handle to the result. Requires matching shapes and matching
4456    /// graphs.
4457    ///
4458    /// # Panics
4459    ///
4460    /// Panics if any operand belongs to a different [`Graph`] than the one this
4461    /// builder is building into. Operand identity is graph-scoped and checked by
4462    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4463    /// deliberate and replaces the hang a cross-graph handle used to produce.
4464    /// Build every operand from one graph, or use a `Result`-returning entry
4465    /// point where one exists.
4466    pub fn add(&self, other: &NodeHandle) -> NodeHandle {
4467        self.binary_op("add", Op::Add, other, self.shape())
4468    }
4469
4470    /// Append a `Mul` node `self * other`.
4471    ///
4472    /// # Panics
4473    ///
4474    /// Panics if any operand belongs to a different [`Graph`] than the one this
4475    /// builder is building into. Operand identity is graph-scoped and checked by
4476    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4477    /// deliberate and replaces the hang a cross-graph handle used to produce.
4478    /// Build every operand from one graph, or use a `Result`-returning entry
4479    /// point where one exists.
4480    pub fn mul(&self, other: &NodeHandle) -> NodeHandle {
4481        self.binary_op("mul", Op::Mul, other, self.shape())
4482    }
4483
4484    /// Append a `MatMul` node. Both operands must have rank ≥ 2. The
4485    /// last two dims are the matrix dims; leading dims are batch dims.
4486    ///
4487    /// - If both operands have the same rank, their batch dims must
4488    ///   match exactly.
4489    /// - If one operand is rank-2 and the other is higher rank, the
4490    ///   rank-2 operand is auto-broadcast to match the higher-rank
4491    ///   operand's batch prefix. This is the common "linear layer
4492    ///   across a batch" pattern (`[batch, seq, d_model] @ [d_model, d_out]`).
4493    /// - Any other rank combination panics; users must reshape first.
4494    ///
4495    /// Shape examples:
4496    /// - `[m, k] @ [k, n]` → `[m, n]`
4497    /// - `[batch, m, k] @ [batch, k, n]` → `[batch, m, n]`
4498    /// - `[batch, seq, k] @ [k, n]` → `[batch, seq, n]` (rhs auto-broadcast)
4499    /// - `[k, n]` @ `[batch, n, m]` → `[batch, k, m]` (lhs auto-broadcast)
4500    ///
4501    /// # Panics
4502    ///
4503    /// Panics if any operand belongs to a different [`Graph`] than the one this
4504    /// builder is building into. Operand identity is graph-scoped and checked by
4505    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4506    /// deliberate and replaces the hang a cross-graph handle used to produce.
4507    /// Build every operand from one graph, or use a `Result`-returning entry
4508    /// point where one exists.
4509    pub fn matmul(&self, other: &NodeHandle) -> NodeHandle {
4510        assert!(
4511            Arc::ptr_eq(&self.graph, &other.graph),
4512            "matmul: tensors must live on the same graph — lhs is on graph #{}, rhs on graph \
4513             #{}; each `from_*` constructor mints a NEW graph, so build `other` on this \
4514             tensor's graph with `from_f32_on(self.graph(), ..)` or `const_*_like`",
4515            self.graph_id(),
4516            other.graph_id(),
4517        );
4518        // Mixed-precision matmul: activations stay in their native
4519        // dtype while weights can live as a lower-precision type on
4520        // device. Currently supported: (F32 × BF16) and (F32 × F16) →
4521        // F32 for half-precision LLM serving (ROADMAP row 34). Other
4522        // heterogeneous combinations are rejected.
4523        let dtypes_ok = self.dtype() == other.dtype()
4524            || (self.dtype() == DType::F32 && matches!(other.dtype(), DType::BF16 | DType::F16));
4525        assert!(
4526            dtypes_ok,
4527            "matmul: unsupported dtype combination: lhs={:?}, rhs={:?}",
4528            self.dtype(),
4529            other.dtype(),
4530        );
4531        let l = self.shape();
4532        let r = other.shape();
4533        let ld = l.dims();
4534        let rd = r.dims();
4535        assert!(
4536            ld.len() >= 2 && rd.len() >= 2,
4537            "matmul: both operands must be rank ≥ 2, got {ld:?} and {rd:?}",
4538        );
4539
4540        // Auto-broadcast the rank-2 operand against the other's batch
4541        // prefix. If ranks already match, this is a no-op.
4542        let (lhs, rhs) = if ld.len() == rd.len() {
4543            (self.clone(), other.clone())
4544        } else if ld.len() == 2 && rd.len() > 2 {
4545            let mut bc_shape: Vec<usize> = rd[..rd.len() - 2].to_vec();
4546            bc_shape.push(ld[0]);
4547            bc_shape.push(ld[1]);
4548            (
4549                self.broadcast_to(Shape::from_dims(&bc_shape)),
4550                other.clone(),
4551            )
4552        } else if rd.len() == 2 && ld.len() > 2 {
4553            let mut bc_shape: Vec<usize> = ld[..ld.len() - 2].to_vec();
4554            bc_shape.push(rd[0]);
4555            bc_shape.push(rd[1]);
4556            (
4557                self.clone(),
4558                other.broadcast_to(Shape::from_dims(&bc_shape)),
4559            )
4560        } else {
4561            panic!(
4562                "matmul: unsupported rank combination {} vs {} — only same-rank or (rank-2 × higher-rank) is supported; reshape first",
4563                ld.len(),
4564                rd.len(),
4565            );
4566        };
4567
4568        // Now both operands have the same rank. Validate batch prefix
4569        // and build the output node.
4570        let lhs_shape = lhs.shape();
4571        let rhs_shape = rhs.shape();
4572        let l = lhs_shape.dims();
4573        let r = rhs_shape.dims();
4574        let rank = l.len();
4575        let batch_rank = rank - 2;
4576        for i in 0..batch_rank {
4577            // GQA-style matmul: A may have more batch heads than B
4578            // (e.g. Q[1,32,1,64] @ K^T[1,4,64,S]). The n_rep factor
4579            // is inferred by the backend at dispatch time; at the
4580            // graph level we just validate divisibility.
4581            let (la, ra) = (l[i], r[i]);
4582            let ok = la == ra || (la > ra && ra > 0 && la % ra == 0);
4583            assert!(
4584                ok,
4585                "matmul: batch dim mismatch at axis {i}: {la} vs {ra} (not equal and not a GQA-divisible pair)",
4586            );
4587        }
4588        let k = l[rank - 1];
4589        let k2 = r[rank - 2];
4590        assert_eq!(k, k2, "matmul: inner dim mismatch (lhs k={k}, rhs k={k2})",);
4591        // Output shape + dtype now flow from primitive_shape (the single source
4592        // of truth); the same-rank operands + validated batch prefix / inner
4593        // dim above guarantee it infers cleanly. (The GQA batch-prefix carry
4594        // uses lhs's batch dims, matching primitive_shape's `l[..rank-2]`.)
4595        let (shape, dtype) = crate::shape::primitive_shape(
4596            &Op::MatMul,
4597            &[lhs_shape.clone(), rhs_shape.clone()],
4598            &[lhs.dtype(), rhs.dtype()],
4599        )
4600        .expect("matmul: operands validated (same-rank, inner dim) before primitive_shape");
4601        let id = self.graph.write().unwrap().push(Node {
4602            op: Op::MatMul,
4603            inputs: vec![lhs.id, rhs.id],
4604            shape,
4605            dtype,
4606        });
4607        Self {
4608            graph: self.graph.clone(),
4609            id,
4610        }
4611    }
4612
4613    /// Data-determined-M matmul: like [`Self::matmul`], but the LHS row
4614    /// count `M` is a **runtime** value `row_count` rather than the static
4615    /// `lhs.shape[-2]`. The LHS and output are **capacity buffers** of
4616    /// `lhs.shape[-2]` rows; only `row_count` rows are computed, the rest
4617    /// left zeroed. This is the sparse-MoE expert-FFN primitive — gather an
4618    /// expert's `count_e` routed tokens into a capacity buffer, then
4619    /// compute exactly `count_e` FFN rows (the FLOP saving). `row_count`
4620    /// resolves at compile if input-determined, else at execute from the
4621    /// producer-bound `SymEnv` (e.g. `Op::NonZeroIndices`'s count). The
4622    /// output shape is the capacity shape `[..., lhs.shape[-2], n]`.
4623    ///
4624    /// # Panics
4625    ///
4626    /// Panics if any operand belongs to a different [`Graph`] than the one this
4627    /// builder is building into. Operand identity is graph-scoped and checked by
4628    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4629    /// deliberate and replaces the hang a cross-graph handle used to produce.
4630    /// Build every operand from one graph, or use a `Result`-returning entry
4631    /// point where one exists.
4632    pub fn matmul_dyn_m(&self, other: &NodeHandle, row_count: DynScalar) -> NodeHandle {
4633        self.assert_same_graph(other, "matmul_dyn_m", "other");
4634        // Only the F32 CPU capacity kernel honors a data-determined row
4635        // count today; other dtypes/backends compute all capacity rows.
4636        // Guard here so a dynamic-M matmul can never be built where it
4637        // would silently over-compute.
4638        assert_eq!(
4639            self.dtype(),
4640            DType::F32,
4641            "matmul_dyn_m: data-determined-M is F32-only today (got lhs {:?})",
4642            self.dtype(),
4643        );
4644        let out = self.matmul(other);
4645        self.graph
4646            .write()
4647            .unwrap()
4648            .set_matmul_row_count(out.id, row_count);
4649        out
4650    }
4651
4652    /// Append an [`Op::Fused`] node carrying
4653    /// [`crate::registry::FusedOpParams::QMatMul`] that multiplies `self` (F32
4654    /// activations, shape `[..., M, K]`) with a Q-type quantized
4655    /// weight matrix of logical shape `[N, K]` stored as a raw byte
4656    /// stream (passed in as a U32 tensor; length = n_bytes / 4).
4657    ///
4658    /// Output shape: `[..., M, N]` F32. The backend dequantizes the
4659    /// weight blocks on the fly inside the matmul kernel, so the
4660    /// quantized blocks stay resident at their compressed size.
4661    ///
4662    /// # Panics
4663    ///
4664    /// Panics if any operand belongs to a different [`Graph`] than the one this
4665    /// builder is building into. Operand identity is graph-scoped and checked by
4666    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4667    /// deliberate and replaces the hang a cross-graph handle used to produce.
4668    /// Build every operand from one graph, or use a `Result`-returning entry
4669    /// point where one exists.
4670    pub fn qmatmul(
4671        &self,
4672        weight_bytes: &NodeHandle,
4673        quant_type: QuantType,
4674        k: usize,
4675        n: usize,
4676    ) -> NodeHandle {
4677        assert!(
4678            Arc::ptr_eq(&self.graph, &weight_bytes.graph),
4679            "qmatmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
4680        );
4681        assert_eq!(
4682            self.dtype(),
4683            DType::F32,
4684            "qmatmul: activations must be F32, got {:?}",
4685            self.dtype(),
4686        );
4687        assert_eq!(
4688            weight_bytes.dtype(),
4689            DType::U32,
4690            "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
4691            weight_bytes.dtype(),
4692        );
4693        let a_dims = self.shape();
4694        let a_dims = a_dims.dims();
4695        assert!(
4696            a_dims.len() >= 2,
4697            "qmatmul: activations must be rank ≥ 2, got {a_dims:?}",
4698        );
4699        assert_eq!(
4700            a_dims[a_dims.len() - 1],
4701            k,
4702            "qmatmul: last dim of activations ({}) must equal k ({k})",
4703            a_dims[a_dims.len() - 1],
4704        );
4705        assert_eq!(
4706            k % quant_type.elements_per_block(),
4707            0,
4708            "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({})",
4709            quant_type.elements_per_block(),
4710        );
4711        // Validate the weight byte count matches [N, K/block_size] blocks.
4712        let expected_bytes =
4713            n * (k / quant_type.elements_per_block()) * quant_type.bytes_per_block();
4714        let expected_u32_elems = expected_bytes.div_ceil(4);
4715        assert_eq!(
4716            weight_bytes.shape().elem_count(),
4717            expected_u32_elems,
4718            "qmatmul: weight_bytes has {} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
4719            weight_bytes.shape().elem_count(),
4720        );
4721        let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
4722        out_dims.push(n);
4723        // Phase 7.6 step 4 (final): emits Op::Fused(QMATMUL, _) per
4724        // the registry split.
4725        let id = self.graph.write().unwrap().push(Node {
4726            op: Op::Fused(
4727                crate::registry::FusedOps::QMATMUL,
4728                crate::registry::FusedOpParams::QMatMul { quant_type, k, n },
4729            ),
4730            inputs: vec![self.id, weight_bytes.id],
4731            shape: Shape::from_dims(&out_dims),
4732            dtype: DType::F32,
4733        });
4734        Self {
4735            graph: self.graph.clone(),
4736            id,
4737        }
4738    }
4739
4740    /// Append an [`Op::Fused`] node carrying
4741    /// [`crate::registry::FusedOpParams::Conv2D`]. `self` must be `[N, Cin, H, W]`
4742    /// (rank 4); `weight` must be `[Cout, Cin/groups, Kh, Kw]` (rank
4743    /// 4) and live on the same graph. `bias` is optional — when
4744    /// present it must be rank 1 with length `Cout`. Returns a rank-4
4745    /// tensor of shape `[N, Cout, Hout, Wout]`.
4746    ///
4747    /// Panics if the input ranks don't match, the channel counts are
4748    /// inconsistent with `groups`, or the output spatial dims would
4749    /// be non-positive.
4750    ///
4751    /// # Panics
4752    ///
4753    /// Panics if any operand belongs to a different [`Graph`] than the one this
4754    /// builder is building into. Operand identity is graph-scoped and checked by
4755    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4756    /// deliberate and replaces the hang a cross-graph handle used to produce.
4757    /// Build every operand from one graph, or use a `Result`-returning entry
4758    /// point where one exists.
4759    pub fn conv2d(
4760        &self,
4761        weight: &NodeHandle,
4762        bias: Option<&NodeHandle>,
4763        stride: (usize, usize),
4764        padding: (usize, usize),
4765        groups: usize,
4766    ) -> NodeHandle {
4767        assert!(
4768            Arc::ptr_eq(&self.graph, &weight.graph),
4769            "conv2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4770        );
4771        if let Some(b) = bias {
4772            assert!(
4773                Arc::ptr_eq(&self.graph, &b.graph),
4774                "conv2d: bias must live on the same graph; use `const_*_like` to build on an existing graph",
4775            );
4776        }
4777        assert!(groups >= 1, "conv2d: groups must be ≥ 1, got {groups}");
4778        let x_dims = self.shape();
4779        let x_dims = x_dims.dims();
4780        let w_dims = weight.shape();
4781        let w_dims = w_dims.dims();
4782        assert_eq!(
4783            x_dims.len(),
4784            4,
4785            "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4786        );
4787        assert_eq!(
4788            w_dims.len(),
4789            4,
4790            "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
4791        );
4792        let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4793        let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4794        assert_eq!(
4795            cin,
4796            cin_per_g * groups,
4797            "conv2d: x has {cin} in-channels but weight expects {} ({}·{groups})",
4798            cin_per_g * groups,
4799            cin_per_g,
4800        );
4801        assert_eq!(
4802            cout % groups,
4803            0,
4804            "conv2d: Cout={cout} must be divisible by groups={groups}",
4805        );
4806        if let Some(b) = bias {
4807            let b_dims = b.shape();
4808            let b_dims = b_dims.dims();
4809            assert_eq!(
4810                b_dims,
4811                &[cout],
4812                "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
4813            );
4814        }
4815        // Hout = (H + 2·pad.0 − Kh) / stride.0 + 1
4816        let (stride_h, stride_w) = stride;
4817        let (pad_h, pad_w) = padding;
4818        assert!(stride_h >= 1 && stride_w >= 1, "conv2d: stride must be ≥ 1");
4819        let h_padded = h_in + 2 * pad_h;
4820        let w_padded = w_in + 2 * pad_w;
4821        assert!(
4822            h_padded >= kh && w_padded >= kw,
4823            "conv2d: padded input ({h_padded}×{w_padded}) smaller than kernel ({kh}×{kw})",
4824        );
4825        let h_out = (h_padded - kh) / stride_h + 1;
4826        let w_out = (w_padded - kw) / stride_w + 1;
4827        let dtype = self.dtype();
4828        let mut inputs = vec![self.id, weight.id];
4829        if let Some(b) = bias {
4830            inputs.push(b.id);
4831        }
4832        // Phase 7.6 step 4 (continued): emit
4833        // `Op::Fused(FusedOps::CONV2D, FusedOpParams::Conv2D { … })`
4834        // through the registry-extended arm. The legacy
4835        // `Op::Conv2D { … }` variant remains in the enum during
4836        // migration (Conv2D's backward still constructs inner
4837        // `Op::Fused(CONV2D, _)` nodes; the legacy variant is reached
4838        // only by direct tests until step 5 drops it).
4839        let id = self.graph.write().unwrap().push(Node {
4840            op: Op::Fused(
4841                crate::registry::FusedOps::CONV2D,
4842                crate::registry::FusedOpParams::Conv2D {
4843                    stride,
4844                    padding,
4845                    groups,
4846                },
4847            ),
4848            inputs,
4849            shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4850            dtype,
4851        });
4852        Self {
4853            graph: self.graph.clone(),
4854            id,
4855        }
4856    }
4857
4858    /// Append an [`Op::Fused`] node carrying
4859    /// [`crate::registry::FusedOpParams::PagedAttn`]. `self` is the Q tensor of shape
4860    /// `[B, Hq, Sq, D]`; `k_cache` and `v_cache` are the paged caches
4861    /// shaped `[num_blocks, block_size, Hkv, D]`; `block_table` is
4862    /// `[B, max_num_blocks_per_seq]` (u32) mapping logical → physical
4863    /// blocks; `context_lens` is `[B]` (u32) of per-sequence lengths;
4864    /// `alibi_slopes` is the optional `[Hq]` per-head bias.
4865    ///
4866    /// Returns a tensor with `q`'s shape `[B, Hq, Sq, D]`.
4867    ///
4868    /// # Panics
4869    ///
4870    /// Panics if any operand belongs to a different [`Graph`] than the one this
4871    /// builder is building into. Operand identity is graph-scoped and checked by
4872    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4873    /// deliberate and replaces the hang a cross-graph handle used to produce.
4874    /// Build every operand from one graph, or use a `Result`-returning entry
4875    /// point where one exists.
4876    pub fn paged_attn(
4877        &self,
4878        k_cache: &NodeHandle,
4879        v_cache: &NodeHandle,
4880        block_table: &NodeHandle,
4881        context_lens: &NodeHandle,
4882        alibi_slopes: Option<&NodeHandle>,
4883        softmax_scale: f32,
4884        block_size: usize,
4885        softcap: Option<f32>,
4886    ) -> NodeHandle {
4887        let g = &self.graph;
4888        assert!(
4889            Arc::ptr_eq(g, &k_cache.graph),
4890            "paged_attn: q + k_cache must share graph"
4891        );
4892        assert!(
4893            Arc::ptr_eq(g, &v_cache.graph),
4894            "paged_attn: q + v_cache must share graph"
4895        );
4896        assert!(
4897            Arc::ptr_eq(g, &block_table.graph),
4898            "paged_attn: q + block_table must share graph"
4899        );
4900        assert!(
4901            Arc::ptr_eq(g, &context_lens.graph),
4902            "paged_attn: q + context_lens must share graph"
4903        );
4904        if let Some(a) = alibi_slopes {
4905            assert!(
4906                Arc::ptr_eq(g, &a.graph),
4907                "paged_attn: alibi_slopes must share graph"
4908            );
4909        }
4910        assert!(block_size >= 1, "paged_attn: block_size must be ≥ 1");
4911
4912        let q_dims = self.shape();
4913        let q_dims = q_dims.dims();
4914        let kc_dims = k_cache.shape();
4915        let kc_dims = kc_dims.dims();
4916        let vc_dims = v_cache.shape();
4917        let vc_dims = vc_dims.dims();
4918        let bt_dims = block_table.shape();
4919        let bt_dims = bt_dims.dims();
4920        let cl_dims = context_lens.shape();
4921        let cl_dims = cl_dims.dims();
4922        assert_eq!(
4923            q_dims.len(),
4924            4,
4925            "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
4926        );
4927        assert_eq!(
4928            kc_dims.len(),
4929            4,
4930            "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}"
4931        );
4932        assert_eq!(
4933            vc_dims.len(),
4934            4,
4935            "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}"
4936        );
4937        assert_eq!(
4938            bt_dims.len(),
4939            2,
4940            "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}"
4941        );
4942        assert_eq!(
4943            cl_dims.len(),
4944            1,
4945            "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}"
4946        );
4947        let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
4948        assert_eq!(
4949            kc_dims[1], block_size,
4950            "paged_attn: k_cache block dim {} != block_size {block_size}",
4951            kc_dims[1]
4952        );
4953        assert_eq!(
4954            vc_dims[1], block_size,
4955            "paged_attn: v_cache block dim {} != block_size {block_size}",
4956            vc_dims[1]
4957        );
4958        let hkv = kc_dims[2];
4959        assert_eq!(
4960            vc_dims[2], hkv,
4961            "paged_attn: Hkv mismatch k_cache vs v_cache"
4962        );
4963        assert_eq!(kc_dims[3], d, "paged_attn: D mismatch q vs k_cache");
4964        assert_eq!(vc_dims[3], d, "paged_attn: D mismatch q vs v_cache");
4965        assert_eq!(
4966            hq % hkv,
4967            0,
4968            "paged_attn: Hq={hq} must be a multiple of Hkv={hkv}"
4969        );
4970        assert_eq!(
4971            bt_dims[0], b,
4972            "paged_attn: block_table batch dim {} != B={b}",
4973            bt_dims[0]
4974        );
4975        assert_eq!(
4976            cl_dims[0], b,
4977            "paged_attn: context_lens len {} != B={b}",
4978            cl_dims[0]
4979        );
4980        assert_eq!(
4981            block_table.dtype(),
4982            crate::DType::U32,
4983            "paged_attn: block_table must be U32"
4984        );
4985        assert_eq!(
4986            context_lens.dtype(),
4987            crate::DType::U32,
4988            "paged_attn: context_lens must be U32"
4989        );
4990        if let Some(a) = alibi_slopes {
4991            let ad = a.shape();
4992            let ad = ad.dims();
4993            assert_eq!(
4994                ad,
4995                &[hq],
4996                "paged_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
4997            );
4998        }
4999
5000        let dtype = self.dtype();
5001        let mut inputs = vec![
5002            self.id,
5003            k_cache.id,
5004            v_cache.id,
5005            block_table.id,
5006            context_lens.id,
5007        ];
5008        if let Some(a) = alibi_slopes {
5009            inputs.push(a.id);
5010        }
5011        // Phase 7.6 step 4 (final): emits Op::Fused(PAGED_ATTN, _).
5012        let id = self.graph.write().unwrap().push(Node {
5013            op: Op::Fused(
5014                crate::registry::FusedOps::PAGED_ATTN,
5015                crate::registry::FusedOpParams::PagedAttn {
5016                    softmax_scale,
5017                    block_size,
5018                    softcap,
5019                },
5020            ),
5021            inputs,
5022            shape: Shape::from_dims(q_dims),
5023            dtype,
5024        });
5025        Self {
5026            graph: self.graph.clone(),
5027            id,
5028        }
5029    }
5030
5031    /// Append an [`Op::Fused`] node carrying
5032    /// [`crate::registry::FusedOpParams::ConvTranspose2D`]. `self` must be
5033    /// `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
5034    /// (note transposed channel order vs `conv2d`). Returns a rank-4
5035    /// tensor `[N, Cout, Hout, Wout]`.
5036    ///
5037    /// Panics if ranks don't match, channel counts are inconsistent
5038    /// with `groups`, or output spatial dims would be non-positive.
5039    ///
5040    /// # Panics
5041    ///
5042    /// Panics if any operand belongs to a different [`Graph`] than the one this
5043    /// builder is building into. Operand identity is graph-scoped and checked by
5044    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5045    /// deliberate and replaces the hang a cross-graph handle used to produce.
5046    /// Build every operand from one graph, or use a `Result`-returning entry
5047    /// point where one exists.
5048    pub fn conv_transpose2d(
5049        &self,
5050        weight: &NodeHandle,
5051        stride: (usize, usize),
5052        padding: (usize, usize),
5053        output_padding: (usize, usize),
5054        dilation: (usize, usize),
5055        groups: usize,
5056    ) -> NodeHandle {
5057        assert!(
5058            Arc::ptr_eq(&self.graph, &weight.graph),
5059            "conv_transpose2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
5060        );
5061        assert!(
5062            groups >= 1,
5063            "conv_transpose2d: groups must be ≥ 1, got {groups}"
5064        );
5065        let x_dims = self.shape();
5066        let x_dims = x_dims.dims();
5067        let w_dims = weight.shape();
5068        let w_dims = w_dims.dims();
5069        assert_eq!(
5070            x_dims.len(),
5071            4,
5072            "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
5073        );
5074        assert_eq!(
5075            w_dims.len(),
5076            4,
5077            "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
5078        );
5079        let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
5080        let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
5081        assert_eq!(
5082            cin, cin_w,
5083            "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
5084        );
5085        assert_eq!(
5086            cin % groups,
5087            0,
5088            "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
5089        );
5090        let cout = cout_per_g * groups;
5091        let (stride_h, stride_w) = stride;
5092        let (pad_h, pad_w) = padding;
5093        let (out_pad_h, out_pad_w) = output_padding;
5094        let (dil_h, dil_w) = dilation;
5095        assert!(
5096            stride_h >= 1 && stride_w >= 1,
5097            "conv_transpose2d: stride must be ≥ 1"
5098        );
5099        assert!(
5100            dil_h >= 1 && dil_w >= 1,
5101            "conv_transpose2d: dilation must be ≥ 1"
5102        );
5103        // Hout = (Hin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1
5104        let h_out = (h_in.saturating_sub(1)) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
5105        let w_out = (w_in.saturating_sub(1)) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
5106        assert!(
5107            h_out > 2 * pad_h && w_out > 2 * pad_w,
5108            "conv_transpose2d: padding ({pad_h}×{pad_w}) is larger than the produced output dims",
5109        );
5110        let h_out = h_out - 2 * pad_h;
5111        let w_out = w_out - 2 * pad_w;
5112        let dtype = self.dtype();
5113        // Phase 7.6 step 4 (final): emits Op::Fused(CONV_TRANSPOSE2D, _).
5114        let id = self.graph.write().unwrap().push(Node {
5115            op: Op::Fused(
5116                crate::registry::FusedOps::CONV_TRANSPOSE2D,
5117                crate::registry::FusedOpParams::ConvTranspose2D {
5118                    stride,
5119                    padding,
5120                    output_padding,
5121                    dilation,
5122                    groups,
5123                },
5124            ),
5125            inputs: vec![self.id, weight.id],
5126            shape: Shape::from_dims(&[n, cout, h_out, w_out]),
5127            dtype,
5128        });
5129        Self {
5130            graph: self.graph.clone(),
5131            id,
5132        }
5133    }
5134
5135    /// Append a transposed 1D convolution by lifting `self` and
5136    /// `weight` into the rank-4 path and dispatching through
5137    /// [`Self::conv_transpose2d`]. `self` is `[N, Cin, Lin]`;
5138    /// `weight` is `[Cin, Cout/groups, K]` (transposed channel
5139    /// order, matches PyTorch). Returns `[N, Cout, Lout]` where
5140    /// `Lout = (Lin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1`.
5141    ///
5142    /// Used by audio codec models (DAC / EnCodec / SNAC / Mimi /
5143    /// Parler-TTS / MetaVoice / CSM) where the decoder upsamples
5144    /// quantized latents back to waveform with strided transposed
5145    /// convs.
5146    ///
5147    /// # Panics
5148    ///
5149    /// Panics if any operand belongs to a different [`Graph`] than the one this
5150    /// builder is building into. Operand identity is graph-scoped and checked by
5151    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5152    /// deliberate and replaces the hang a cross-graph handle used to produce.
5153    /// Build every operand from one graph, or use a `Result`-returning entry
5154    /// point where one exists.
5155    pub fn conv_transpose1d(
5156        &self,
5157        weight: &NodeHandle,
5158        stride: usize,
5159        padding: usize,
5160        output_padding: usize,
5161        dilation: usize,
5162        groups: usize,
5163    ) -> NodeHandle {
5164        self.assert_same_graph(weight, "conv_transpose1d", "weight");
5165        let x_dims = self.shape();
5166        let x_dims = x_dims.dims();
5167        let w_dims = weight.shape();
5168        let w_dims = w_dims.dims();
5169        assert_eq!(
5170            x_dims.len(),
5171            3,
5172            "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
5173        );
5174        assert_eq!(
5175            w_dims.len(),
5176            3,
5177            "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
5178        );
5179        let (n, cin, l_in) = (x_dims[0], x_dims[1], x_dims[2]);
5180        let (cin_w, cout_per_g, k) = (w_dims[0], w_dims[1], w_dims[2]);
5181        let x4 = self.reshape(Shape::from_dims(&[n, cin, 1, l_in]));
5182        let w4 = weight.reshape(Shape::from_dims(&[cin_w, cout_per_g, 1, k]));
5183        let y4 = x4.conv_transpose2d(
5184            &w4,
5185            (1, stride),
5186            (0, padding),
5187            (0, output_padding),
5188            (1, dilation),
5189            groups,
5190        );
5191        let y_dims = y4.shape();
5192        let y_dims = y_dims.dims();
5193        let (n_o, cout, _h_one, l_out) = (y_dims[0], y_dims[1], y_dims[2], y_dims[3]);
5194        y4.reshape(Shape::from_dims(&[n_o, cout, l_out]))
5195    }
5196
5197    /// Append an [`Op::Fused`] node carrying
5198    /// [`crate::registry::FusedOpParams::FlashAttn`]. `self` is `q` of shape
5199    /// `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]` with
5200    /// `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional) is
5201    /// `[Hq]`. Returns a tensor with `q`'s shape.
5202    /// Build the `flash_attn` node.
5203    ///
5204    /// # Panics
5205    ///
5206    /// Panics if any operand belongs to a different [`Graph`] than the one this
5207    /// builder is building into. Operand identity is graph-scoped and checked by
5208    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5209    /// deliberate and replaces the hang a cross-graph handle used to produce.
5210    /// Build every operand from one graph, or use a `Result`-returning entry
5211    /// point where one exists.
5212    pub fn flash_attn(
5213        &self,
5214        k: &NodeHandle,
5215        v: &NodeHandle,
5216        alibi_slopes: Option<&NodeHandle>,
5217        softmax_scale: f32,
5218        causal: bool,
5219        window_size_left: Option<usize>,
5220        window_size_right: Option<usize>,
5221        softcap: Option<f32>,
5222    ) -> NodeHandle {
5223        assert!(
5224            Arc::ptr_eq(&self.graph, &k.graph),
5225            "flash_attn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5226        );
5227        assert!(
5228            Arc::ptr_eq(&self.graph, &v.graph),
5229            "flash_attn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5230        );
5231        if let Some(a) = alibi_slopes {
5232            assert!(
5233                Arc::ptr_eq(&self.graph, &a.graph),
5234                "flash_attn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5235            );
5236        }
5237        let q_dims = self.shape();
5238        let q_dims = q_dims.dims();
5239        let k_dims = k.shape();
5240        let k_dims = k_dims.dims();
5241        let v_dims = v.shape();
5242        let v_dims = v_dims.dims();
5243        assert_eq!(
5244            q_dims.len(),
5245            4,
5246            "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5247        );
5248        assert_eq!(
5249            k_dims.len(),
5250            4,
5251            "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}"
5252        );
5253        assert_eq!(
5254            v_dims.len(),
5255            4,
5256            "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}"
5257        );
5258        let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5259        let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5260        let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5261        assert_eq!(b, bk, "flash_attn: B mismatch q vs k ({b} vs {bk})");
5262        assert_eq!(b, bv, "flash_attn: B mismatch q vs v");
5263        assert_eq!(hkv, hkv_v, "flash_attn: Hkv mismatch k vs v");
5264        assert_eq!(sk, sk_v, "flash_attn: Sk mismatch k vs v");
5265        assert_eq!(d, dk, "flash_attn: head_dim mismatch q vs k");
5266        assert_eq!(d, dv, "flash_attn: head_dim mismatch q vs v");
5267        assert_eq!(
5268            hq % hkv,
5269            0,
5270            "flash_attn: Hq={hq} must be a multiple of Hkv={hkv}"
5271        );
5272        if let Some(a) = alibi_slopes {
5273            let ad = a.shape();
5274            let ad = ad.dims();
5275            assert_eq!(
5276                ad,
5277                &[hq],
5278                "flash_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5279            );
5280        }
5281        let dtype = self.dtype();
5282        let mut inputs = vec![self.id, k.id, v.id];
5283        if let Some(a) = alibi_slopes {
5284            inputs.push(a.id);
5285        }
5286        // Phase 7.6 step 4 (final): emits Op::Fused(FLASH_ATTN, _).
5287        let id = self.graph.write().unwrap().push(Node {
5288            op: Op::Fused(
5289                crate::registry::FusedOps::FLASH_ATTN,
5290                crate::registry::FusedOpParams::FlashAttn {
5291                    softmax_scale,
5292                    causal,
5293                    window_size_left,
5294                    window_size_right,
5295                    softcap,
5296                    k_len: None,
5297                },
5298            ),
5299            inputs,
5300            shape: Shape::from_dims(&[b, hq, sq, d]),
5301            dtype,
5302        });
5303        Self {
5304            graph: self.graph.clone(),
5305            id,
5306        }
5307    }
5308
5309    /// Append an [`Op::Fused`] node carrying
5310    /// [`crate::registry::FusedOpParams::FlashAttn`] over a fixed-**capacity** K/V whose
5311    /// attended length is a **runtime** value (`k_len`) resolved through
5312    /// the per-pass [`fuel_ir::SymEnv`] at realize, decoupled
5313    /// from K's allocated shape.
5314    ///
5315    /// `self` is `q` of shape `[B, Hq, Sq, D]`; `k`/`v` are the capacity
5316    /// buffers `[B, Hkv, max_seq, D]` (GQA: `Hq % Hkv == 0`). Only the
5317    /// first `k_len.resolve(env)` rows along the K/V length axis are
5318    /// attended; the causal mask (when `causal`) is bottom-right-aligned
5319    /// at offset `k_len - Sq` — the standard FlashAttention-2 convention,
5320    /// equal to `cached_len` in autoregressive decode. Returns a tensor
5321    /// with `q`'s shape.
5322    ///
5323    /// This is the flash counterpart of [`Self::write_slice_dyn`]: the
5324    /// decode KV-cache write appends at the runtime offset and flash
5325    /// attends the runtime prefix, so the graph structure stays
5326    /// identical across tokens (Phase D symbolic extents).
5327    ///
5328    /// # Panics
5329    ///
5330    /// Panics if any operand belongs to a different [`Graph`] than the one this
5331    /// builder is building into. Operand identity is graph-scoped and checked by
5332    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5333    /// deliberate and replaces the hang a cross-graph handle used to produce.
5334    /// Build every operand from one graph, or use a `Result`-returning entry
5335    /// point where one exists.
5336    pub fn flash_attn_dyn(
5337        &self,
5338        k: &NodeHandle,
5339        v: &NodeHandle,
5340        alibi_slopes: Option<&NodeHandle>,
5341        softmax_scale: f32,
5342        causal: bool,
5343        window_size_left: Option<usize>,
5344        window_size_right: Option<usize>,
5345        softcap: Option<f32>,
5346        k_len: fuel_ir::DynScalar,
5347    ) -> NodeHandle {
5348        assert!(
5349            Arc::ptr_eq(&self.graph, &k.graph),
5350            "flash_attn_dyn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5351        );
5352        assert!(
5353            Arc::ptr_eq(&self.graph, &v.graph),
5354            "flash_attn_dyn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5355        );
5356        if let Some(a) = alibi_slopes {
5357            assert!(
5358                Arc::ptr_eq(&self.graph, &a.graph),
5359                "flash_attn_dyn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5360            );
5361        }
5362        let q_dims = self.shape();
5363        let q_dims = q_dims.dims();
5364        let k_dims = k.shape();
5365        let k_dims = k_dims.dims();
5366        let v_dims = v.shape();
5367        let v_dims = v_dims.dims();
5368        assert_eq!(
5369            q_dims.len(),
5370            4,
5371            "flash_attn_dyn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5372        );
5373        assert_eq!(
5374            k_dims.len(),
5375            4,
5376            "flash_attn_dyn: k must be rank 4 [B, Hkv, max_seq, D], got {k_dims:?}"
5377        );
5378        assert_eq!(
5379            v_dims.len(),
5380            4,
5381            "flash_attn_dyn: v must be rank 4 [B, Hkv, max_seq, D], got {v_dims:?}"
5382        );
5383        let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5384        let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5385        let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5386        assert_eq!(b, bk, "flash_attn_dyn: B mismatch q vs k ({b} vs {bk})");
5387        assert_eq!(b, bv, "flash_attn_dyn: B mismatch q vs v");
5388        assert_eq!(hkv, hkv_v, "flash_attn_dyn: Hkv mismatch k vs v");
5389        assert_eq!(
5390            sk, sk_v,
5391            "flash_attn_dyn: capacity (max_seq) mismatch k vs v ({sk} vs {sk_v})"
5392        );
5393        assert_eq!(d, dk, "flash_attn_dyn: head_dim mismatch q vs k");
5394        assert_eq!(d, dv, "flash_attn_dyn: head_dim mismatch q vs v");
5395        assert_eq!(
5396            hq % hkv,
5397            0,
5398            "flash_attn_dyn: Hq={hq} must be a multiple of Hkv={hkv}"
5399        );
5400        // A build-time constant k_len must fit the capacity and cover Sq.
5401        if let fuel_ir::DynScalar::Concrete(kl) = k_len {
5402            assert!(
5403                kl <= sk,
5404                "flash_attn_dyn: k_len ({kl}) exceeds K capacity ({sk})"
5405            );
5406            assert!(
5407                kl >= sq,
5408                "flash_attn_dyn: k_len ({kl}) must be >= Sq ({sq}) for a valid causal prefix"
5409            );
5410        }
5411        if let Some(a) = alibi_slopes {
5412            let ad = a.shape();
5413            let ad = ad.dims();
5414            assert_eq!(
5415                ad,
5416                &[hq],
5417                "flash_attn_dyn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5418            );
5419        }
5420        let dtype = self.dtype();
5421        let mut inputs = vec![self.id, k.id, v.id];
5422        if let Some(a) = alibi_slopes {
5423            inputs.push(a.id);
5424        }
5425        let id = self.graph.write().unwrap().push(Node {
5426            op: Op::Fused(
5427                crate::registry::FusedOps::FLASH_ATTN,
5428                crate::registry::FusedOpParams::FlashAttn {
5429                    softmax_scale,
5430                    causal,
5431                    window_size_left,
5432                    window_size_right,
5433                    softcap,
5434                    k_len: Some(k_len),
5435                },
5436            ),
5437            inputs,
5438            shape: Shape::from_dims(&[b, hq, sq, d]),
5439            dtype,
5440        });
5441        Self {
5442            graph: self.graph.clone(),
5443            id,
5444        }
5445    }
5446
5447    /// Append a `Relu` node `max(0, self)`.
5448    pub fn relu(&self) -> NodeHandle {
5449        self.unary_op(Op::Relu)
5450    }
5451
5452    /// Append a `Sqr` node `self * self`.
5453    pub fn sqr(&self) -> NodeHandle {
5454        self.unary_op(Op::Sqr)
5455    }
5456
5457    /// Append an `Exp` node `e^self`.
5458    pub fn exp(&self) -> NodeHandle {
5459        self.unary_op(Op::Exp)
5460    }
5461
5462    /// Append a `Permute` node rearranging the axes according to `axes`.
5463    /// `out.shape[i] = self.shape[axes[i]]`. The axes vector must be a
5464    /// permutation of `0..rank`. For a rank-3 input with `axes = [2, 0, 1]`,
5465    /// the shape transform is `[a, b, c] → [c, a, b]`.
5466    pub fn permute(&self, axes: &[usize]) -> NodeHandle {
5467        let in_shape = self.shape();
5468        let in_dims = in_shape.dims();
5469        let rank = in_dims.len();
5470        assert_eq!(
5471            axes.len(),
5472            rank,
5473            "permute: axes length {} must equal tensor rank {}",
5474            axes.len(),
5475            rank,
5476        );
5477        // Validate that axes is a permutation of 0..rank.
5478        let mut seen = vec![false; rank];
5479        for &ax in axes {
5480            assert!(
5481                ax < rank,
5482                "permute: axis {ax} out of bounds for rank {rank}"
5483            );
5484            assert!(!seen[ax], "permute: duplicate axis {ax} in axes");
5485            seen[ax] = true;
5486        }
5487        let out_dims: Vec<usize> = axes.iter().map(|&ax| in_dims[ax]).collect();
5488        let dtype = self.dtype();
5489        let id = self.graph.write().unwrap().push(Node {
5490            op: Op::Permute(axes.to_vec()),
5491            inputs: vec![self.id],
5492            shape: Shape::from_dims(&out_dims),
5493            dtype,
5494        });
5495        Self {
5496            graph: self.graph.clone(),
5497            id,
5498        }
5499    }
5500
5501    /// Result-returning sibling of [`Self::permute`]. Surfaces bad
5502    /// axes (wrong length, out-of-bounds entry, or duplicate) as a
5503    /// typed error rather than panicking.
5504    pub fn try_permute(&self, axes: &[usize]) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5505        let in_shape = self.shape();
5506        let rank = in_shape.dims().len();
5507        if axes.len() != rank {
5508            return Err(fuel_ir::Error::Msg(format!(
5509                "permute: axes length {} must equal tensor rank {}",
5510                axes.len(),
5511                rank,
5512            ))
5513            .bt());
5514        }
5515        let mut seen = vec![false; rank];
5516        for &ax in axes {
5517            if ax >= rank {
5518                return Err(fuel_ir::Error::Msg(format!(
5519                    "permute: axis {ax} out of bounds for rank {rank}",
5520                ))
5521                .bt());
5522            }
5523            if seen[ax] {
5524                return Err(
5525                    fuel_ir::Error::Msg(format!("permute: duplicate axis {ax} in axes",)).bt(),
5526                );
5527            }
5528            seen[ax] = true;
5529        }
5530        let op = Op::Permute(axes.to_vec());
5531        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5532        let id = self.graph.write().unwrap().push(Node {
5533            op,
5534            inputs: vec![self.id],
5535            shape,
5536            dtype,
5537        });
5538        Ok(Self {
5539            graph: self.graph.clone(),
5540            id,
5541        })
5542    }
5543
5544    /// Append a `Transpose` node that swaps the last two dimensions of a
5545    /// tensor of rank ≥ 2. Leading dims are unchanged. For a rank-2
5546    /// tensor this is the ordinary matrix transpose; for higher ranks,
5547    /// every batch slice is transposed independently.
5548    pub fn transpose(&self) -> NodeHandle {
5549        let in_shape = self.shape();
5550        assert!(
5551            in_shape.dims().len() >= 2,
5552            "transpose: input must be rank ≥ 2, got shape {:?}",
5553            in_shape.dims(),
5554        );
5555        let op = Op::Transpose;
5556        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
5557            .expect("transpose: rank validated above");
5558        let id = self.graph.write().unwrap().push(Node {
5559            op,
5560            inputs: vec![self.id],
5561            shape,
5562            dtype,
5563        });
5564        Self {
5565            graph: self.graph.clone(),
5566            id,
5567        }
5568    }
5569
5570    /// Result-returning sibling of [`Self::transpose`]. Surfaces
5571    /// rank < 2 as a typed error rather than panicking.
5572    pub fn try_transpose(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5573        let in_shape = self.shape();
5574        if in_shape.dims().len() < 2 {
5575            return Err(fuel_ir::Error::Msg(format!(
5576                "transpose: input must be rank ≥ 2, got shape {:?}",
5577                in_shape.dims(),
5578            ))
5579            .bt());
5580        }
5581        let op = Op::Transpose;
5582        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5583        let id = self.graph.write().unwrap().push(Node {
5584            op,
5585            inputs: vec![self.id],
5586            shape,
5587            dtype,
5588        });
5589        Ok(Self {
5590            graph: self.graph.clone(),
5591            id,
5592        })
5593    }
5594
5595    // --- additional element-wise binary ops ---
5596
5597    /// Append a `Sub` node `self - other`. Requires matching shapes and dtypes.
5598    ///
5599    /// # Panics
5600    ///
5601    /// Panics if any operand belongs to a different [`Graph`] than the one this
5602    /// builder is building into. Operand identity is graph-scoped and checked by
5603    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5604    /// deliberate and replaces the hang a cross-graph handle used to produce.
5605    /// Build every operand from one graph, or use a `Result`-returning entry
5606    /// point where one exists.
5607    pub fn sub(&self, other: &NodeHandle) -> NodeHandle {
5608        self.binary_op("sub", Op::Sub, other, self.shape())
5609    }
5610
5611    /// Append a `Div` node `self / other`. Requires matching shapes and dtypes.
5612    ///
5613    /// # Panics
5614    ///
5615    /// Panics if any operand belongs to a different [`Graph`] than the one this
5616    /// builder is building into. Operand identity is graph-scoped and checked by
5617    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5618    /// deliberate and replaces the hang a cross-graph handle used to produce.
5619    /// Build every operand from one graph, or use a `Result`-returning entry
5620    /// point where one exists.
5621    pub fn div(&self, other: &NodeHandle) -> NodeHandle {
5622        self.binary_op("div", Op::Div, other, self.shape())
5623    }
5624
5625    // --- additional element-wise unary ops ---
5626
5627    /// Append a `Neg` node `-self`.
5628    pub fn neg(&self) -> NodeHandle {
5629        self.unary_op(Op::Neg)
5630    }
5631
5632    /// Append a `Sqrt` node `sqrt(self)`.
5633    pub fn sqrt(&self) -> NodeHandle {
5634        self.unary_op(Op::Sqrt)
5635    }
5636
5637    /// Append a `Log` node `ln(self)`.
5638    pub fn log(&self) -> NodeHandle {
5639        self.unary_op(Op::Log)
5640    }
5641
5642    /// Append a `Sin` node.
5643    pub fn sin(&self) -> NodeHandle {
5644        self.unary_op(Op::Sin)
5645    }
5646
5647    /// Append a `Cos` node.
5648    pub fn cos(&self) -> NodeHandle {
5649        self.unary_op(Op::Cos)
5650    }
5651
5652    /// Append a `Tanh` node.
5653    pub fn tanh(&self) -> NodeHandle {
5654        self.unary_op(Op::Tanh)
5655    }
5656
5657    /// Append a `Sigmoid` node.
5658    pub fn sigmoid(&self) -> NodeHandle {
5659        self.unary_op(Op::Sigmoid)
5660    }
5661
5662    /// Append a `Silu` node (SiLU/Swish activation: `x · sigmoid(x)`).
5663    pub fn silu(&self) -> NodeHandle {
5664        self.unary_op(Op::Silu)
5665    }
5666
5667    /// Append a `GeluTanh` node (tanh-approximation GELU).
5668    pub fn gelu_tanh(&self) -> NodeHandle {
5669        self.unary_op(Op::GeluTanh)
5670    }
5671
5672    /// Append a `Step` node (Heaviside step: `1` where `x > 0`, else `0`).
5673    pub fn step(&self) -> NodeHandle {
5674        self.unary_op(Op::Step)
5675    }
5676
5677    /// Append a `Recip` node (`1 / self`).
5678    pub fn recip(&self) -> NodeHandle {
5679        self.unary_op(Op::Recip)
5680    }
5681
5682    /// Append an `Abs` node (`|self|`).
5683    pub fn abs(&self) -> NodeHandle {
5684        self.unary_op(Op::Abs)
5685    }
5686
5687    // ---- In-place unary builders (Phase 2 of the in-place ops
5688    // infrastructure) ----
5689    //
5690    // Each emits an `Op::*Inplace` node whose input is `self`. The
5691    // returned `NodeHandle` shares the underlying graph and is the new
5692    // root; subsequent ops should use the returned handle to make the
5693    // mutation-after-read ordering observable to `derive_ordering`.
5694    //
5695    // Phase 4 (the mutation-safety pass) is what makes these safe to
5696    // call on tape-tracked tensors. Until Phase 4 lands, calling these
5697    // on a tensor that's been saved for backward will panic at
5698    // `NodeHandle::backward` time (clear error, no silent gradient
5699    // corruption).
5700
5701    /// Append a `ReluInplace` node — mutates `self`'s storage with
5702    /// `max(0, self)`. See `NodeHandle::relu` for the functional variant.
5703    pub fn relu_inplace(&self) -> NodeHandle {
5704        self.unary_op(Op::ReluInplace)
5705    }
5706
5707    /// Append a `SiluInplace` node — mutates `self`'s storage with
5708    /// `self * sigmoid(self)`. See `NodeHandle::silu` for the functional
5709    /// variant.
5710    pub fn silu_inplace(&self) -> NodeHandle {
5711        self.unary_op(Op::SiluInplace)
5712    }
5713
5714    /// Append a `GeluTanhInplace` node — mutates `self`'s storage with
5715    /// the tanh-approximation GELU. See `NodeHandle::gelu_tanh` for the
5716    /// functional variant.
5717    pub fn gelu_tanh_inplace(&self) -> NodeHandle {
5718        self.unary_op(Op::GeluTanhInplace)
5719    }
5720
5721    /// Append a `TanhInplace` node — mutates `self`'s storage with
5722    /// `tanh(self)`. See `NodeHandle::tanh` for the functional variant.
5723    pub fn tanh_inplace(&self) -> NodeHandle {
5724        self.unary_op(Op::TanhInplace)
5725    }
5726
5727    /// Append a `SigmoidInplace` node — mutates `self`'s storage
5728    /// with `sigmoid(self)`. See `NodeHandle::sigmoid` for the functional
5729    /// variant.
5730    pub fn sigmoid_inplace(&self) -> NodeHandle {
5731        self.unary_op(Op::SigmoidInplace)
5732    }
5733
5734    /// Append a `NegInplace` node — mutates `self`'s storage with
5735    /// `-self`. See `NodeHandle::neg` for the functional variant.
5736    pub fn neg_inplace(&self) -> NodeHandle {
5737        self.unary_op(Op::NegInplace)
5738    }
5739
5740    /// Append an `AbsInplace` node — mutates `self`'s storage with
5741    /// `|self|`. See `NodeHandle::abs` for the functional variant.
5742    pub fn abs_inplace(&self) -> NodeHandle {
5743        self.unary_op(Op::AbsInplace)
5744    }
5745
5746    /// Append a `SqrInplace` node — mutates `self`'s storage with
5747    /// `self²`. See `NodeHandle::sqr` for the functional variant.
5748    pub fn sqr_inplace(&self) -> NodeHandle {
5749        self.unary_op(Op::SqrInplace)
5750    }
5751
5752    /// Append a `SqrtInplace` node — mutates `self`'s storage with
5753    /// `√self`. See `NodeHandle::sqrt` for the functional variant.
5754    pub fn sqrt_inplace(&self) -> NodeHandle {
5755        self.unary_op(Op::SqrtInplace)
5756    }
5757
5758    /// Append a `RsqrtInplace` node — mutates `self`'s storage with
5759    /// `1/√self`. See `NodeHandle::rsqrt` for the functional variant.
5760    pub fn rsqrt_inplace(&self) -> NodeHandle {
5761        self.unary_op(Op::RsqrtInplace)
5762    }
5763
5764    /// Append a `RecipInplace` node — mutates `self`'s storage with
5765    /// `1/self`. See `NodeHandle::recip` for the functional variant.
5766    pub fn recip_inplace(&self) -> NodeHandle {
5767        self.unary_op(Op::RecipInplace)
5768    }
5769
5770    /// Append an `ExpInplace` node — mutates `self`'s storage with
5771    /// `exp(self)`. See `NodeHandle::exp` for the functional variant.
5772    pub fn exp_inplace(&self) -> NodeHandle {
5773        self.unary_op(Op::ExpInplace)
5774    }
5775
5776    /// Append a `LogInplace` node — mutates `self`'s storage with
5777    /// `ln(self)`. See `NodeHandle::log` for the functional variant.
5778    pub fn log_inplace(&self) -> NodeHandle {
5779        self.unary_op(Op::LogInplace)
5780    }
5781
5782    /// Append a `SinInplace` node — mutates `self`'s storage with
5783    /// `sin(self)`. See `NodeHandle::sin` for the functional variant.
5784    pub fn sin_inplace(&self) -> NodeHandle {
5785        self.unary_op(Op::SinInplace)
5786    }
5787
5788    /// Append a `CosInplace` node — mutates `self`'s storage with
5789    /// `cos(self)`. See `NodeHandle::cos` for the functional variant.
5790    pub fn cos_inplace(&self) -> NodeHandle {
5791        self.unary_op(Op::CosInplace)
5792    }
5793
5794    /// Append a `SignInplace` node — mutates `self`'s storage with
5795    /// `sign(self)`. See `NodeHandle::sign` for the functional variant.
5796    pub fn sign_inplace(&self) -> NodeHandle {
5797        self.unary_op(Op::SignInplace)
5798    }
5799
5800    /// Append a `FloorInplace` node — mutates `self`'s storage with
5801    /// `⌊self⌋`. See `NodeHandle::floor` for the functional variant.
5802    pub fn floor_inplace(&self) -> NodeHandle {
5803        self.unary_op(Op::FloorInplace)
5804    }
5805
5806    /// Append a `CeilInplace` node — mutates `self`'s storage with
5807    /// `⌈self⌉`. See `NodeHandle::ceil` for the functional variant.
5808    pub fn ceil_inplace(&self) -> NodeHandle {
5809        self.unary_op(Op::CeilInplace)
5810    }
5811
5812    /// Append a `RoundInplace` node — mutates `self`'s storage with
5813    /// `round(self)`. See `NodeHandle::round` for the functional variant.
5814    pub fn round_inplace(&self) -> NodeHandle {
5815        self.unary_op(Op::RoundInplace)
5816    }
5817
5818    /// Append an `ErfInplace` node — mutates `self`'s storage with
5819    /// `erf(self)`. See `NodeHandle::erf` for the functional variant.
5820    pub fn erf_inplace(&self) -> NodeHandle {
5821        self.unary_op(Op::ErfInplace)
5822    }
5823
5824    /// Append a `GeluInplace` node — mutates `self`'s storage
5825    /// with the exact-GeLU formula. See `NodeHandle::gelu` for the
5826    /// functional variant.
5827    pub fn gelu_inplace(&self) -> NodeHandle {
5828        self.unary_op(Op::GeluInplace)
5829    }
5830
5831    /// Append a `ClampInplace { min, max }` node — mutates `self`'s
5832    /// storage with `clamp(self, min, max)`. See `NodeHandle::clamp` for
5833    /// the functional variant.
5834    pub fn clamp_inplace(&self, min: f64, max: f64) -> NodeHandle {
5835        self.unary_op(Op::ClampInplace { min, max })
5836    }
5837
5838    /// Append a `PowIInplace(exp)` node — mutates `self`'s storage
5839    /// with `self.powi(exp)`. See `NodeHandle::powi` for the functional
5840    /// variant.
5841    pub fn powi_inplace(&self, exp: i32) -> NodeHandle {
5842        self.unary_op(Op::PowIInplace(exp))
5843    }
5844
5845    /// Append an `Op::Fused(INPLACE_AFFINE, ...)` node — mutates
5846    /// `self`'s storage with `self = mul · self + add`. Single-input
5847    /// fused op (no functional `Op::Affine` exists on
5848    /// `fuel-graph::Op`; the non-inplace equivalent is `self
5849    /// .mul_scalar(mul).add_scalar(add)`). Wired to baracuda's
5850    /// `affine_inplace_*` symbol on CUDA when Phase 3 lands.
5851    pub fn affine_inplace(&self, mul: f64, add: f64) -> NodeHandle {
5852        let shape = self.shape();
5853        let dtype = self.dtype();
5854        let id = self.graph.write().unwrap().push(Node {
5855            op: Op::Fused(
5856                crate::registry::FusedOps::INPLACE_AFFINE,
5857                crate::registry::FusedOpParams::InplaceAffine { mul, add },
5858            ),
5859            inputs: vec![self.id],
5860            shape,
5861            dtype,
5862        });
5863        Self {
5864            graph: self.graph.clone(),
5865            id,
5866        }
5867    }
5868
5869    /// Append a `Floor` node (`⌊self⌋`). Output dtype = input dtype.
5870    /// Backward is the zero distribution almost everywhere; gradient
5871    /// is dropped silently.
5872    pub fn floor(&self) -> NodeHandle {
5873        self.unary_op(Op::Floor)
5874    }
5875
5876    /// Append a `Ceil` node (`⌈self⌉`). Output dtype = input dtype.
5877    /// Backward drops gradient (non-differentiable almost everywhere).
5878    pub fn ceil(&self) -> NodeHandle {
5879        self.unary_op(Op::Ceil)
5880    }
5881
5882    /// Append a `Round` node — banker's rounding (round-half-to-even,
5883    /// IEEE 754 roundeven). 0.5 → 0, 1.5 → 2, 2.5 → 2, 3.5 → 4.
5884    /// Output dtype = input dtype. Backward drops gradient.
5885    pub fn round(&self) -> NodeHandle {
5886        self.unary_op(Op::Round)
5887    }
5888
5889    /// Append a `Sign` node (`-1` / `0` / `1`). `sign(0) = 0` by
5890    /// subgradient convention. Output dtype = input dtype. Backward
5891    /// drops gradient.
5892    pub fn sign(&self) -> NodeHandle {
5893        self.unary_op(Op::Sign)
5894    }
5895
5896    /// Append an `Erf` node (Gauss error function). Output dtype =
5897    /// input dtype. Differentiable.
5898    pub fn erf(&self) -> NodeHandle {
5899        self.unary_op(Op::Erf)
5900    }
5901
5902    /// Append a `Gelu` node — exact-erf formulation of GELU
5903    /// (`0.5 * x * (1 + erf(x/√2))`). Distinct from [`Self::gelu_tanh`]
5904    /// (tanh approximation). Output dtype = input dtype.
5905    /// Differentiable.
5906    pub fn gelu(&self) -> NodeHandle {
5907        self.unary_op(Op::Gelu)
5908    }
5909
5910    /// Append a `Pow` node `pow(self, other)` element-wise (real
5911    /// exponent). Both operands must share dtype and shape. Distinct
5912    /// from [`Self::powi`] (scalar `i32` exponent). NaN follows
5913    /// IEEE-754 (`pow(-2, 0.5) = NaN`).
5914    ///
5915    /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5916    /// typed error, not a panic.
5917    pub fn pow(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5918        let out_shape = self.shape();
5919        self.try_binary_op("pow", Op::Pow, other, out_shape)
5920    }
5921
5922    /// Append an `Rsqrt` node (`1 / sqrt(self)`). Same dtype as
5923    /// input. Single op rather than `sqrt(x).recip()` — one kernel
5924    /// launch and matches RMSNorm's `x * rsqrt(...)` shape.
5925    /// Differentiable.
5926    pub fn rsqrt(&self) -> NodeHandle {
5927        self.unary_op(Op::Rsqrt)
5928    }
5929
5930    /// Append a `Rem` node `self % other` element-wise (PyTorch
5931    /// convention: `a - floor(a/b) * b`, sign of result matches
5932    /// divisor). Both operands must share dtype and shape.
5933    /// Differentiable.
5934    ///
5935    /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5936    /// typed error, not a panic.
5937    pub fn rem(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5938        let out_shape = self.shape();
5939        self.try_binary_op("rem", Op::Rem, other, out_shape)
5940    }
5941
5942    /// Append a `Flip` node — reverses element order along `dim`.
5943    /// Output shape == input shape. Materializing op (real byte
5944    /// shuffle; not a metadata-only view). Differentiable
5945    /// (involutive: backward is another Flip on the same dim).
5946    ///
5947    /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5948    pub fn flip(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5949        let in_shape = self.shape();
5950        let rank = in_shape.dims().len();
5951        if dim >= rank {
5952            return Err(fuel_ir::Error::Msg(format!(
5953                "flip: dim {dim} out of bounds for rank {rank}",
5954            ))
5955            .bt());
5956        }
5957        let op = Op::Flip { dim };
5958        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5959        let id = self.graph.write().unwrap().push(Node {
5960            op,
5961            inputs: vec![self.id],
5962            shape,
5963            dtype,
5964        });
5965        Ok(Self {
5966            graph: self.graph.clone(),
5967            id,
5968        })
5969    }
5970
5971    /// Append a `Roll` node — cyclic shift along `dim` by `shift`
5972    /// positions. Positive `shift` moves elements to higher indices
5973    /// (wrapping); negative the opposite. Output shape == input
5974    /// shape. Differentiable (backward is `Roll { dim, -shift }`).
5975    ///
5976    /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5977    pub fn roll(&self, dim: usize, shift: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5978        let in_shape = self.shape();
5979        let rank = in_shape.dims().len();
5980        if dim >= rank {
5981            return Err(fuel_ir::Error::Msg(format!(
5982                "roll: dim {dim} out of bounds for rank {rank}",
5983            ))
5984            .bt());
5985        }
5986        let op = Op::Roll { dim, shift };
5987        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5988        let id = self.graph.write().unwrap().push(Node {
5989            op,
5990            inputs: vec![self.id],
5991            shape,
5992            dtype,
5993        });
5994        Ok(Self {
5995            graph: self.graph.clone(),
5996            id,
5997        })
5998    }
5999
6000    /// Append a `CumSum` node — running cumulative sum along `dim`.
6001    /// Output shape == input shape. Differentiable; backward is
6002    /// reverse-cumsum (`Flip → CumSum → Flip`).
6003    ///
6004    /// **Returns `Result`**: bad `dim` surfaces as a typed error.
6005    pub fn cumsum(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6006        let in_shape = self.shape();
6007        let rank = in_shape.dims().len();
6008        if dim >= rank {
6009            return Err(fuel_ir::Error::Msg(format!(
6010                "cumsum: dim {dim} out of bounds for rank {rank}",
6011            ))
6012            .bt());
6013        }
6014        let dtype = self.dtype();
6015        let id = self.graph.write().unwrap().push(Node {
6016            op: Op::CumSum { dim },
6017            inputs: vec![self.id],
6018            shape: in_shape,
6019            dtype,
6020        });
6021        Ok(Self {
6022            graph: self.graph.clone(),
6023            id,
6024        })
6025    }
6026
6027    /// Append a `Triu` node — upper-triangular mask along the last two
6028    /// dims. `diagonal = 0` keeps the main diagonal and above; positive
6029    /// values shift the cutoff up (keeping less); negative shift down
6030    /// (keeping more, including subdiagonals).
6031    ///
6032    /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6033    pub fn triu(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6034        let in_shape = self.shape();
6035        let rank = in_shape.dims().len();
6036        if rank < 2 {
6037            return Err(fuel_ir::Error::Msg(format!(
6038                "triu: input must have rank >= 2, got {rank}",
6039            ))
6040            .bt());
6041        }
6042        let dtype = self.dtype();
6043        let id = self.graph.write().unwrap().push(Node {
6044            op: Op::Triu { diagonal },
6045            inputs: vec![self.id],
6046            shape: in_shape,
6047            dtype,
6048        });
6049        Ok(Self {
6050            graph: self.graph.clone(),
6051            id,
6052        })
6053    }
6054
6055    /// Append an [`Op::Scan`] node — a bounded `lax.scan` recurrence.
6056    /// `self` is the `init_carry`. The body must already be built in the same
6057    /// graph, referencing `Op::ScanPlaceholder{Carry,0}` for the per-step
6058    /// carry and `Op::ScanPlaceholder{Elem,i}` for the per-step slice of
6059    /// `xs[i]`; `consts` are referenced by real NodeId. `body_new_carry` /
6060    /// `body_y` are the body's two exit nodes. Always a 2-slot bundle
6061    /// (slot 0 = stacked `ys` `[bound] ++ body_y`, slot 1 = final carry);
6062    /// `emit` selects which slot this call projects. `early_exit` is Phase 2
6063    /// (always `None` here).
6064    ///
6065    /// **Returns `Result`**: a malformed body/carry/bound surfaces as a typed
6066    /// error — never a panic.
6067    pub fn scan(
6068        &self,
6069        xs: &[NodeHandle],
6070        consts: &[NodeHandle],
6071        body_new_carry: &NodeHandle,
6072        body_y: &NodeHandle,
6073        bound: usize,
6074        emit: ScanEmit,
6075    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6076        let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6077        if !same_graph(body_new_carry)
6078            || !same_graph(body_y)
6079            || !xs.iter().all(same_graph)
6080            || !consts.iter().all(same_graph)
6081        {
6082            return Err(fuel_ir::Error::Msg(
6083                "scan: init_carry, xs, consts, and body exits must live on one graph".into(),
6084            )
6085            .bt());
6086        }
6087        if bound == 0 {
6088            return Err(fuel_ir::Error::Msg("scan: bound must be >= 1".into()).bt());
6089        }
6090        let carry_shape = self.shape();
6091        if body_new_carry.shape().dims() != carry_shape.dims() {
6092            return Err(fuel_ir::Error::Msg(format!(
6093                "scan: body_new_carry shape {:?} must equal init_carry shape {:?}",
6094                body_new_carry.shape().dims(),
6095                carry_shape.dims(),
6096            ))
6097            .bt());
6098        }
6099        // Validate body placeholders at graph-build time (single-carry; every
6100        // Elem index < n_xs) so a malformed body is a typed Err here, not a
6101        // later `elem[index]` panic on the unroll / forward-driver path.
6102        {
6103            let g = self.graph.read().unwrap();
6104            crate::scan::validate_scan_body_placeholders(
6105                &g,
6106                &[body_new_carry.id, body_y.id],
6107                // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6108                // construction below); the IR and the unroll are not.
6109                1,
6110                xs.len(),
6111            )?;
6112        }
6113        let carry_dtype = self.dtype();
6114        let y_dtype = body_y.dtype();
6115
6116        // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6117        let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6118        ys_dims.push(bound);
6119        ys_dims.extend_from_slice(body_y.shape().dims());
6120        let ys_shape = Shape::from_dims(&ys_dims);
6121        let specs = vec![
6122            fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6123            fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6124        ];
6125        let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs)
6126            .map_err(|e| fuel_ir::Error::Msg(format!("scan: compose_bundle failed: {e}")).bt())?;
6127
6128        let mut inputs: Vec<NodeId> = Vec::with_capacity(2 + xs.len() + consts.len() + 2);
6129        inputs.push(self.id);
6130        inputs.extend(xs.iter().map(|t| t.id));
6131        inputs.extend(consts.iter().map(|t| t.id));
6132        inputs.push(body_new_carry.id);
6133        inputs.push(body_y.id);
6134
6135        let id = {
6136            let mut g = self.graph.write().unwrap();
6137            // Node.shape/dtype are the PRIMARY (slot-0) shape/dtype per the
6138            // multi-output authoring contract.
6139            let id = g.push(Node {
6140                op: Op::Scan {
6141                    // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6142                    // `parse_scan_layout` and `build_scan_step` all handle N
6143                    // carries. This BUILDER deliberately still constructs ONE.
6144                    //
6145                    // Widening it means N+1 output-view specs through
6146                    // `compose_bundle` below -- i.e. the bundle arity -- which is
6147                    // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6148                    // is NOT this change. A reader must not read "the builder makes
6149                    // one" as "multi-carry does not work".
6150                    n_carries: 1,
6151                    n_xs: xs.len(),
6152                    bound,
6153                    emit,
6154                    early_exit: None,
6155                },
6156                inputs,
6157                shape: ys_shape,
6158                dtype: y_dtype,
6159            });
6160            g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6161                .map_err(|e| {
6162                    fuel_ir::Error::Msg(format!("scan: set_output_views failed: {e}")).bt()
6163                })?;
6164            id
6165        };
6166        let producer = Self {
6167            graph: self.graph.clone(),
6168            id,
6169        };
6170        match emit {
6171            ScanEmit::All => producer.view(0),
6172            ScanEmit::Final => producer.view(1),
6173        }
6174    }
6175
6176    /// Append an early-exit [`Op::Scan`] node — the `Result`-returning sibling
6177    /// of [`NodeHandle::scan`] that carries a convergence predicate as the extra
6178    /// trailing input (`early_exit = Some(ScanPredicate)`). `self` is the
6179    /// `init_carry`; `pred_exit` is a scalar-`U8` sub-DAG over the carry
6180    /// (`Op::ScanPlaceholder{Carry,0}` for the pre-step carry, and the shared
6181    /// `body_new_carry` node for the post-step carry) that stops iteration when
6182    /// it fires. The runtime stop count is data-dependent under the static
6183    /// capacity `bound`.
6184    ///
6185    /// **`consts` must include every const referenced by the body OR the
6186    /// predicate** — the clone/unroll machinery shares only `consts`; a
6187    /// predicate const outside `consts` would be re-cloned dataless and fail at
6188    /// realize.
6189    ///
6190    /// **Returns `Result`**: a malformed body/carry/bound, or a non-scalar /
6191    /// non-`U8` / `Elem`-referencing predicate, surfaces as a typed error —
6192    /// never a panic (validated at graph-build time).
6193    pub fn scan_until(
6194        &self,
6195        xs: &[NodeHandle],
6196        consts: &[NodeHandle],
6197        body_new_carry: &NodeHandle,
6198        body_y: &NodeHandle,
6199        pred_exit: &NodeHandle,
6200        bound: usize,
6201        emit: ScanEmit,
6202    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6203        let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6204        if !same_graph(body_new_carry)
6205            || !same_graph(body_y)
6206            || !same_graph(pred_exit)
6207            || !xs.iter().all(same_graph)
6208            || !consts.iter().all(same_graph)
6209        {
6210            return Err(fuel_ir::Error::Msg(
6211                "scan_until: init_carry, xs, consts, body exits, and pred_exit must live on one graph".into(),
6212            ).bt());
6213        }
6214        if bound == 0 {
6215            return Err(fuel_ir::Error::Msg("scan_until: bound must be >= 1".into()).bt());
6216        }
6217        let carry_shape = self.shape();
6218        if body_new_carry.shape().dims() != carry_shape.dims() {
6219            return Err(fuel_ir::Error::Msg(format!(
6220                "scan_until: body_new_carry shape {:?} must equal init_carry shape {:?}",
6221                body_new_carry.shape().dims(),
6222                carry_shape.dims(),
6223            ))
6224            .bt());
6225        }
6226        // Validate body placeholders at graph-build time (single-carry; every
6227        // Elem index < n_xs) so a malformed body is a typed Err here, not a
6228        // later `elem[index]` panic in the forward driver's build_scan_step.
6229        {
6230            let g = self.graph.read().unwrap();
6231            crate::scan::validate_scan_body_placeholders(
6232                &g,
6233                &[body_new_carry.id, body_y.id],
6234                // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6235                // construction below); the IR and the unroll are not.
6236                1,
6237                xs.len(),
6238            )?;
6239        }
6240        // Predicate must be a scalar Bool (shape [] or product == 1) — a
6241        // convergence flag, not a per-element mask. Validate at build time.
6242        // GAP-168(c): Bool, not U8. A predicate's natural producer is a
6243        // comparison, and those now yield Bool, so requiring U8 here would make
6244        // the ordinary `carry.ge(&thr)` path unusable as a predicate.
6245        if pred_exit.dtype() != fuel_ir::DType::Bool {
6246            return Err(fuel_ir::Error::Msg(format!(
6247                "scan_until: pred_exit must be Bool (a boolean flag), got {:?}",
6248                pred_exit.dtype(),
6249            ))
6250            .bt());
6251        }
6252        let pred_dims = pred_exit.shape();
6253        let pred_numel: usize = pred_dims.dims().iter().product();
6254        if pred_numel != 1 {
6255            return Err(fuel_ir::Error::Msg(format!(
6256                "scan_until: pred_exit must be a scalar (shape [] or [1]/all-ones), got {:?}",
6257                pred_dims.dims(),
6258            ))
6259            .bt());
6260        }
6261        // Every ScanPlaceholder reachable from pred_exit must be Carry{0} — the
6262        // predicate is over the carry, never a per-step Elem slice.
6263        {
6264            let g = self.graph.read().unwrap();
6265            for &id in &crate::topo_order_multi(&g, &[pred_exit.id]) {
6266                if let Op::ScanPlaceholder { role, index } = &g.node(id).op {
6267                    let bad = matches!(role, ScanRole::Elem) || *index != 0;
6268                    if bad {
6269                        return Err(fuel_ir::Error::Msg(format!(
6270                            "scan_until: pred_exit references ScanPlaceholder{{{role:?}, {index}}} — \
6271                             the predicate may only read the carry (Carry, index 0)",
6272                        )).bt());
6273                    }
6274                }
6275            }
6276        }
6277        let carry_dtype = self.dtype();
6278        let y_dtype = body_y.dtype();
6279
6280        // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6281        let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6282        ys_dims.push(bound);
6283        ys_dims.extend_from_slice(body_y.shape().dims());
6284        let ys_shape = Shape::from_dims(&ys_dims);
6285        let specs = vec![
6286            fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6287            fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6288        ];
6289        let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs).map_err(|e| {
6290            fuel_ir::Error::Msg(format!("scan_until: compose_bundle failed: {e}")).bt()
6291        })?;
6292
6293        let mut inputs: Vec<NodeId> = Vec::with_capacity(3 + xs.len() + consts.len());
6294        inputs.push(self.id);
6295        inputs.extend(xs.iter().map(|t| t.id));
6296        inputs.extend(consts.iter().map(|t| t.id));
6297        inputs.push(body_new_carry.id);
6298        inputs.push(body_y.id);
6299        inputs.push(pred_exit.id); // <-- the C1 trailing predicate
6300
6301        let id = {
6302            let mut g = self.graph.write().unwrap();
6303            let id = g.push(Node {
6304                op: Op::Scan {
6305                    // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6306                    // `parse_scan_layout` and `build_scan_step` all handle N
6307                    // carries. This BUILDER deliberately still constructs ONE.
6308                    //
6309                    // Widening it means N+1 output-view specs through
6310                    // `compose_bundle` below -- i.e. the bundle arity -- which is
6311                    // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6312                    // is NOT this change. A reader must not read "the builder makes
6313                    // one" as "multi-carry does not work".
6314                    n_carries: 1,
6315                    n_xs: xs.len(),
6316                    bound,
6317                    emit,
6318                    early_exit: Some(ScanPredicate),
6319                },
6320                inputs,
6321                shape: ys_shape,
6322                dtype: y_dtype,
6323            });
6324            g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6325                .map_err(|e| {
6326                    fuel_ir::Error::Msg(format!("scan_until: set_output_views failed: {e}")).bt()
6327                })?;
6328            id
6329        };
6330        let producer = Self {
6331            graph: self.graph.clone(),
6332            id,
6333        };
6334        match emit {
6335            ScanEmit::All => producer.view(0),
6336            ScanEmit::Final => producer.view(1),
6337        }
6338    }
6339
6340    /// Append a `Tril` node — lower-triangular mask along the last two
6341    /// dims. `diagonal = 0` keeps the main diagonal and below.
6342    /// `tril(diagonal = 0)` is the canonical causal-attention mask.
6343    ///
6344    /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6345    pub fn tril(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6346        let in_shape = self.shape();
6347        let rank = in_shape.dims().len();
6348        if rank < 2 {
6349            return Err(fuel_ir::Error::Msg(format!(
6350                "tril: input must have rank >= 2, got {rank}",
6351            ))
6352            .bt());
6353        }
6354        let dtype = self.dtype();
6355        let id = self.graph.write().unwrap().push(Node {
6356            op: Op::Tril { diagonal },
6357            inputs: vec![self.id],
6358            shape: in_shape,
6359            dtype,
6360        });
6361        Ok(Self {
6362            graph: self.graph.clone(),
6363            id,
6364        })
6365    }
6366
6367    /// Append a `LogSoftmaxLastDim` node. Output shape == input shape.
6368    /// Numerically stable (max-subtracting formula) — preferred over
6369    /// `log(softmax(x))` for NLL / cross-entropy loss.
6370    ///
6371    /// **Returns `Result`**: rank < 1 surfaces as a typed error.
6372    pub fn log_softmax_last_dim(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6373        let in_shape = self.shape();
6374        if in_shape.dims().is_empty() {
6375            return Err(fuel_ir::Error::Msg(
6376                "log_softmax_last_dim: input must have rank >= 1".to_string(),
6377            )
6378            .bt());
6379        }
6380        let dtype = self.dtype();
6381        let id = self.graph.write().unwrap().push(Node {
6382            op: Op::LogSoftmaxLastDim,
6383            inputs: vec![self.id],
6384            shape: in_shape,
6385            dtype,
6386        });
6387        Ok(Self {
6388            graph: self.graph.clone(),
6389            id,
6390        })
6391    }
6392
6393    /// Append a `MaskedFill` node. `mask` must be `Bool` (GAP-168(c)) and have
6394    /// the same shape as `self`. Every position where `mask` is true gets `value`;
6395    /// every position where `mask == 0` passes `self` through. `value`
6396    /// is a scalar of `self`'s dtype.
6397    ///
6398    /// **Returns `Result`**: shape or dtype mismatches surface as typed
6399    /// errors.
6400    pub fn masked_fill(
6401        &self,
6402        mask: &NodeHandle,
6403        value: Scalar,
6404    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6405        self.require_same_graph(mask, "masked_fill", "mask")?;
6406        if self.shape().dims() != mask.shape().dims() {
6407            return Err(fuel_ir::Error::Msg(format!(
6408                "masked_fill: x.shape={:?} != mask.shape={:?}",
6409                self.shape().dims(),
6410                mask.shape().dims(),
6411            ))
6412            .bt());
6413        }
6414        if mask.dtype() != DType::Bool {
6415            return Err(fuel_ir::Error::Msg(format!(
6416                "masked_fill: mask dtype must be Bool, got {:?} — cast a numeric \
6417                 mask to Bool explicitly (GAP-168(c))",
6418                mask.dtype(),
6419            ))
6420            .bt());
6421        }
6422        // GAP-002 (D5) / GAP-075 (fix B): classify EVERY dtype explicitly — no
6423        // wildcard default. The guard is SEMANTIC: masked_fill needs a
6424        // representable fill value AND a zero (the backward fills with zero), so
6425        // it rejects the packed formats (F4/F6*, no scalar fill) and the
6426        // block-scales (F8E8M0/F8E6M2, no zero), and permits the ordinary
6427        // numeric dtypes. Rejecting on the guard's own terms also keeps the
6428        // `Scalar::zero` Err branch in the MaskedFill `backward` arm provably
6429        // unreachable in a well-formed graph.
6430        //
6431        // Under the OLD denylist (`matches!(reject-set)`, else allow) a FUTURE
6432        // dtype fell through to "permitted" SILENTLY. With new dtypes scheduled
6433        // (GAP-097: e5m2, complex, sub-byte int, …) that would silently accept
6434        // masked_fill on formats whose fill semantics are unsettled. An
6435        // exhaustive match makes a new dtype a COMPILE ERROR here, forcing the
6436        // person who adds it to decide its permission consciously — the compiler
6437        // is the real guard; the tests below protect the existing classification.
6438        //
6439        // NOTE: "permitted" is a graph-build PERMISSION (is masked_fill
6440        // semantically well-defined?), NOT a promise a backend can allocate/run
6441        // the dtype. An unimplemented storage still declines loudly downstream
6442        // (typed `UnsupportedDTypeForOp` at allocation), which is the sound
6443        // composition — a semantically-true guard upstream, a loud capability
6444        // decline downstream.
6445        match self.dtype() {
6446            DType::F4 | DType::F6E2M3 | DType::F6E3M2 | DType::F8E8M0 | DType::F8E6M2 => {
6447                return Err(
6448                    fuel_ir::Error::UnsupportedDTypeForOp(self.dtype(), "masked_fill").bt(),
6449                );
6450            }
6451            DType::U8
6452            | DType::I8
6453            | DType::U32
6454            | DType::I16
6455            | DType::I32
6456            | DType::I64
6457            | DType::BF16
6458            | DType::F16
6459            | DType::F32
6460            | DType::F64
6461            | DType::F8E4M3
6462            // GAP-097: F8E5M2 is PERMITTED, on the guard's own semantic terms.
6463            //
6464            // The reject set above is not "exotic dtypes" — it is two distinct
6465            // NON-VALUE categories: the block-scales (F8E8M0/F8E6M2) ride as
6466            // sibling operands and are not element value dtypes at all, and the
6467            // block-scoped elements (F4/F6*) have no standalone byte layout, so
6468            // a single element is not addressable without its block. Neither has
6469            // a well-defined fill-one-element operation, which is what this op
6470            // needs. F8E5M2 is a value dtype in exactly the way F8E4M3 (already
6471            // permitted, directly above) is: sign + exponent + mantissa, a
6472            // standalone byte layout, a representable zero for the backward, and
6473            // a representable fill value. So permitting it CONTINUES the
6474            // existing classification; rejecting would be the exception.
6475            //
6476            // Weighed and rejected as grounds for the opposite call: F8E5M2
6477            // currently has NO host or CUDA storage (fuel-cpu-backend and
6478            // fuel-cuda-backend both decline it), so this permits a graph the
6479            // backends cannot yet allocate — GAP(GAP-161) tracks that storage
6480            // decline and its expiry. That is the NOTE above working as
6481            // designed — permission is semantic, allocation is a capability, and
6482            // they are different questions. Writing REJECT here would encode the
6483            // claim "F8E5M2 has no representable fill value", which is FALSE and
6484            // would outlive the storage gap that motivated it.
6485            | DType::F8E5M2
6486            // GAP-168(c): Bool is a value dtype with a representable fill value
6487            // (true/false) and a zero for the backward (false) — permitted on
6488            // this guard's own semantic terms, exactly as the FP8 value dtypes
6489            // are. (This is the FILLED tensor's dtype; the MASK dtype is checked
6490            // separately above.)
6491            | DType::Bool => {}
6492        }
6493        if value.dtype() != self.dtype() {
6494            return Err(fuel_ir::Error::Msg(format!(
6495                "masked_fill: value dtype {:?} != x dtype {:?}",
6496                value.dtype(),
6497                self.dtype(),
6498            ))
6499            .bt());
6500        }
6501        let op = Op::MaskedFill { value };
6502        let (shape, dtype) = crate::shape::primitive_shape(
6503            &op,
6504            &[self.shape(), mask.shape()],
6505            &[self.dtype(), mask.dtype()],
6506        )
6507        .expect("masked_fill: shapes/dtypes validated above");
6508        let id = self.graph.write().unwrap().push(Node {
6509            op,
6510            inputs: vec![self.id, mask.id],
6511            shape,
6512            dtype,
6513        });
6514        Ok(Self {
6515            graph: self.graph.clone(),
6516            id,
6517        })
6518    }
6519
6520    /// Append a `Pad` node — multi-dim padding. `padding[i] = (before, after)`
6521    /// for axis `i`; `padding.len()` must equal `self.rank()`.
6522    /// Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
6523    /// `value` is the fill constant for [`PadMode::Constant`]
6524    /// (ignored for other modes).
6525    ///
6526    /// Only Constant mode is wired through the executor in the v1
6527    /// cut; the other modes produce a clean error at realize time.
6528    /// Differentiable for Constant (backward slices the gradient
6529    /// along each padded axis to restore the input shape).
6530    ///
6531    /// **Returns `Result`**: rank mismatch surfaces as a typed error.
6532    pub fn pad(
6533        &self,
6534        padding: Vec<(usize, usize)>,
6535        mode: PadMode,
6536        value: f64,
6537    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6538        let in_shape = self.shape();
6539        let rank = in_shape.dims().len();
6540        if padding.len() != rank {
6541            return Err(fuel_ir::Error::Msg(format!(
6542                "pad: padding.len() ({}) must equal tensor rank ({rank})",
6543                padding.len(),
6544            ))
6545            .bt());
6546        }
6547        let op = Op::Pad {
6548            padding,
6549            mode,
6550            value,
6551        };
6552        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6553        let id = self.graph.write().unwrap().push(Node {
6554            op,
6555            inputs: vec![self.id],
6556            shape,
6557            dtype,
6558        });
6559        Ok(Self {
6560            graph: self.graph.clone(),
6561            id,
6562        })
6563    }
6564
6565    /// Append an `Equal` node (`self == other`) producing a `Bool` mask.
6566    /// Both operands must share dtype and shape; output dtype is `Bool`
6567    /// (`1` where equal, `0` otherwise). NaN follows IEEE-754
6568    /// (`NaN == NaN` is false). Non-differentiable.
6569    ///
6570    /// # Panics
6571    ///
6572    /// Panics if any operand belongs to a different [`Graph`] than the one this
6573    /// builder is building into. Operand identity is graph-scoped and checked by
6574    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6575    /// deliberate and replaces the hang a cross-graph handle used to produce.
6576    /// Build every operand from one graph, or use a `Result`-returning entry
6577    /// point where one exists.
6578    pub fn eq(&self, other: &NodeHandle) -> NodeHandle {
6579        self.binary_compare_op("eq", Op::Equal, other)
6580    }
6581
6582    /// Append a `Ne` node (`self != other`) producing a `Bool` mask.
6583    /// Same shape/dtype contract as [`Self::eq`]. NaN follows
6584    /// IEEE-754 (`NaN != NaN` is true → `1`). Non-differentiable.
6585    ///
6586    /// # Panics
6587    ///
6588    /// Panics if any operand belongs to a different [`Graph`] than the one this
6589    /// builder is building into. Operand identity is graph-scoped and checked by
6590    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6591    /// deliberate and replaces the hang a cross-graph handle used to produce.
6592    /// Build every operand from one graph, or use a `Result`-returning entry
6593    /// point where one exists.
6594    pub fn ne(&self, other: &NodeHandle) -> NodeHandle {
6595        self.binary_compare_op("ne", Op::Ne, other)
6596    }
6597
6598    /// Append an `Lt` node (`self < other`) producing a `Bool` mask.
6599    /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6600    /// is always `0` (IEEE-754 unordered). Non-differentiable.
6601    ///
6602    /// # Panics
6603    ///
6604    /// Panics if any operand belongs to a different [`Graph`] than the one this
6605    /// builder is building into. Operand identity is graph-scoped and checked by
6606    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6607    /// deliberate and replaces the hang a cross-graph handle used to produce.
6608    /// Build every operand from one graph, or use a `Result`-returning entry
6609    /// point where one exists.
6610    pub fn lt(&self, other: &NodeHandle) -> NodeHandle {
6611        self.binary_compare_op("lt", Op::Lt, other)
6612    }
6613
6614    /// Append an `Le` node (`self <= other`) producing a `Bool` mask.
6615    /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6616    /// is always `0`. Non-differentiable.
6617    ///
6618    /// # Panics
6619    ///
6620    /// Panics if any operand belongs to a different [`Graph`] than the one this
6621    /// builder is building into. Operand identity is graph-scoped and checked by
6622    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6623    /// deliberate and replaces the hang a cross-graph handle used to produce.
6624    /// Build every operand from one graph, or use a `Result`-returning entry
6625    /// point where one exists.
6626    pub fn le(&self, other: &NodeHandle) -> NodeHandle {
6627        self.binary_compare_op("le", Op::Le, other)
6628    }
6629
6630    /// Append a `Gt` node (`self > other`) producing a `Bool` mask.
6631    /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6632    /// is always `0`. Non-differentiable.
6633    ///
6634    /// # Panics
6635    ///
6636    /// Panics if any operand belongs to a different [`Graph`] than the one this
6637    /// builder is building into. Operand identity is graph-scoped and checked by
6638    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6639    /// deliberate and replaces the hang a cross-graph handle used to produce.
6640    /// Build every operand from one graph, or use a `Result`-returning entry
6641    /// point where one exists.
6642    pub fn gt(&self, other: &NodeHandle) -> NodeHandle {
6643        self.binary_compare_op("gt", Op::Gt, other)
6644    }
6645
6646    /// Append a `Ge` node (`self >= other`) producing a `Bool` mask.
6647    /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6648    /// is always `0`. Non-differentiable.
6649    ///
6650    /// # Panics
6651    ///
6652    /// Panics if any operand belongs to a different [`Graph`] than the one this
6653    /// builder is building into. Operand identity is graph-scoped and checked by
6654    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6655    /// deliberate and replaces the hang a cross-graph handle used to produce.
6656    /// Build every operand from one graph, or use a `Result`-returning entry
6657    /// point where one exists.
6658    pub fn ge(&self, other: &NodeHandle) -> NodeHandle {
6659        self.binary_compare_op("ge", Op::Ge, other)
6660    }
6661
6662    /// Ternary select: `result[i] = if self[i] { a[i] } else { b[i] }`.
6663    /// Receiver is the `cond` mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
6664    /// must share dtype with each other and shape with `self`. Output
6665    /// dtype matches `a`/`b`. Returning a new tensor where each slot is
6666    /// picked from `a` (cond=1) or `b` (cond=0).
6667    ///
6668    /// Named `where_cond` because `where` is a Rust reserved keyword.
6669    /// Common spelling in Candle/PyTorch families.
6670    ///
6671    /// Differentiable through `a` and `b` only; gradient through the
6672    /// cond mask is `None` (registered in
6673    /// [`crate::grad::WhereRule`]).
6674    ///
6675    /// # Panics
6676    ///
6677    /// Panics if any operand belongs to a different [`Graph`] than the one this
6678    /// builder is building into. Operand identity is graph-scoped and checked by
6679    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6680    /// deliberate and replaces the hang a cross-graph handle used to produce.
6681    /// Build every operand from one graph, or use a `Result`-returning entry
6682    /// point where one exists.
6683    pub fn where_cond(&self, a: &NodeHandle, b: &NodeHandle) -> NodeHandle {
6684        assert!(
6685            Arc::ptr_eq(&self.graph, &a.graph) && Arc::ptr_eq(&self.graph, &b.graph),
6686            "where_cond: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
6687        );
6688        assert_eq!(
6689            self.dtype(),
6690            DType::Bool,
6691            "where_cond: cond must be Bool (GAP-168(c)), got {:?} — cast a numeric \
6692             mask to Bool explicitly",
6693            self.dtype(),
6694        );
6695        assert_eq!(
6696            a.dtype(),
6697            b.dtype(),
6698            "where_cond: a/b dtype mismatch: a={:?}, b={:?}",
6699            a.dtype(),
6700            b.dtype(),
6701        );
6702        assert_eq!(
6703            self.shape().dims(),
6704            a.shape().dims(),
6705            "where_cond: cond/a shape mismatch: cond={:?}, a={:?}",
6706            self.shape().dims(),
6707            a.shape().dims(),
6708        );
6709        assert_eq!(
6710            self.shape().dims(),
6711            b.shape().dims(),
6712            "where_cond: cond/b shape mismatch: cond={:?}, b={:?}",
6713            self.shape().dims(),
6714            b.shape().dims(),
6715        );
6716        let (shape, dtype) = crate::shape::primitive_shape(
6717            &Op::Where,
6718            &[self.shape(), a.shape(), b.shape()],
6719            &[self.dtype(), a.dtype(), b.dtype()],
6720        )
6721        .expect("where_cond: shapes/dtypes validated above");
6722        let id = self.graph.write().unwrap().push(Node {
6723            op: Op::Where,
6724            inputs: vec![self.id, a.id, b.id],
6725            shape,
6726            dtype,
6727        });
6728        Self {
6729            graph: self.graph.clone(),
6730            id,
6731        }
6732    }
6733
6734    // --- dtype and broadcasting ---
6735
6736    /// Append a `Cast` node converting this tensor's element type to
6737    /// `target`. Shape is preserved. An identity cast (`target` equals the
6738    /// current dtype) is a no-op that the optimizer elides (see
6739    /// `opt::optimize`'s identity-`Cast` rule) — kept here rather than
6740    /// special-cased at construction so every identity cast, however it
6741    /// arises (decompose, autograd, user), is removed in one place.
6742    pub fn cast(&self, target: DType) -> NodeHandle {
6743        let op = Op::Cast(target);
6744        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6745            .expect("cast: single input, dtype change always infers");
6746        let id = self.graph.write().unwrap().push(Node {
6747            op,
6748            inputs: vec![self.id],
6749            shape,
6750            dtype,
6751        });
6752        Self {
6753            graph: self.graph.clone(),
6754            id,
6755        }
6756    }
6757
6758    /// Append a `BroadcastTo` node that expands `self` to the given target
6759    /// shape using NumPy broadcasting rules (right-align, pad with 1s,
6760    /// expand size-1 dims). The new tensor has the target shape and the
6761    /// same dtype as `self`.
6762    pub fn broadcast_to(&self, target: impl Into<Shape>) -> NodeHandle {
6763        let target = target.into();
6764        let src_dims = self.shape();
6765        // Validate broadcast compatibility up front so users hear about
6766        // bad target shapes at build time, not realize time.
6767        check_broadcast_compatible(src_dims.dims(), target.dims());
6768        let op = Op::BroadcastTo(target);
6769        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6770            .expect("broadcast_to: compatibility validated above");
6771        let id = self.graph.write().unwrap().push(Node {
6772            op,
6773            inputs: vec![self.id],
6774            shape,
6775            dtype,
6776        });
6777        Self {
6778            graph: self.graph.clone(),
6779            id,
6780        }
6781    }
6782
6783    /// Result-returning sibling of [`Self::broadcast_to`]. Surfaces
6784    /// shape incompatibility as a typed error rather than panicking.
6785    pub fn try_broadcast_to(
6786        &self,
6787        target: impl Into<Shape>,
6788    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6789        let target = target.into();
6790        let src_dims = self.shape();
6791        try_check_broadcast_compatible(src_dims.dims(), target.dims())?;
6792        let op = Op::BroadcastTo(target);
6793        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6794        let id = self.graph.write().unwrap().push(Node {
6795            op,
6796            inputs: vec![self.id],
6797            shape,
6798            dtype,
6799        });
6800        Ok(Self {
6801            graph: self.graph.clone(),
6802            id,
6803        })
6804    }
6805
6806    /// Append an `Unsqueeze` node that inserts a size-1 dimension at
6807    /// position `dim`. `dim` must be in `0..=rank` (where `dim == rank`
6808    /// appends to the end). Pure metadata — the output shares bytes
6809    /// with `self`, with a new size-1 axis layered into the Layout
6810    /// side-table. Strictly more efficient than `reshape` for the
6811    /// size-1-insertion case because non-contiguous (e.g. transposed
6812    /// or broadcast) inputs flow through without auto-Contiguize.
6813    pub fn unsqueeze(&self, dim: usize) -> NodeHandle {
6814        let in_shape = self.shape();
6815        let rank = in_shape.dims().len();
6816        assert!(
6817            dim <= rank,
6818            "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6819        );
6820        let op = Op::Unsqueeze { dim };
6821        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6822            .expect("unsqueeze: dim validated above");
6823        let id = self.graph.write().unwrap().push(Node {
6824            op,
6825            inputs: vec![self.id],
6826            shape,
6827            dtype,
6828        });
6829        Self {
6830            graph: self.graph.clone(),
6831            id,
6832        }
6833    }
6834
6835    /// Result-returning sibling of [`Self::unsqueeze`]. Surfaces
6836    /// `dim > rank` as a typed error rather than panicking.
6837    pub fn try_unsqueeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6838        let in_shape = self.shape();
6839        let rank = in_shape.dims().len();
6840        if dim > rank {
6841            return Err(fuel_ir::Error::Msg(format!(
6842                "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6843            ))
6844            .bt());
6845        }
6846        let op = Op::Unsqueeze { dim };
6847        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6848        let id = self.graph.write().unwrap().push(Node {
6849            op,
6850            inputs: vec![self.id],
6851            shape,
6852            dtype,
6853        });
6854        Ok(Self {
6855            graph: self.graph.clone(),
6856            id,
6857        })
6858    }
6859
6860    /// Append a `Squeeze` node that drops the size-1 dimension at
6861    /// position `dim` (range `0..rank`). Inverse of [`Self::unsqueeze`].
6862    /// Metadata-only view: the output shares bytes with `self`, with
6863    /// the named dim pruned from the Layout side-table.
6864    ///
6865    /// **Returns `Result`** rather than panicking — production paths
6866    /// can recover from a bad `dim` instead of crashing. Bad `dim`
6867    /// (out of bounds OR `shape[dim] != 1`) surfaces as a typed error.
6868    pub fn squeeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6869        let in_shape = self.shape();
6870        let rank = in_shape.dims().len();
6871        if dim >= rank {
6872            return Err(fuel_ir::Error::Msg(format!(
6873                "squeeze: dim {dim} out of bounds for rank {rank} (must be < rank)",
6874            ))
6875            .bt());
6876        }
6877        if in_shape.dims()[dim] != 1 {
6878            return Err(fuel_ir::Error::Msg(format!(
6879                "squeeze: dim {dim} has size {}, expected 1",
6880                in_shape.dims()[dim],
6881            ))
6882            .bt());
6883        }
6884        let op = Op::Squeeze { dim };
6885        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6886        let id = self.graph.write().unwrap().push(Node {
6887            op,
6888            inputs: vec![self.id],
6889            shape,
6890            dtype,
6891        });
6892        Ok(Self {
6893            graph: self.graph.clone(),
6894            id,
6895        })
6896    }
6897
6898    /// Append an `Op::Contiguize` node that materializes a
6899    /// contiguous copy of `self`. Output shape and dtype match the
6900    /// input; only the layout changes to contiguous + zero-offset.
6901    /// Zero-copy when the input is already contiguous + zero-offset
6902    /// (the executor adopts the input Storage Arc unchanged).
6903    ///
6904    /// First-class IR node so the optimizer (Phase 2.2) can insert
6905    /// layout-fixups before kernels that don't advertise
6906    /// `crate::KernelCaps::strided_input` without overloading
6907    /// [`Self::reshape`]'s "change shape" semantics.
6908    pub fn contiguize(&self) -> NodeHandle {
6909        let shape = self.shape().clone();
6910        let dtype = self.dtype();
6911        let id = self.graph.write().unwrap().push(Node {
6912            op: Op::Contiguize,
6913            inputs: vec![self.id],
6914            shape,
6915            dtype,
6916        });
6917        Self {
6918            graph: self.graph.clone(),
6919            id,
6920        }
6921    }
6922
6923    /// Append a `Reshape` node producing `self`'s data under a new shape.
6924    /// The new shape must have the same total element count as the
6925    /// current shape.
6926    pub fn reshape(&self, target: impl Into<Shape>) -> NodeHandle {
6927        let target = target.into();
6928        assert_eq!(
6929            self.shape().elem_count(),
6930            target.elem_count(),
6931            "reshape: element count mismatch: from {} to {}",
6932            self.shape().elem_count(),
6933            target.elem_count(),
6934        );
6935        let op = Op::Reshape(target);
6936        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6937            .expect("reshape: element count validated above");
6938        let id = self.graph.write().unwrap().push(Node {
6939            op,
6940            inputs: vec![self.id],
6941            shape,
6942            dtype,
6943        });
6944        Self {
6945            graph: self.graph.clone(),
6946            id,
6947        }
6948    }
6949
6950    /// Result-returning sibling of [`Self::reshape`]. Surfaces
6951    /// element-count mismatch as a typed error rather than panicking.
6952    pub fn try_reshape(
6953        &self,
6954        target: impl Into<Shape>,
6955    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6956        let target = target.into();
6957        let from = self.shape().elem_count();
6958        let to = target.elem_count();
6959        if from != to {
6960            return Err(fuel_ir::Error::Msg(format!(
6961                "reshape: element count mismatch: from {from} to {to}",
6962            ))
6963            .bt());
6964        }
6965        let op = Op::Reshape(target);
6966        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6967        let id = self.graph.write().unwrap().push(Node {
6968            op,
6969            inputs: vec![self.id],
6970            shape,
6971            dtype,
6972        });
6973        Ok(Self {
6974            graph: self.graph.clone(),
6975            id,
6976        })
6977    }
6978
6979    /// Append a `ReduceSumTo` node that sum-reduces `self` to a smaller
6980    /// shape. The target must be reachable from `self.shape()` via
6981    /// reduction of dims (i.e. `self.shape()` could be produced from
6982    /// `target` by broadcasting).
6983    pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> NodeHandle {
6984        let target = target.into();
6985        // Symmetric check: self must be broadcast-compatible FROM the
6986        // smaller target. That is, the target must be broadcast-ready to
6987        // self.shape().
6988        check_broadcast_compatible(target.dims(), self.shape().dims());
6989        let op = Op::ReduceSumTo(target);
6990        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6991            .expect("reduce_sum_to: compatibility validated above");
6992        let id = self.graph.write().unwrap().push(Node {
6993            op,
6994            inputs: vec![self.id],
6995            shape,
6996            dtype,
6997        });
6998        Self {
6999            graph: self.graph.clone(),
7000            id,
7001        }
7002    }
7003
7004    /// Append a `ReduceMaxTo` node that max-reduces `self` to a smaller
7005    /// shape — the max-symmetric counterpart of [`Self::reduce_sum_to`].
7006    /// The target must be reachable from `self.shape()` via reduction
7007    /// of dims (i.e. `self.shape()` could be produced from `target` by
7008    /// broadcasting).
7009    pub fn reduce_max_to(&self, target: impl Into<Shape>) -> NodeHandle {
7010        let target = target.into();
7011        check_broadcast_compatible(target.dims(), self.shape().dims());
7012        let op = Op::ReduceMaxTo(target);
7013        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
7014            .expect("reduce_max_to: compatibility validated above");
7015        let id = self.graph.write().unwrap().push(Node {
7016            op,
7017            inputs: vec![self.id],
7018            shape,
7019            dtype,
7020        });
7021        Self {
7022            graph: self.graph.clone(),
7023            id,
7024        }
7025    }
7026
7027    // --- reductions to a scalar ---
7028
7029    /// Append a `SumAll` node reducing every element to a scalar (rank-0).
7030    pub fn sum_all(&self) -> NodeHandle {
7031        self.scalar_reduction(Op::SumAll)
7032    }
7033
7034    /// Append a `MaxAll` node producing the max element as a scalar.
7035    pub fn max_all(&self) -> NodeHandle {
7036        self.scalar_reduction(Op::MaxAll)
7037    }
7038
7039    /// Append a `MinAll` node producing the min element as a scalar.
7040    pub fn min_all(&self) -> NodeHandle {
7041        self.scalar_reduction(Op::MinAll)
7042    }
7043
7044    /// Append a `MeanAll` node producing the arithmetic mean as a scalar.
7045    pub fn mean_all(&self) -> NodeHandle {
7046        self.scalar_reduction(Op::MeanAll)
7047    }
7048
7049    // --- reductions along one dimension ---
7050
7051    /// Append a `SumDim(dim)` node. Reduces along `dim`; output rank is
7052    /// `input rank - 1` (the reduced dim is removed).
7053    pub fn sum_dim(&self, dim: usize) -> NodeHandle {
7054        self.axis_reduction("sum_dim", Op::SumDim(dim), dim)
7055    }
7056
7057    /// Append a `MaxDim(dim)` node.
7058    pub fn max_dim(&self, dim: usize) -> NodeHandle {
7059        self.axis_reduction("max_dim", Op::MaxDim(dim), dim)
7060    }
7061
7062    /// Append a `MinDim(dim)` node.
7063    pub fn min_dim(&self, dim: usize) -> NodeHandle {
7064        self.axis_reduction("min_dim", Op::MinDim(dim), dim)
7065    }
7066
7067    /// Append a `MeanDim(dim)` node.
7068    pub fn mean_dim(&self, dim: usize) -> NodeHandle {
7069        self.axis_reduction("mean_dim", Op::MeanDim(dim), dim)
7070    }
7071
7072    /// Append an `ArgMaxDim(dim)` node. Produces a U32 tensor with the
7073    /// reduced dim removed, whose values are the index of the maximum
7074    /// along that dim. Non-differentiable — trying to run `backward()`
7075    /// through an ArgMax node will panic.
7076    pub fn argmax_dim(&self, dim: usize) -> NodeHandle {
7077        self.index_reduction("argmax_dim", Op::ArgMaxDim(dim), dim)
7078    }
7079
7080    /// Append an `ArgMinDim(dim)` node. Same semantics as `argmax_dim`
7081    /// but for the minimum.
7082    pub fn argmin_dim(&self, dim: usize) -> NodeHandle {
7083        self.index_reduction("argmin_dim", Op::ArgMinDim(dim), dim)
7084    }
7085
7086    /// Internal helper for index-producing reductions. Validates the
7087    /// dim, builds the reduced shape, and stamps the output with
7088    /// `DType::U32` regardless of the input dtype.
7089    fn index_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
7090        let in_shape = self.shape();
7091        assert!(
7092            dim < in_shape.dims().len(),
7093            "{name}: dim {dim} out of bounds for shape {:?}",
7094            in_shape.dims(),
7095        );
7096        // primitive_shape carries both the rank-reduced shape and the U32
7097        // index dtype for ArgMaxDim/ArgMinDim (the single source of truth).
7098        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
7099            .expect("index_reduction: dim validated above");
7100        let id = self.graph.write().unwrap().push(Node {
7101            op,
7102            inputs: vec![self.id],
7103            shape,
7104            dtype,
7105        });
7106        Self {
7107            graph: self.graph.clone(),
7108            id,
7109        }
7110    }
7111
7112    // --- compositions ---
7113
7114    /// Append a `SoftmaxLastDim` node. Shape is preserved.
7115    ///
7116    /// Phase 7.6 step 3: emits `Op::Fused(FusedOps::SOFTMAX_LAST_DIM,
7117    /// FusedOpParams::SoftmaxLastDim)` — the registry-extended arm.
7118    /// The legacy `Op::SoftmaxLastDim` variant remains in the enum
7119    /// during the migration; step 5 drops it once nothing emits it.
7120    pub fn softmax_last_dim(&self) -> NodeHandle {
7121        assert!(
7122            !self.shape().dims().is_empty(),
7123            "softmax_last_dim: input must be rank >= 1",
7124        );
7125        self.unary_op(Op::Fused(
7126            crate::registry::FusedOps::SOFTMAX_LAST_DIM,
7127            crate::registry::FusedOpParams::SoftmaxLastDim,
7128        ))
7129    }
7130
7131    /// Append a `CausalConv1d` node — depthwise 1-D causal convolution
7132    /// + bias + optional fused SiLU. Three inputs:
7133    /// - `self` (x): `[batch, channels, seq + kernel - 1]` F32
7134    ///   (caller pre-pads with `kernel - 1` zeros on the left for the
7135    ///   causal mask — matches Mamba-2's prefill convention).
7136    /// - `weight`: `[channels, 1, kernel]` F32 (depthwise — one filter
7137    ///   per channel; `groups == channels`).
7138    /// - `bias`: `[channels]` F32 (required — matches baracuda's
7139    ///   `causal_conv1d_*_run` signature; pass zeros if you don't want
7140    ///   a bias).
7141    ///
7142    /// Output: `[batch, channels, seq]` F32 where `seq = x.dims[2] -
7143    /// (kernel - 1)`.
7144    ///
7145    /// Emits `Op::Fused(FusedOps::CAUSAL_CONV1D,
7146    /// FusedOpParams::CausalConv1d { use_silu })`. See
7147    /// `fuel-graph/src/registry/causal_conv1d.rs` for the registry
7148    /// entry. No primitive decomposition exists (fuel-graph has no
7149    /// `Op::Conv1D`); backends without a native kernel fall through
7150    /// to the executor's cpu_fallback path.
7151    ///
7152    /// # Panics
7153    ///
7154    /// Panics if any operand belongs to a different [`Graph`] than the one this
7155    /// builder is building into. Operand identity is graph-scoped and checked by
7156    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7157    /// deliberate and replaces the hang a cross-graph handle used to produce.
7158    /// Build every operand from one graph, or use a `Result`-returning entry
7159    /// point where one exists.
7160    pub fn causal_conv1d(
7161        &self,
7162        weight: &NodeHandle,
7163        bias: &NodeHandle,
7164        use_silu: bool,
7165    ) -> NodeHandle {
7166        assert!(
7167            Arc::ptr_eq(&self.graph, &weight.graph) && Arc::ptr_eq(&self.graph, &bias.graph),
7168            "causal_conv1d: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7169        );
7170        let dtype = self.dtype();
7171        assert!(
7172            matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7173            "causal_conv1d: x must be F32/F64/BF16/F16, got {dtype:?}",
7174        );
7175        assert_eq!(
7176            weight.dtype(),
7177            dtype,
7178            "causal_conv1d: weight dtype {:?} must match x dtype {dtype:?}",
7179            weight.dtype(),
7180        );
7181        assert_eq!(
7182            bias.dtype(),
7183            dtype,
7184            "causal_conv1d: bias dtype {:?} must match x dtype {dtype:?}",
7185            bias.dtype(),
7186        );
7187        let x_dims = self.shape();
7188        let x_dims = x_dims.dims();
7189        let w_dims = weight.shape();
7190        let w_dims = w_dims.dims();
7191        let b_dims = bias.shape();
7192        let b_dims = b_dims.dims();
7193        assert_eq!(
7194            x_dims.len(),
7195            3,
7196            "causal_conv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
7197        );
7198        assert_eq!(
7199            w_dims.len(),
7200            3,
7201            "causal_conv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
7202        );
7203        assert_eq!(
7204            b_dims.len(),
7205            1,
7206            "causal_conv1d: bias must be rank 1 [channels], got {b_dims:?}",
7207        );
7208        let batch = x_dims[0];
7209        let channels = x_dims[1];
7210        let x_seq = x_dims[2];
7211        let kernel = w_dims[2];
7212        assert_eq!(
7213            w_dims[0], channels,
7214            "causal_conv1d: weight's first dim {} must equal channels {channels}",
7215            w_dims[0],
7216        );
7217        assert_eq!(
7218            w_dims[1], 1,
7219            "causal_conv1d: weight's middle dim must be 1 (depthwise), got {}",
7220            w_dims[1],
7221        );
7222        assert_eq!(
7223            b_dims[0], channels,
7224            "causal_conv1d: bias length {} must equal channels {channels}",
7225            b_dims[0],
7226        );
7227        assert!(
7228            x_seq >= kernel - 1,
7229            "causal_conv1d: x time dim {x_seq} must be ≥ kernel - 1 = {} \
7230             (caller must pre-pad with {} zeros)",
7231            kernel - 1,
7232            kernel - 1,
7233        );
7234        let out_seq = x_seq - (kernel - 1);
7235        let id = self.graph.write().unwrap().push(Node {
7236            op: Op::Fused(
7237                crate::registry::FusedOps::CAUSAL_CONV1D,
7238                crate::registry::FusedOpParams::CausalConv1d { use_silu },
7239            ),
7240            inputs: vec![self.id, weight.id, bias.id],
7241            shape: Shape::from_dims(&[batch, channels, out_seq]),
7242            dtype,
7243        });
7244        Self {
7245            graph: self.graph.clone(),
7246            id,
7247        }
7248    }
7249
7250    /// Append an `Nf4Matmul` node — bitsandbytes-style 4-bit
7251    /// NormalFloat quantized matrix multiply. Three inputs:
7252    /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7253    /// - `w_packed`: `[N, K/2]` U8 (two 4-bit codes per byte)
7254    /// - `absmax`:   `[N, K/block_size]` F32 (per-output-row, per-block)
7255    ///
7256    /// Output: `[..., M, N]` matching activations' dtype.
7257    ///
7258    /// `block_size` is the NF4 quantization block size (typically 64
7259    /// in bitsandbytes). `K` must be even AND a multiple of
7260    /// `block_size`.
7261    ///
7262    /// Emits `Op::Fused(FusedOps::NF4_MATMUL, FusedOpParams::Nf4Matmul
7263    /// { block_size })`. No primitive decomposition (the dequant +
7264    /// matmul roundtrip is exactly what NF4's fused dequant-in-kernel
7265    /// design avoids); backends without a native kernel fall through
7266    /// to the executor's cpu_fallback path.
7267    ///
7268    /// # Panics
7269    ///
7270    /// Panics if any operand belongs to a different [`Graph`] than the one this
7271    /// builder is building into. Operand identity is graph-scoped and checked by
7272    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7273    /// deliberate and replaces the hang a cross-graph handle used to produce.
7274    /// Build every operand from one graph, or use a `Result`-returning entry
7275    /// point where one exists.
7276    pub fn nf4_matmul(
7277        &self,
7278        w_packed: &NodeHandle,
7279        absmax: &NodeHandle,
7280        block_size: usize,
7281    ) -> NodeHandle {
7282        assert!(
7283            Arc::ptr_eq(&self.graph, &w_packed.graph) && Arc::ptr_eq(&self.graph, &absmax.graph),
7284            "nf4_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7285        );
7286        let act_dtype = self.dtype();
7287        assert!(
7288            matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7289            "nf4_matmul v1: activations must be F32/F16/BF16, got {:?}",
7290            act_dtype,
7291        );
7292        assert_eq!(
7293            w_packed.dtype(),
7294            DType::U8,
7295            "nf4_matmul: w_packed must be U8 (two 4-bit codes per byte), got {:?}",
7296            w_packed.dtype(),
7297        );
7298        assert_eq!(
7299            absmax.dtype(),
7300            DType::F32,
7301            "nf4_matmul: absmax must be F32, got {:?}",
7302            absmax.dtype(),
7303        );
7304        let a_dims = self.shape();
7305        let a_dims = a_dims.dims();
7306        let w_dims = w_packed.shape();
7307        let w_dims = w_dims.dims();
7308        let abs_dims = absmax.shape();
7309        let abs_dims = abs_dims.dims();
7310        assert!(
7311            a_dims.len() >= 2,
7312            "nf4_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7313        );
7314        assert_eq!(
7315            w_dims.len(),
7316            2,
7317            "nf4_matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
7318        );
7319        assert_eq!(
7320            abs_dims.len(),
7321            2,
7322            "nf4_matmul: absmax must be rank 2 [n, k/block_size], got {abs_dims:?}",
7323        );
7324        let _m = a_dims[a_dims.len() - 2];
7325        let k = a_dims[a_dims.len() - 1];
7326        let n = w_dims[0];
7327        assert!(
7328            k.is_multiple_of(2),
7329            "nf4_matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
7330        );
7331        assert!(
7332            block_size > 0 && k.is_multiple_of(block_size),
7333            "nf4_matmul: k={k} must be a positive multiple of block_size={block_size}",
7334        );
7335        assert_eq!(
7336            w_dims[1],
7337            k / 2,
7338            "nf4_matmul: w_packed second dim {} must equal k/2 = {}",
7339            w_dims[1],
7340            k / 2,
7341        );
7342        assert_eq!(
7343            abs_dims,
7344            &[n, k / block_size][..],
7345            "nf4_matmul: absmax {abs_dims:?} must be [n={n}, k/block_size={}]",
7346            k / block_size,
7347        );
7348        let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7349        out_dims.push(n);
7350        let id = self.graph.write().unwrap().push(Node {
7351            op: Op::Fused(
7352                crate::registry::FusedOps::NF4_MATMUL,
7353                crate::registry::FusedOpParams::Nf4Matmul { block_size },
7354            ),
7355            inputs: vec![self.id, w_packed.id, absmax.id],
7356            shape: Shape::from_dims(&out_dims),
7357            dtype: act_dtype,
7358        });
7359        Self {
7360            graph: self.graph.clone(),
7361            id,
7362        }
7363    }
7364
7365    /// Append an `AwqMatmul` node — AWQ (mit-han-lab) asymmetric int4
7366    /// weight-only matrix multiply. Four inputs, the quantized three in the
7367    /// baracuda W4A16 kernel layout (OC-major; see
7368    /// [`crate::registry::awq_matmul`]):
7369    /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7370    /// - `weight`: `[N, K/8]` U32 (eight int4 codes per word, sequential
7371    ///   nibble order)
7372    /// - `zeros`:  `[N, zeros_w]` U32 (group `g`'s zero-point is nibble
7373    ///   `g % 8` of word `g / 8`), `zeros_w =`
7374    ///   [`crate::registry::awq_matmul::awq_zeros_w`]`(K, group_size)`
7375    /// - `scales`: `[N, 8 * zeros_w]` F16 (entry `g` is group `g`'s scale)
7376    ///
7377    /// Output: `[..., M, N]` matching activations' dtype.
7378    ///
7379    /// `group_size` must be 64 or 128 and evenly divide `K`; `K` must be a
7380    /// multiple of 8. `split_k_iters` is a CUDA launch-tuning parameter the
7381    /// decompose path ignores.
7382    /// `fuel_quantized::awq_repack::repack_hf_awq_for_kernel` produces the
7383    /// three quantized operands from a HuggingFace `*-AWQ` checkpoint.
7384    ///
7385    /// Emits `Op::Fused(FusedOps::AWQ_MATMUL, FusedOpParams::AwqMatmul
7386    /// { group_size, split_k_iters })`.
7387    ///
7388    /// # Panics
7389    ///
7390    /// Panics if any operand belongs to a different [`Graph`] than the one
7391    /// this builder is building into, or if any shape/dtype precondition
7392    /// above doesn't hold — same discipline as [`Self::nf4_matmul`].
7393    pub fn awq_matmul(
7394        &self,
7395        weight: &NodeHandle,
7396        zeros: &NodeHandle,
7397        scales: &NodeHandle,
7398        group_size: usize,
7399        split_k_iters: i32,
7400    ) -> NodeHandle {
7401        assert!(
7402            Arc::ptr_eq(&self.graph, &weight.graph)
7403                && Arc::ptr_eq(&self.graph, &zeros.graph)
7404                && Arc::ptr_eq(&self.graph, &scales.graph),
7405            "awq_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7406        );
7407        let act_dtype = self.dtype();
7408        assert!(
7409            matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7410            "awq_matmul v1: activations must be F32/F16/BF16, got {:?}",
7411            act_dtype,
7412        );
7413        assert_eq!(
7414            weight.dtype(),
7415            DType::U32,
7416            "awq_matmul: weight must be U32 (eight 4-bit codes per word), got {:?}",
7417            weight.dtype(),
7418        );
7419        assert_eq!(
7420            zeros.dtype(),
7421            DType::U32,
7422            "awq_matmul: zeros must be U32 (eight 4-bit codes per word), got {:?}",
7423            zeros.dtype(),
7424        );
7425        assert_eq!(
7426            scales.dtype(),
7427            DType::F16,
7428            "awq_matmul: scales must be F16, got {:?}",
7429            scales.dtype(),
7430        );
7431        let a_dims = self.shape();
7432        let a_dims = a_dims.dims();
7433        let w_dims = weight.shape();
7434        let w_dims = w_dims.dims();
7435        let z_dims = zeros.shape();
7436        let z_dims = z_dims.dims();
7437        let s_dims = scales.shape();
7438        let s_dims = s_dims.dims();
7439        assert!(
7440            a_dims.len() >= 2,
7441            "awq_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7442        );
7443        assert_eq!(
7444            w_dims.len(),
7445            2,
7446            "awq_matmul: weight must be rank 2 [N, K/8], got {w_dims:?}",
7447        );
7448        assert_eq!(
7449            z_dims.len(),
7450            2,
7451            "awq_matmul: zeros must be rank 2 [N, zeros_w], got {z_dims:?}",
7452        );
7453        assert_eq!(
7454            s_dims.len(),
7455            2,
7456            "awq_matmul: scales must be rank 2 [N, 8 * zeros_w], got {s_dims:?}",
7457        );
7458        let k = a_dims[a_dims.len() - 1];
7459        let n = w_dims[0];
7460        assert!(
7461            k.is_multiple_of(8),
7462            "awq_matmul: k={k} must be a multiple of 8 (weight packs 8 codes per word along k)",
7463        );
7464        let Some(zeros_w) = crate::registry::awq_matmul::awq_zeros_w(k, group_size) else {
7465            panic!("awq_matmul: group_size={group_size} must be 64 or 128 and divide k={k}");
7466        };
7467        assert_eq!(
7468            w_dims[1],
7469            k / 8,
7470            "awq_matmul: weight second dim {} must equal k/8 = {}",
7471            w_dims[1],
7472            k / 8,
7473        );
7474        assert_eq!(
7475            z_dims,
7476            &[n, zeros_w][..],
7477            "awq_matmul: zeros {z_dims:?} must be [n={n}, zeros_w={zeros_w}]",
7478        );
7479        assert_eq!(
7480            s_dims,
7481            &[n, 8 * zeros_w][..],
7482            "awq_matmul: scales {s_dims:?} must be [n={n}, 8 * zeros_w={}]",
7483            8 * zeros_w,
7484        );
7485        let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7486        out_dims.push(n);
7487        let id = self.graph.write().unwrap().push(Node {
7488            op: Op::Fused(
7489                crate::registry::FusedOps::AWQ_MATMUL,
7490                crate::registry::FusedOpParams::AwqMatmul {
7491                    group_size,
7492                    split_k_iters,
7493                },
7494            ),
7495            inputs: vec![self.id, weight.id, zeros.id, scales.id],
7496            shape: Shape::from_dims(&out_dims),
7497            dtype: act_dtype,
7498        });
7499        Self {
7500            graph: self.graph.clone(),
7501            id,
7502        }
7503    }
7504
7505    /// Append an `SsdChunkScan` node — Mamba-2's State-Space
7506    /// Duality chunked scan (forward). Five inputs:
7507    /// - `self` (x): `[batch, seqlen, heads, head_dim]` F32
7508    /// - `dt`:       `[batch, seqlen, heads]` F32
7509    /// - `a`:        `[heads]` F32 (per-head scalar log A)
7510    /// - `b`:        `[batch, seqlen, heads, state_dim]` F32
7511    /// - `c`:        `[batch, seqlen, heads, state_dim]` F32
7512    ///
7513    /// Output: `y: [batch, seqlen, heads, head_dim]` F32 (same as x).
7514    ///
7515    /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
7516    /// It controls GPU parallelism granularity but the mathematical
7517    /// result is identical to a sequential scan; the CPU kernel runs
7518    /// sequential regardless. Validation: `chunk_size > 0` and
7519    /// `seqlen % chunk_size == 0`.
7520    ///
7521    /// Emits `Op::Fused(FusedOps::SSD_CHUNK_SCAN,
7522    /// FusedOpParams::SsdChunkScan { chunk_size })`. No primitive
7523    /// decomposition; backends without a native kernel fall through
7524    /// to the executor's cpu_fallback path.
7525    /// Internal: build the bundled SsdChunkScan producer node and
7526    /// return its NodeId. Callers project per-slot via
7527    /// [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7528    fn ssd_chunk_scan_producer(
7529        &self,
7530        dt: &NodeHandle,
7531        a: &NodeHandle,
7532        b: &NodeHandle,
7533        c: &NodeHandle,
7534        chunk_size: usize,
7535    ) -> NodeHandle {
7536        assert!(
7537            Arc::ptr_eq(&self.graph, &dt.graph)
7538                && Arc::ptr_eq(&self.graph, &a.graph)
7539                && Arc::ptr_eq(&self.graph, &b.graph)
7540                && Arc::ptr_eq(&self.graph, &c.graph),
7541            "ssd_chunk_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7542        );
7543        let dtype = self.dtype();
7544        assert!(
7545            matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7546            "ssd_chunk_scan: x must be F32/F64/BF16/F16, got {dtype:?}",
7547        );
7548        for (name, t) in [("dt", dt), ("a", a), ("b", b), ("c", c)] {
7549            assert_eq!(
7550                t.dtype(),
7551                dtype,
7552                "ssd_chunk_scan: {name} dtype {:?} must match x dtype {dtype:?}",
7553                t.dtype(),
7554            );
7555        }
7556        let x_dims = self.shape();
7557        let x_dims = x_dims.dims();
7558        let dt_dims = dt.shape();
7559        let dt_dims = dt_dims.dims();
7560        let a_dims = a.shape();
7561        let a_dims = a_dims.dims();
7562        let b_dims = b.shape();
7563        let b_dims = b_dims.dims();
7564        let c_dims = c.shape();
7565        let c_dims = c_dims.dims();
7566        assert_eq!(
7567            x_dims.len(),
7568            4,
7569            "ssd_chunk_scan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
7570        );
7571        let batch = x_dims[0];
7572        let seqlen = x_dims[1];
7573        let heads = x_dims[2];
7574        let head_dim = x_dims[3];
7575        assert_eq!(
7576            dt_dims,
7577            &[batch, seqlen, heads][..],
7578            "ssd_chunk_scan: dt {dt_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}]",
7579        );
7580        assert_eq!(
7581            a_dims,
7582            &[heads][..],
7583            "ssd_chunk_scan: a {a_dims:?} must be [heads={heads}]",
7584        );
7585        assert_eq!(
7586            b_dims.len(),
7587            4,
7588            "ssd_chunk_scan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
7589        );
7590        let state_dim = b_dims[3];
7591        assert_eq!(
7592            b_dims,
7593            &[batch, seqlen, heads, state_dim][..],
7594            "ssd_chunk_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}, state_dim={state_dim}]",
7595        );
7596        assert_eq!(
7597            c_dims,
7598            &[batch, seqlen, heads, state_dim][..],
7599            "ssd_chunk_scan: c {c_dims:?} must match b shape",
7600        );
7601        let params = crate::registry::FusedOpParams::SsdChunkScan { chunk_size };
7602        let input_shapes = [
7603            Shape::from_dims(x_dims),
7604            Shape::from_dims(dt_dims),
7605            Shape::from_dims(a_dims),
7606            Shape::from_dims(b_dims),
7607            Shape::from_dims(c_dims),
7608        ];
7609        let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7610        let entry = crate::registry::default_registry()
7611            .entry(crate::registry::FusedOps::SSD_CHUNK_SCAN)
7612            .expect("SSD_CHUNK_SCAN registered");
7613        let specs =
7614            (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, &params);
7615        let (_total_bytes, views) =
7616            fuel_ir::storage::compose_bundle(&specs).expect("SsdChunkScan compose_bundle");
7617        let mut g = self.graph.write().unwrap();
7618        let id = g.push(Node {
7619            op: Op::Fused(crate::registry::FusedOps::SSD_CHUNK_SCAN, params),
7620            inputs: vec![self.id, dt.id, a.id, b.id, c.id],
7621            shape: Shape::from_dims(&[batch, seqlen, heads, head_dim]),
7622            dtype,
7623        });
7624        g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7625            .expect("SsdChunkScan set_output_views");
7626        drop(g);
7627        Self {
7628            graph: self.graph.clone(),
7629            id,
7630        }
7631    }
7632
7633    /// Single-output SsdChunkScan: returns the `y` slot of the
7634    /// bundled producer (View(0)). See
7635    /// [`Self::ssd_chunk_scan_bundled`] for the multi-output variant.
7636    ///
7637    /// # Panics
7638    ///
7639    /// Panics if any operand belongs to a different [`Graph`] than the one this
7640    /// builder is building into. Operand identity is graph-scoped and checked by
7641    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7642    /// deliberate and replaces the hang a cross-graph handle used to produce.
7643    /// Build every operand from one graph, or use a `Result`-returning entry
7644    /// point where one exists.
7645    pub fn ssd_chunk_scan(
7646        &self,
7647        dt: &NodeHandle,
7648        a: &NodeHandle,
7649        b: &NodeHandle,
7650        c: &NodeHandle,
7651        chunk_size: usize,
7652    ) -> NodeHandle {
7653        self.assert_same_graph(dt, "ssd_chunk_scan", "dt");
7654        self.assert_same_graph(a, "ssd_chunk_scan", "a");
7655        self.assert_same_graph(b, "ssd_chunk_scan", "b");
7656        self.assert_same_graph(c, "ssd_chunk_scan", "c");
7657        let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7658        producer
7659            .view(0)
7660            .expect("SsdChunkScan view(0) must succeed (just registered slots)")
7661    }
7662
7663    /// Append a `SelectiveScan` node — Mamba-1's selective
7664    /// state-space scan (forward). Five inputs:
7665    /// - `self` (u): `[batch, seqlen, dim]` F32
7666    /// - `delta`:    `[batch, seqlen, dim]` F32
7667    /// - `a`:        `[dim, dstate]` F32
7668    /// - `b`:        `[batch, seqlen, dstate]` F32
7669    /// - `c`:        `[batch, seqlen, dstate]` F32
7670    ///
7671    /// Output: `y: [batch, seqlen, dim]` F32.
7672    ///
7673    /// `delta_softplus` toggles the softplus(delta) activation before
7674    /// use (matches baracuda's `selective_scan_*_run` flag). The v1
7675    /// op surface skips the optional `d_skip`, `z`, `delta_bias`
7676    /// inputs and the `last_state` second output — see
7677    /// `fuel-graph/src/registry/selective_scan.rs` for the rationale.
7678    ///
7679    /// Emits `Op::Fused(FusedOps::SELECTIVE_SCAN,
7680    /// FusedOpParams::SelectiveScan { delta_softplus })`. No
7681    /// primitive decomposition exists (the scan is a sequential
7682    /// recurrence); backends without a native kernel fall through to
7683    /// the executor's cpu_fallback path.
7684    /// Internal: build the bundled SelectiveScan producer node and
7685    /// return its NodeId (wrapped in a `NodeHandle`). Callers project
7686    /// per-slot via [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7687    fn selective_scan_producer(
7688        &self,
7689        delta: &NodeHandle,
7690        a: &NodeHandle,
7691        b: &NodeHandle,
7692        c: &NodeHandle,
7693        delta_softplus: bool,
7694    ) -> NodeHandle {
7695        assert!(
7696            Arc::ptr_eq(&self.graph, &delta.graph)
7697                && Arc::ptr_eq(&self.graph, &a.graph)
7698                && Arc::ptr_eq(&self.graph, &b.graph)
7699                && Arc::ptr_eq(&self.graph, &c.graph),
7700            "selective_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7701        );
7702        let dtype = self.dtype();
7703        assert!(
7704            matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7705            "selective_scan: u must be F32/F64/BF16/F16, got {dtype:?}",
7706        );
7707        for (name, t) in [("delta", delta), ("a", a), ("b", b), ("c", c)] {
7708            assert_eq!(
7709                t.dtype(),
7710                dtype,
7711                "selective_scan: {name} dtype {:?} must match u dtype {dtype:?}",
7712                t.dtype(),
7713            );
7714        }
7715        let u_dims = self.shape();
7716        let u_dims = u_dims.dims();
7717        let delta_dims = delta.shape();
7718        let delta_dims = delta_dims.dims();
7719        let a_dims = a.shape();
7720        let a_dims = a_dims.dims();
7721        let b_dims = b.shape();
7722        let b_dims = b_dims.dims();
7723        let c_dims = c.shape();
7724        let c_dims = c_dims.dims();
7725        assert_eq!(
7726            u_dims.len(),
7727            3,
7728            "selective_scan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
7729        );
7730        assert_eq!(
7731            delta_dims, u_dims,
7732            "selective_scan: delta {delta_dims:?} must match u {u_dims:?}",
7733        );
7734        assert_eq!(
7735            a_dims.len(),
7736            2,
7737            "selective_scan: a must be rank 2 [dim, dstate], got {a_dims:?}",
7738        );
7739        let batch = u_dims[0];
7740        let seqlen = u_dims[1];
7741        let dim = u_dims[2];
7742        let dstate = a_dims[1];
7743        assert_eq!(
7744            a_dims[0], dim,
7745            "selective_scan: a's first dim {} must equal dim {dim}",
7746            a_dims[0],
7747        );
7748        assert_eq!(
7749            b_dims,
7750            &[batch, seqlen, dstate][..],
7751            "selective_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7752        );
7753        assert_eq!(
7754            c_dims,
7755            &[batch, seqlen, dstate][..],
7756            "selective_scan: c {c_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7757        );
7758        let params = crate::registry::FusedOpParams::SelectiveScan { delta_softplus };
7759        let input_shapes = [
7760            Shape::from_dims(u_dims),
7761            Shape::from_dims(delta_dims),
7762            Shape::from_dims(a_dims),
7763            Shape::from_dims(b_dims),
7764            Shape::from_dims(c_dims),
7765        ];
7766        let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7767        let entry = crate::registry::default_registry()
7768            .entry(crate::registry::FusedOps::SELECTIVE_SCAN)
7769            .expect("SELECTIVE_SCAN registered");
7770        let specs =
7771            (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, &params);
7772        let (_total_bytes, views) =
7773            fuel_ir::storage::compose_bundle(&specs).expect("SelectiveScan compose_bundle");
7774        let mut g = self.graph.write().unwrap();
7775        let id = g.push(Node {
7776            op: Op::Fused(crate::registry::FusedOps::SELECTIVE_SCAN, params),
7777            inputs: vec![self.id, delta.id, a.id, b.id, c.id],
7778            shape: Shape::from_dims(&[batch, seqlen, dim]),
7779            dtype,
7780        });
7781        g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7782            .expect("SelectiveScan set_output_views");
7783        drop(g);
7784        Self {
7785            graph: self.graph.clone(),
7786            id,
7787        }
7788    }
7789
7790    /// Single-output SelectiveScan: returns the `y` slot of the
7791    /// bundled producer, with the View(0) projection emitted so
7792    /// callers can downstream-realize / copy / etc. transparently.
7793    /// See [`Self::selective_scan_bundled`] for the multi-output
7794    /// variant that also exposes `last_state` for autoregressive
7795    /// resumption.
7796    ///
7797    /// # Panics
7798    ///
7799    /// Panics if any operand belongs to a different [`Graph`] than the one this
7800    /// builder is building into. Operand identity is graph-scoped and checked by
7801    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7802    /// deliberate and replaces the hang a cross-graph handle used to produce.
7803    /// Build every operand from one graph, or use a `Result`-returning entry
7804    /// point where one exists.
7805    pub fn selective_scan(
7806        &self,
7807        delta: &NodeHandle,
7808        a: &NodeHandle,
7809        b: &NodeHandle,
7810        c: &NodeHandle,
7811        delta_softplus: bool,
7812    ) -> NodeHandle {
7813        self.assert_same_graph(delta, "selective_scan", "delta");
7814        self.assert_same_graph(a, "selective_scan", "a");
7815        self.assert_same_graph(b, "selective_scan", "b");
7816        self.assert_same_graph(c, "selective_scan", "c");
7817        let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7818        producer
7819            .view(0)
7820            .expect("SelectiveScan view(0) must succeed (just registered slots)")
7821    }
7822
7823    /// Multi-output variant of [`Self::selective_scan`]. Returns
7824    /// `(y, last_state)` — both Op::View tensors projected from the
7825    /// shared bundled producer. `y` matches the existing
7826    /// single-output `selective_scan` shape; `last_state` is the
7827    /// final hidden state `[batch, dim, dstate]` for autoregressive
7828    /// resumption.
7829    pub fn selective_scan_bundled(
7830        &self,
7831        delta: &NodeHandle,
7832        a: &NodeHandle,
7833        b: &NodeHandle,
7834        c: &NodeHandle,
7835        delta_softplus: bool,
7836    ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7837        self.require_same_graph(delta, "selective_scan_bundled", "delta")?;
7838        self.require_same_graph(a, "selective_scan_bundled", "a")?;
7839        self.require_same_graph(b, "selective_scan_bundled", "b")?;
7840        self.require_same_graph(c, "selective_scan_bundled", "c")?;
7841        let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7842        let y = producer.view(0)?;
7843        let last_state = producer.view(1)?;
7844        Ok((y, last_state))
7845    }
7846
7847    /// Multi-output variant of [`Self::ssd_chunk_scan`]. Returns
7848    /// `(y, last_state)`.
7849    pub fn ssd_chunk_scan_bundled(
7850        &self,
7851        dt: &NodeHandle,
7852        a: &NodeHandle,
7853        b: &NodeHandle,
7854        c: &NodeHandle,
7855        chunk_size: usize,
7856    ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7857        self.require_same_graph(dt, "ssd_chunk_scan_bundled", "dt")?;
7858        self.require_same_graph(a, "ssd_chunk_scan_bundled", "a")?;
7859        self.require_same_graph(b, "ssd_chunk_scan_bundled", "b")?;
7860        self.require_same_graph(c, "ssd_chunk_scan_bundled", "c")?;
7861        let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7862        let y = producer.view(0)?;
7863        let last_state = producer.view(1)?;
7864        Ok((y, last_state))
7865    }
7866
7867    /// TopKLastDim (ROADMAP row 172 item 2): the `k` largest values along the
7868    /// last axis and their `U32` indices. Returns `(values, indices)`, each
7869    /// `[.., k]`; descending, NaN largest, ties lower index first. `k` is static
7870    /// and validated here (`1 <= k <= last axis length`); a bad `k`, a non-float
7871    /// dtype or a rank-0 input is an `Err`, never a panic.
7872    pub fn top_k_last_dim(
7873        &self,
7874        k: usize,
7875    ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7876        let dtype = self.dtype();
7877        if !matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16) {
7878            return Err(fuel_ir::Error::Msg(format!(
7879                "top_k_last_dim: input must be F32/F64/BF16/F16, got {dtype:?}"
7880            ))
7881            .bt());
7882        }
7883        let shape = self.shape();
7884        let Some(&n) = shape.dims().last() else {
7885            return Err(fuel_ir::Error::Msg("top_k_last_dim: input must be rank >= 1".into()).bt());
7886        };
7887        crate::registry::top_k_last_dim::validate_k(k, n)
7888            .map_err(|m| fuel_ir::Error::Msg(m).bt())?;
7889        let params = crate::registry::FusedOpParams::TopKLastDim { k };
7890        let entry = crate::registry::default_registry()
7891            .entry(crate::registry::FusedOps::TOP_K_LAST_DIM)
7892            .ok_or_else(|| {
7893                fuel_ir::Error::Msg("top_k_last_dim: TOP_K_LAST_DIM is not registered".into()).bt()
7894            })?;
7895        let specs = (entry.output_views.ok_or_else(|| {
7896            fuel_ir::Error::Msg("top_k_last_dim: entry has no output_views".into()).bt()
7897        })?)(std::slice::from_ref(&shape), &[dtype], &params);
7898        let (_total_bytes, views) = fuel_ir::storage::compose_bundle(&specs)?;
7899        let slot0 = specs[0].shape.clone();
7900        let mut g = self.graph.write().unwrap();
7901        let id = g.push(Node {
7902            op: Op::Fused(crate::registry::FusedOps::TOP_K_LAST_DIM, params),
7903            inputs: vec![self.id],
7904            shape: slot0,
7905            dtype,
7906        });
7907        g.set_output_views(id, Arc::from(views.into_boxed_slice()))?;
7908        drop(g);
7909        let producer = Self {
7910            graph: self.graph.clone(),
7911            id,
7912        };
7913        let values = producer.view(0)?;
7914        let indices = producer.view(1)?;
7915        Ok((values, indices))
7916    }
7917
7918    /// MatMulTopK (ROADMAP row 172 item 2 step B): `TopKLastDim(self @ b)` as one
7919    /// fused node. `self [.., M, K]` and `b [.., K, N]` need equal rank >= 2 and
7920    /// equal batch dims, one float dtype; returns `(values, indices)`, each
7921    /// `[.., M, k]`. An `Err`, never a panic, on any violation.
7922    pub fn matmul_top_k(
7923        &self,
7924        b: &NodeHandle,
7925        k: usize,
7926    ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7927        self.require_same_graph(b, "matmul_top_k", "b")?;
7928        let dtype = self.dtype();
7929        if !matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16)
7930            || b.dtype() != dtype
7931        {
7932            return Err(fuel_ir::Error::Msg(format!(
7933                "matmul_top_k: a and b must share one float dtype, got {dtype:?} and {:?}",
7934                b.dtype()
7935            ))
7936            .bt());
7937        }
7938        let (a_shape, b_shape) = (self.shape(), b.shape());
7939        let (ad, bd) = (a_shape.dims(), b_shape.dims());
7940        if ad.len() < 2 || ad.len() != bd.len() || ad[..ad.len() - 2] != bd[..bd.len() - 2] {
7941            return Err(fuel_ir::Error::Msg(format!(
7942                "matmul_top_k: a {ad:?} and b {bd:?} need equal rank >= 2 and equal batch dims"
7943            ))
7944            .bt());
7945        }
7946        if ad[ad.len() - 1] != bd[bd.len() - 2] {
7947            return Err(fuel_ir::Error::Msg(format!(
7948                "matmul_top_k: contracting dims disagree: a {ad:?}, b {bd:?}"
7949            ))
7950            .bt());
7951        }
7952        crate::registry::top_k_last_dim::validate_k(k, bd[bd.len() - 1])
7953            .map_err(|m| fuel_ir::Error::Msg(m).bt())?;
7954        let params = crate::registry::FusedOpParams::MatMulTopK { k };
7955        let entry = crate::registry::default_registry()
7956            .entry(crate::registry::FusedOps::MATMUL_TOP_K)
7957            .ok_or_else(|| {
7958                fuel_ir::Error::Msg("matmul_top_k: MATMUL_TOP_K is not registered".into()).bt()
7959            })?;
7960        let ins = [a_shape.clone(), b_shape.clone()];
7961        let specs = (entry.output_views.ok_or_else(|| {
7962            fuel_ir::Error::Msg("matmul_top_k: entry has no output_views".into()).bt()
7963        })?)(&ins, &[dtype, dtype], &params);
7964        let (_total_bytes, views) = fuel_ir::storage::compose_bundle(&specs)?;
7965        let slot0 = specs[0].shape.clone();
7966        let mut g = self.graph.write().unwrap();
7967        let id = g.push(Node {
7968            op: Op::Fused(crate::registry::FusedOps::MATMUL_TOP_K, params),
7969            inputs: vec![self.id, b.id],
7970            shape: slot0,
7971            dtype,
7972        });
7973        g.set_output_views(id, Arc::from(views.into_boxed_slice()))?;
7974        drop(g);
7975        let producer = Self {
7976            graph: self.graph.clone(),
7977            id,
7978        };
7979        Ok((producer.view(0)?, producer.view(1)?))
7980    }
7981
7982    /// Append an [`Op::NonZeroIndices`] producer node — the keystone
7983    /// primitive for **data-dependent dynamic shapes**. Returns the
7984    /// bundled producer `NodeHandle` (a `[capacity]` U32 tensor); callers
7985    /// usually want [`Self::nonzero_indices_bundled`] to also get the
7986    /// runtime count slot.
7987    ///
7988    /// `capacity = self.elem_count()` is the static worst-case bound
7989    /// (every element nonzero). `count_sym` is the [`SymId`] the executor
7990    /// binds to the realized nonzero count in the per-pass `SymEnv`; the
7991    /// caller allocates it from their `SymGen` and threads it into any
7992    /// downstream op that consumes the count as a dynamic extent /
7993    /// `DynScalar::Sym` (the KV-cache `cached_len` pattern, generalized to
7994    /// a data-determined count).
7995    pub fn nonzero_indices_producer(&self, count_sym: SymId) -> NodeHandle {
7996        let capacity = self.shape().elem_count();
7997        let indices_shape = Shape::from_dims(&[capacity]);
7998        let count_shape = Shape::from_dims(&[1]);
7999        let specs = vec![
8000            fuel_ir::storage::OutputViewSpec {
8001                dtype: DType::U32,
8002                shape: indices_shape.clone(),
8003                layout: Layout::contiguous(indices_shape.clone()),
8004                name: Some("indices"),
8005            },
8006            fuel_ir::storage::OutputViewSpec {
8007                dtype: DType::U32,
8008                shape: count_shape.clone(),
8009                layout: Layout::contiguous(count_shape),
8010                name: Some("count"),
8011            },
8012        ];
8013        let (_total_bytes, views) =
8014            fuel_ir::storage::compose_bundle(&specs).expect("NonZeroIndices compose_bundle");
8015        let mut g = self.graph.write().unwrap();
8016        let id = g.push(Node {
8017            op: Op::NonZeroIndices { count_sym },
8018            inputs: vec![self.id],
8019            shape: indices_shape,
8020            dtype: DType::U32,
8021        });
8022        g.set_output_views(id, Arc::from(views.into_boxed_slice()))
8023            .expect("NonZeroIndices set_output_views");
8024        drop(g);
8025        Self {
8026            graph: self.graph.clone(),
8027            id,
8028        }
8029    }
8030
8031    /// Multi-output [`Op::NonZeroIndices`]: returns `(indices, count)` —
8032    /// both `Op::View` projections of the shared bundled producer.
8033    /// `indices` is `[capacity]` U32 (first `count` entries valid, in
8034    /// ascending flat order); `count` is `[1]` U32, the runtime nonzero
8035    /// count. The executor also publishes `count`'s value into the
8036    /// per-pass `SymEnv` under the producer's `count_sym`.
8037    pub fn nonzero_indices_bundled(
8038        &self,
8039        count_sym: SymId,
8040    ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
8041        let producer = self.nonzero_indices_producer(count_sym);
8042        let indices = producer.view(0)?;
8043        let count = producer.view(1)?;
8044        Ok((indices, count))
8045    }
8046
8047    /// Append a `FusedSoftmaxCrossEntropy` node. Two inputs:
8048    /// - `self` (logits): `[..., V]` F32 / F64 / BF16 / F16
8049    /// - `targets`: `[...]` I64 (class indices; matches PyTorch /
8050    ///   baracuda convention)
8051    ///
8052    /// Output dtype is always F32 (the FSCE declared dtype — losses
8053    /// accumulate in F64 and narrow to F32, matching PyTorch and the
8054    /// baracuda kernel) regardless of the logits dtype. Output shape
8055    /// depends on `reduction`:
8056    /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
8057    /// - `Reduction::None` → same as `targets.shape`
8058    ///
8059    /// `ignore_index` rows are dropped from the loss accumulator and
8060    /// the Mean denominator. The conventional sentinel is `-100`.
8061    ///
8062    /// Emits `Op::Fused(FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
8063    /// FusedOpParams::FusedSoftmaxCrossEntropy { reduction, ignore_index })`.
8064    /// See `fuel-graph/src/registry/fused_softmax_cross_entropy.rs` for
8065    /// the registry entry and decompose chain.
8066    ///
8067    /// # Panics
8068    ///
8069    /// Panics if any operand belongs to a different [`Graph`] than the one this
8070    /// builder is building into. Operand identity is graph-scoped and checked by
8071    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8072    /// deliberate and replaces the hang a cross-graph handle used to produce.
8073    /// Build every operand from one graph, or use a `Result`-returning entry
8074    /// point where one exists.
8075    pub fn fused_softmax_cross_entropy(
8076        &self,
8077        targets: &NodeHandle,
8078        reduction: crate::registry::Reduction,
8079        ignore_index: i64,
8080    ) -> NodeHandle {
8081        assert!(
8082            Arc::ptr_eq(&self.graph, &targets.graph),
8083            "fused_softmax_cross_entropy: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8084        );
8085        assert!(
8086            matches!(
8087                self.dtype(),
8088                DType::F32 | DType::F64 | DType::BF16 | DType::F16,
8089            ),
8090            "fused_softmax_cross_entropy: logits must be F32/F64/BF16/F16, got {:?}",
8091            self.dtype(),
8092        );
8093        assert_eq!(
8094            targets.dtype(),
8095            DType::I64,
8096            "fused_softmax_cross_entropy: targets must be I64, got {:?}",
8097            targets.dtype(),
8098        );
8099        let logits_dims = self.shape();
8100        let logits_dims = logits_dims.dims();
8101        assert!(
8102            !logits_dims.is_empty(),
8103            "fused_softmax_cross_entropy: logits must have rank ≥ 1",
8104        );
8105        let target_dims = targets.shape();
8106        let target_dims = target_dims.dims();
8107        assert_eq!(
8108            target_dims,
8109            &logits_dims[..logits_dims.len() - 1],
8110            "fused_softmax_cross_entropy: targets shape {target_dims:?} must equal \
8111             logits shape {logits_dims:?} minus the last dim",
8112        );
8113        let out_shape = match reduction {
8114            crate::registry::Reduction::Mean | crate::registry::Reduction::Sum => {
8115                Shape::from_dims(&[])
8116            }
8117            crate::registry::Reduction::None => Shape::from_dims(target_dims),
8118        };
8119        let id = self.graph.write().unwrap().push(Node {
8120            op: Op::Fused(
8121                crate::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
8122                crate::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
8123                    reduction,
8124                    ignore_index,
8125                },
8126            ),
8127            inputs: vec![self.id, targets.id],
8128            shape: out_shape,
8129            dtype: DType::F32,
8130        });
8131        Self {
8132            graph: self.graph.clone(),
8133            id,
8134        }
8135    }
8136
8137    /// Append a `LayerNormLastDim` node with the given epsilon. Shape is
8138    /// preserved.
8139    ///
8140    /// Phase 7.6 step 4 (continued): emits
8141    /// `Op::Fused(FusedOps::LAYER_NORM_LAST_DIM, FusedOpParams::LayerNormLastDim { eps })`
8142    /// through the registry-extended arm. The legacy
8143    /// `Op::LayerNormLastDim { eps }` variant remains in the enum
8144    /// during migration; step 5 drops it once nothing emits it.
8145    pub fn layer_norm_last_dim(&self, eps: f64) -> NodeHandle {
8146        let dims = self.shape();
8147        let d = dims.dims();
8148        assert!(
8149            !d.is_empty() && *d.last().unwrap() > 0,
8150            "layer_norm_last_dim: input must have a non-zero last dim, got {d:?}",
8151        );
8152        self.unary_op(Op::Fused(
8153            crate::registry::FusedOps::LAYER_NORM_LAST_DIM,
8154            crate::registry::FusedOpParams::LayerNormLastDim { eps },
8155        ))
8156    }
8157
8158    /// Apply rotary position embeddings (RoPE) to `self`. The input is
8159    /// expected to have shape `[..., seq, d]` where `seq` is the
8160    /// sequence length and `d` is the per-head feature dim (which must
8161    /// be even). `base` is the frequency base — 10000.0 for LLaMA.
8162    /// `start_pos` lets callers apply RoPE at a non-zero offset, which
8163    /// is what KV-cached inference does when the query for position
8164    /// `n + k` is processed against a cache that already holds
8165    /// positions `0..n+k`.
8166    ///
8167    /// Uses the half-split layout (the one LLaMA and HuggingFace use):
8168    /// pair feature `i` with feature `i + d/2`. Under that layout the
8169    /// rotation reduces to the identity `x' = x·cos + rotate_half(x)·sin`
8170    /// where `rotate_half(x)` concatenates `[-x[d/2:], x[:d/2]]` along
8171    /// the last dim.
8172    ///
8173    /// Implemented as a composition of existing graph primitives —
8174    /// `Slice`, `Neg`, `Concat`, `Reshape`, `BroadcastTo`, `Mul`, `Add`
8175    /// — plus two precomputed `Const` tensors for the cos/sin frequency
8176    /// tables. Every primitive already has a working backward rule, so
8177    /// gradients flow through RoPE without any new backward machinery.
8178    ///
8179    /// Only `f32` is supported today. Extending to other float dtypes
8180    /// is mechanical: build the frequency tables in the target dtype.
8181    pub fn rope(&self, base: f64, start_pos: usize) -> NodeHandle {
8182        let (seq, d) = {
8183            let dims = self.shape();
8184            let v = dims.dims();
8185            let rank = v.len();
8186            assert!(rank >= 2, "rope: input must have rank ≥ 2");
8187            (v[rank - 2], v[rank - 1])
8188        };
8189        let (cos, sin) = build_rope_tables(base, start_pos, seq, d);
8190        // Phase 7.5 G2: const_*_like derives the device from self's
8191        // graph internally — RoPE tables go on the same device as self.
8192        // ⚠️ GAP-003 category 2, in production: the proof EXISTS but is NOT
8193        // LOCAL -- `build_rope_tables` owns the length guarantee and its
8194        // signature `-> (Vec<f32>, Vec<f32>)` does not carry it. So the message
8195        // claims NO proof; it names where the guarantee lives. `rope` returns
8196        // `NodeHandle` and already asserts on rank, so giving it an error
8197        // channel is a signature change -- a different obligation. See #157.
8198        let cos_t = self
8199            .const_f32_like(cos, Shape::from_dims(&[seq, d]))
8200            .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
8201        let sin_t = self
8202            .const_f32_like(sin, Shape::from_dims(&[seq, d]))
8203            .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
8204        self.rope_with_tables(&cos_t, &sin_t)
8205    }
8206
8207    /// Apply RoPE using caller-supplied `cos` and `sin` tables. Each
8208    /// table has shape `[seq, head_dim]` and matches the layout
8209    /// [`build_rope_tables`] produces. This is the hot-path entry
8210    /// point: in a transformer forward pass every attention layer
8211    /// applies RoPE to Q and K with the *same* `(start_pos, seq,
8212    /// head_dim)`, so the caller can build the tables once and share
8213    /// the const nodes across all layers rather than re-duplicating
8214    /// them inside each `.rope()` call. The classic [`Self::rope`] entry
8215    /// point funnels through this after building the tables itself.
8216    ///
8217    /// # Panics
8218    ///
8219    /// Panics if any operand belongs to a different [`Graph`] than the one this
8220    /// builder is building into. Operand identity is graph-scoped and checked by
8221    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8222    /// deliberate and replaces the hang a cross-graph handle used to produce.
8223    /// Build every operand from one graph, or use a `Result`-returning entry
8224    /// point where one exists.
8225    pub fn rope_with_tables(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8226        self.assert_same_graph(cos, "rope_with_tables", "cos");
8227        self.assert_same_graph(sin, "rope_with_tables", "sin");
8228        assert_eq!(
8229            self.dtype(),
8230            DType::F32,
8231            "rope: only f32 is supported today (cast explicitly for other dtypes)",
8232        );
8233        let in_shape = self.shape();
8234        let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8235        let rank = dims_vec.len();
8236        assert!(
8237            rank >= 2,
8238            "rope: input must have rank ≥ 2, got {dims_vec:?}"
8239        );
8240        let seq = dims_vec[rank - 2];
8241        let d = dims_vec[rank - 1];
8242        assert!(d.is_multiple_of(2), "rope: feature dim {d} must be even",);
8243        let cos_shape = cos.shape();
8244        let sin_shape = sin.shape();
8245        assert_eq!(
8246            cos_shape.dims(),
8247            &[seq, d],
8248            "rope_with_tables: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
8249            cos_shape.dims(),
8250        );
8251        assert_eq!(
8252            sin_shape.dims(),
8253            &[seq, d],
8254            "rope_with_tables: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
8255            sin_shape.dims(),
8256        );
8257        let _ = rank;
8258        // Emit a single fused Rope node. The decomposed version
8259        // (slice+neg+concat+broadcast+mul+add) produces ~72 dispatches
8260        // on GPU backends because concat-along-last-dim has a per-row
8261        // host loop. Fused path dispatches once.
8262        //
8263        // Phase 7.6 step 4 (continued): emits
8264        // `Op::Fused(FusedOps::ROPE, FusedOpParams::Rope)` through the
8265        // registry-extended arm. The legacy `Op::Rope` variant remains
8266        // in the enum during migration; step 5 drops it once nothing
8267        // emits it.
8268        let out_shape = in_shape.clone();
8269        let dtype = self.dtype();
8270        let id = self.graph.write().unwrap().push(Node {
8271            op: Op::Fused(
8272                crate::registry::FusedOps::ROPE,
8273                crate::registry::FusedOpParams::Rope,
8274            ),
8275            inputs: vec![self.id, cos.id, sin.id],
8276            shape: out_shape,
8277            dtype,
8278        });
8279        Self {
8280            graph: self.graph.clone(),
8281            id,
8282        }
8283    }
8284
8285    /// The pre-fused decomposition of `rope_with_tables`. Retained so
8286    /// backends without a native `Op::Rope` kernel can synthesize from
8287    /// primitives, and so correctness tests can cross-check the fused
8288    /// path against the primitive path.
8289    ///
8290    /// # Panics
8291    ///
8292    /// Panics if any operand belongs to a different [`Graph`] than the one this
8293    /// builder is building into. Operand identity is graph-scoped and checked by
8294    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8295    /// deliberate and replaces the hang a cross-graph handle used to produce.
8296    /// Build every operand from one graph, or use a `Result`-returning entry
8297    /// point where one exists.
8298    #[doc(hidden)]
8299    pub fn rope_with_tables_decomposed(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8300        self.assert_same_graph(cos, "rope_with_tables_decomposed", "cos");
8301        self.assert_same_graph(sin, "rope_with_tables_decomposed", "sin");
8302        let in_shape = self.shape();
8303        let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8304        let rank = dims_vec.len();
8305        let seq = dims_vec[rank - 2];
8306        let d = dims_vec[rank - 1];
8307        let half = d / 2;
8308
8309        let mut broadcast_shape: Vec<usize> = vec![1_usize; rank];
8310        broadcast_shape[rank - 2] = seq;
8311        broadcast_shape[rank - 1] = d;
8312        let cos_reshaped = cos.reshape(Shape::from_dims(&broadcast_shape));
8313        let sin_reshaped = sin.reshape(Shape::from_dims(&broadcast_shape));
8314        let cos_bcast = cos_reshaped.broadcast_to(in_shape.clone());
8315        let sin_bcast = sin_reshaped.broadcast_to(in_shape);
8316
8317        let first_half = self.slice(rank - 1, 0, half);
8318        let second_half = self.slice(rank - 1, half, half);
8319        let neg_second = second_half.neg();
8320        let rotated_half = neg_second.concat(&first_half, rank - 1);
8321
8322        let left = self.mul(&cos_bcast);
8323        let right = rotated_half.mul(&sin_bcast);
8324        left.add(&right)
8325    }
8326
8327    /// Root-Mean-Square Normalization along the last dim, without
8328    /// affine parameters. `y = x / sqrt(mean(x², last) + eps)`.
8329    ///
8330    /// This is the normalization layer used by LLaMA-family models.
8331    /// Unlike LayerNorm, RmsNorm does not subtract the mean — it only
8332    /// divides by the root-mean-square, which is both cheaper and
8333    /// empirically just as effective in transformer blocks.
8334    ///
8335    /// Emits a fused RmsNormLastDim node. Backends that have a native
8336    /// implementation dispatch it as one kernel; ones that don't get a
8337    /// CPU fallback via the reference implementation.
8338    ///
8339    /// Phase 7.6 step 4 (continued): emits
8340    /// `Op::Fused(FusedOps::RMS_NORM_LAST_DIM, FusedOpParams::RmsNormLastDim { eps })`
8341    /// through the registry-extended arm. The legacy
8342    /// `Op::RmsNormLastDim { eps }` variant remains in the enum during
8343    /// migration; step 5 drops it once nothing emits it.
8344    ///
8345    /// Use [`rms_norm_last_dim_decomposed`](Self::rms_norm_last_dim_decomposed)
8346    /// instead if you need to differentiate through this op —
8347    /// backward through the fused op is not yet implemented.
8348    pub fn rms_norm_last_dim(&self, eps: f64) -> NodeHandle {
8349        let x_dims_vec: Vec<usize> = self.shape().dims().to_vec();
8350        assert!(
8351            !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8352            "rms_norm_last_dim: input must have non-zero last dim, got {x_dims_vec:?}",
8353        );
8354        self.unary_op(Op::Fused(
8355            crate::registry::FusedOps::RMS_NORM_LAST_DIM,
8356            crate::registry::FusedOpParams::RmsNormLastDim { eps },
8357        ))
8358    }
8359
8360    /// Decomposed version — emits the (sqr → mean_dim → reshape →
8361    /// add_scalar → sqrt → broadcast_to → div) primitive chain. Has
8362    /// working backward rules through its primitive subgraph. Use
8363    /// this when you need to differentiate through RMSNorm; use
8364    /// [`rms_norm_last_dim`](Self::rms_norm_last_dim) for inference.
8365    pub fn rms_norm_last_dim_decomposed(&self, eps: f64) -> NodeHandle {
8366        let x_shape = self.shape();
8367        let x_dims_vec: Vec<usize> = x_shape.dims().to_vec();
8368        assert!(
8369            !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8370            "rms_norm_last_dim_decomposed: input must have non-zero last dim, got {x_dims_vec:?}",
8371        );
8372        let last = x_dims_vec.len() - 1;
8373        let mean_sq = self.sqr().mean_dim(last);
8374        let mut keepdim_dims = x_dims_vec.clone();
8375        keepdim_dims[last] = 1;
8376        let mean_sq_kd = mean_sq.reshape(Shape::from_dims(&keepdim_dims));
8377        let denom = mean_sq_kd.add_scalar(eps).sqrt();
8378        let denom_bcast = denom.broadcast_to(x_shape);
8379        self.div(&denom_bcast)
8380    }
8381
8382    // --- indexing ---
8383
8384    /// Append an `IndexSelect` node that picks slices from `self` along
8385    /// `dim` using a 1-D `u32` index tensor. The output has the same
8386    /// shape as `self` except dimension `dim` is replaced by
8387    /// `indices.shape()[0]`.
8388    ///
8389    /// # Panics
8390    ///
8391    /// Panics if any operand belongs to a different [`Graph`] than the one this
8392    /// builder is building into. Operand identity is graph-scoped and checked by
8393    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8394    /// deliberate and replaces the hang a cross-graph handle used to produce.
8395    /// Build every operand from one graph, or use a `Result`-returning entry
8396    /// point where one exists.
8397    pub fn index_select(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8398        assert!(
8399            Arc::ptr_eq(&self.graph, &indices.graph),
8400            "index_select: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8401        );
8402        assert_eq!(
8403            indices.dtype(),
8404            DType::U32,
8405            "index_select: index tensor must be U32, got {:?}",
8406            indices.dtype(),
8407        );
8408        let idx_dims = indices.shape();
8409        assert_eq!(
8410            idx_dims.dims().len(),
8411            1,
8412            "index_select: index tensor must be rank 1, got {:?}",
8413            idx_dims.dims(),
8414        );
8415        let data_dims = self.shape();
8416        assert!(
8417            dim < data_dims.dims().len(),
8418            "index_select: dim {dim} out of bounds for data shape {:?}",
8419            data_dims.dims(),
8420        );
8421        let op = Op::IndexSelect { dim };
8422        let (shape, dtype) = crate::shape::primitive_shape(
8423            &op,
8424            &[data_dims, idx_dims],
8425            &[self.dtype(), indices.dtype()],
8426        )
8427        .expect("index_select: shapes/dims validated above");
8428        let id = self.graph.write().unwrap().push(Node {
8429            op,
8430            inputs: vec![self.id, indices.id],
8431            shape,
8432            dtype,
8433        });
8434        Self {
8435            graph: self.graph.clone(),
8436            id,
8437        }
8438    }
8439
8440    /// Append a `Gather` node that performs an N-dimensional gather along
8441    /// `dim`. The `indices` tensor must be `U32` with the same rank as
8442    /// `self`. Output shape equals `indices.shape()`.
8443    ///
8444    /// # Panics
8445    ///
8446    /// Panics if any operand belongs to a different [`Graph`] than the one this
8447    /// builder is building into. Operand identity is graph-scoped and checked by
8448    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8449    /// deliberate and replaces the hang a cross-graph handle used to produce.
8450    /// Build every operand from one graph, or use a `Result`-returning entry
8451    /// point where one exists.
8452    pub fn gather(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8453        assert!(
8454            Arc::ptr_eq(&self.graph, &indices.graph),
8455            "gather: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8456        );
8457        assert_eq!(
8458            indices.dtype(),
8459            DType::U32,
8460            "gather: index tensor must be U32, got {:?}",
8461            indices.dtype(),
8462        );
8463        let data_rank = self.shape().dims().len();
8464        let idx_rank = indices.shape().dims().len();
8465        assert_eq!(
8466            data_rank, idx_rank,
8467            "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
8468        );
8469        assert!(
8470            dim < data_rank,
8471            "gather: dim {dim} out of bounds for rank {data_rank}",
8472        );
8473        let op = Op::Gather { dim };
8474        let (shape, dtype) = crate::shape::primitive_shape(
8475            &op,
8476            &[self.shape(), indices.shape()],
8477            &[self.dtype(), indices.dtype()],
8478        )
8479        .expect("gather: shapes/dims validated above");
8480        let id = self.graph.write().unwrap().push(Node {
8481            op,
8482            inputs: vec![self.id, indices.id],
8483            shape,
8484            dtype,
8485        });
8486        Self {
8487            graph: self.graph.clone(),
8488            id,
8489        }
8490    }
8491
8492    /// Append a `Concat` node joining `self` and `other` along `dim`.
8493    ///
8494    /// # Panics
8495    ///
8496    /// Panics if any operand belongs to a different [`Graph`] than the one this
8497    /// builder is building into. Operand identity is graph-scoped and checked by
8498    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8499    /// deliberate and replaces the hang a cross-graph handle used to produce.
8500    /// Build every operand from one graph, or use a `Result`-returning entry
8501    /// point where one exists.
8502    pub fn concat(&self, other: &NodeHandle, dim: usize) -> NodeHandle {
8503        assert!(
8504            Arc::ptr_eq(&self.graph, &other.graph),
8505            "concat: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8506        );
8507        assert_eq!(
8508            self.dtype(),
8509            other.dtype(),
8510            "concat: dtype mismatch {:?} vs {:?}",
8511            self.dtype(),
8512            other.dtype(),
8513        );
8514        let a = self.shape();
8515        let b = other.shape();
8516        let ad = a.dims();
8517        let bd = b.dims();
8518        assert_eq!(ad.len(), bd.len(), "concat: rank mismatch");
8519        assert!(dim < ad.len(), "concat: dim out of bounds");
8520        for i in 0..ad.len() {
8521            if i != dim {
8522                assert_eq!(
8523                    ad[i], bd[i],
8524                    "concat: non-dim shapes must match (dim {i}: {} vs {})",
8525                    ad[i], bd[i],
8526                );
8527            }
8528        }
8529        let op = Op::Concat { dim };
8530        let (shape, dtype) =
8531            crate::shape::primitive_shape(&op, &[a, b], &[self.dtype(), other.dtype()])
8532                .expect("concat: shapes/dtypes validated above");
8533        let id = self.graph.write().unwrap().push(Node {
8534            op,
8535            inputs: vec![self.id, other.id],
8536            shape,
8537            dtype,
8538        });
8539        Self {
8540            graph: self.graph.clone(),
8541            id,
8542        }
8543    }
8544
8545    /// Append a `Slice` (narrow) node taking elements `[start, start+len)`
8546    /// along `dim`. The output has the same rank; only `dim` shrinks.
8547    pub fn slice(&self, dim: usize, start: usize, len: usize) -> NodeHandle {
8548        let in_shape = self.shape();
8549        let in_dims = in_shape.dims();
8550        assert!(dim < in_dims.len(), "slice: dim out of bounds");
8551        assert!(
8552            start + len <= in_dims[dim],
8553            "slice: [start={start}, len={len}) exceeds dim size {}",
8554            in_dims[dim],
8555        );
8556        let op = Op::Slice { dim, start, len };
8557        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8558            .expect("slice: dim/start/len validated above");
8559        let id = self.graph.write().unwrap().push(Node {
8560            op,
8561            inputs: vec![self.id],
8562            shape,
8563            dtype,
8564        });
8565        Self {
8566            graph: self.graph.clone(),
8567            id,
8568        }
8569    }
8570
8571    /// Append an `AddScalar` node: `y[i] = x[i] + c`. Convenient for
8572    /// avoiding a full-shape const node when you just want to bias a
8573    /// tensor by a constant.
8574    pub fn add_scalar(&self, c: f64) -> NodeHandle {
8575        self.unary_op(Op::AddScalar(c))
8576    }
8577
8578    /// Append a `MulScalar` node: `y[i] = x[i] * c`.
8579    pub fn mul_scalar(&self, c: f64) -> NodeHandle {
8580        self.unary_op(Op::MulScalar(c))
8581    }
8582
8583    /// Append a `PowI` node raising each element to an integer power.
8584    pub fn powi(&self, n: i32) -> NodeHandle {
8585        self.unary_op(Op::PowI(n))
8586    }
8587
8588    /// Append a `Clamp` node restricting each element to `[min, max]`.
8589    pub fn clamp(&self, min: f64, max: f64) -> NodeHandle {
8590        assert!(min <= max, "clamp: min ({min}) must be <= max ({max})",);
8591        self.unary_op(Op::Clamp { min, max })
8592    }
8593
8594    /// Append a `Maximum` node `max(self, other)` element-wise. Matching
8595    /// shapes required.
8596    ///
8597    /// # Panics
8598    ///
8599    /// Panics if any operand belongs to a different [`Graph`] than the one this
8600    /// builder is building into. Operand identity is graph-scoped and checked by
8601    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8602    /// deliberate and replaces the hang a cross-graph handle used to produce.
8603    /// Build every operand from one graph, or use a `Result`-returning entry
8604    /// point where one exists.
8605    pub fn maximum(&self, other: &NodeHandle) -> NodeHandle {
8606        self.binary_op("maximum", Op::Maximum, other, self.shape())
8607    }
8608
8609    /// Append a `Minimum` node `min(self, other)` element-wise.
8610    ///
8611    /// # Panics
8612    ///
8613    /// Panics if any operand belongs to a different [`Graph`] than the one this
8614    /// builder is building into. Operand identity is graph-scoped and checked by
8615    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8616    /// deliberate and replaces the hang a cross-graph handle used to produce.
8617    /// Build every operand from one graph, or use a `Result`-returning entry
8618    /// point where one exists.
8619    pub fn minimum(&self, other: &NodeHandle) -> NodeHandle {
8620        self.binary_op("minimum", Op::Minimum, other, self.shape())
8621    }
8622
8623    /// The IEEE-754 NaN-**suppressing** maximum — the KISS-OPS §6.15-0001
8624    /// `fmax_ieee` op, DISTINCT from [`maximum`](Self::maximum) (which is
8625    /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8626    /// the other; if both are NaN, returns NaN; otherwise the larger.
8627    ///
8628    /// Built by RESOLUTION through the spec-pinned §6.13 decomposition
8629    /// (KISS-OPS-6.15-0001), used VERBATIM — Fuel does not substitute `maximum`
8630    /// for it (that substitution is the §6.15 violation). Because the
8631    /// decomposition is spec-authored, its edge behaviour — including ±0 ordering
8632    /// under `cmp_ge` (`cmp_ge(-0.0, +0.0)` is true, so this returns `-0.0` for
8633    /// that pair) — is the SPEC's to define and a KISS conformance vector's to
8634    /// catch. Fuel resolves; it does not re-derive. (GAP-048.)
8635    pub fn fmax_ieee(&self, other: &NodeHandle) -> NodeHandle {
8636        // select(a != a, b, select(b != b, a, select(a >= b, a, b)))
8637        let a = self;
8638        let b = other;
8639        let plain = a.ge(b).where_cond(a, b); // a >= b ? a : b
8640        let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8641        a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8642    }
8643
8644    /// The IEEE-754 NaN-**suppressing** minimum — the KISS-OPS §6.15-0001
8645    /// `fmin_ieee` op, DISTINCT from [`minimum`](Self::minimum) (which is
8646    /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8647    /// the other; if both are NaN, returns NaN; otherwise the smaller.
8648    ///
8649    /// Built by RESOLUTION through the spec-pinned KISS-OPS §6.13 decomposition
8650    /// (KISS-OPS-6.15-0001), used VERBATIM — the `cmp_le` mirror of
8651    /// [`fmax_ieee`](Self::fmax_ieee)'s `cmp_ge` form. Fuel resolves; it does not
8652    /// substitute `minimum` (that substitution is the §6.15 violation) and does
8653    /// not re-derive: the decomposition is KISS's, so its ±0 edge behaviour is the
8654    /// spec's to define and a KISS conformance vector's to catch. (GAP-048.)
8655    pub fn fmin_ieee(&self, other: &NodeHandle) -> NodeHandle {
8656        // select(a != a, b, select(b != b, a, select(a <= b, a, b)))
8657        let a = self;
8658        let b = other;
8659        let plain = a.le(b).where_cond(a, b); // a <= b ? a : b
8660        let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8661        a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8662    }
8663
8664    /// Round toward zero — the KISS-OPS §6.3 `trunc` floor op (GAP-300).
8665    ///
8666    /// ⚠️ Unlike [`fmax_ieee`](Self::fmax_ieee)/[`fmin_ieee`](Self::fmin_ieee),
8667    /// which resolve through KISS's OWN §6.13 decompositions, `trunc` is a §6.3
8668    /// *floor* op: KISS-OPS-6.3-0003 forbids the standard from carrying a
8669    /// reference decomposition for a floor op, so THIS expansion is FUEL's, blessed
8670    /// by no spec clause. It IS now checked by KISS vectors: `ops-rounding.json`
8671    /// (vendored at KISS `0af5d3b6`) carries 18 `f32` `trunc` cells (signed zero, halves
8672    /// and ties, 2^23, max finite, ±inf, subnormals), all of which pass through the lazy
8673    /// `Tensor` (`fuel-tensor/tests/kiss_nan_conformance.rs`); `f64` and NaN inputs are
8674    /// not in that file. Beyond it, correctness is Fuel's liability — see GAP-300, whose born-reds assert
8675    /// on `to_bits()` (a value compare `0.0 == -0.0` passes vacuously).
8676    ///
8677    /// `trunc(q) = if q >= 0 { floor(q) } else { ceil(q) }`. Float dtypes only;
8678    /// integer dtypes are already whole, so `trunc` is identity for them (returned
8679    /// unchanged — never a panic on a non-float operand).
8680    ///
8681    /// REJECTED-FOR-NOW alternative: `copysign(floor(abs(q)), q)` is cleaner (no
8682    /// dtype-matched zero; ±0/NaN/inf fall out of the IEEE primitives). Fuel has no
8683    /// `copysign` op today (absent from `Op` and the builder API), so it is not
8684    /// buildable — adopt it IF `copysign` ever lands.
8685    pub fn trunc(&self) -> NodeHandle {
8686        let q = self;
8687        // A scalar zero of q's dtype, broadcast to q's shape — comparisons require
8688        // matching shapes (no implicit broadcast in `binary_compare_op`).
8689        let zero = match q.dtype() {
8690            DType::F32 => q
8691                .const_f32_like(vec![0.0f32], &[1])
8692                .expect("trunc: a 1-element vec with shape [1]")
8693                .broadcast_to(q.shape()),
8694            DType::F64 => q
8695                .const_f64_like(vec![0.0f64], &[1])
8696                .expect("trunc: a 1-element vec with shape [1]")
8697                .broadcast_to(q.shape()),
8698            DType::BF16 => q
8699                .const_bf16_like(vec![half::bf16::from_f32(0.0)], &[1])
8700                .expect("trunc: a 1-element vec with shape [1]")
8701                .broadcast_to(q.shape()),
8702            DType::F16 => q
8703                .const_f16_like(vec![half::f16::from_f32(0.0)], &[1])
8704                .expect("trunc: a 1-element vec with shape [1]")
8705                .broadcast_to(q.shape()),
8706            // Integer/other dtypes are already whole: trunc is identity.
8707            _ => return q.clone(),
8708        };
8709        // q >= 0 ? floor(q) : ceil(q). Note: at ±0 BOTH branches yield the same
8710        // signed zero (`floor(-0.0) == ceil(-0.0) == -0.0`), so trunc's ±0 result
8711        // is robust to a tie-bias in `ge` — but the born-red still checks the bits.
8712        q.ge(&zero).where_cond(&q.floor(), &q.ceil())
8713    }
8714
8715    /// Truncated remainder — the KISS-OPS §6.15-0003 `rem_trunc` op, DISTINCT from
8716    /// [`rem`](Self::rem) (which is FLOORED / PyTorch, sign of the *divisor*).
8717    /// `rem_trunc` takes the sign of the *dividend* (C99 `fmod` / Rust `%`).
8718    ///
8719    /// Built by RESOLUTION through KISS's spec-pinned §6.13 decomposition
8720    /// (KISS-OPS-6.15-0003) — `a - trunc(a / b) * b` — used VERBATIM. Fuel does not
8721    /// substitute `rem` (that substitution is the §6.15 violation); the two diverge
8722    /// whenever the operands have opposite signs (e.g. `-7 rem_trunc 3 = -1`, where
8723    /// `rem` (floored) = `2`). The `trunc` leaf is Fuel's own expansion (GAP-300).
8724    pub fn rem_trunc(&self, other: &NodeHandle) -> NodeHandle {
8725        // a - trunc(a / b) * b
8726        let a = self;
8727        let b = other;
8728        let t = a.div(b).trunc();
8729        a.sub(&t.mul(b))
8730    }
8731
8732    /// Element-wise addition with automatic broadcasting. Unlike `add`,
8733    /// which requires matching shapes, `broadcast_add` computes the
8734    /// broadcast shape of the two operands, inserts explicit
8735    /// `BroadcastTo` nodes as needed, and then emits a regular `Add`.
8736    /// Useful for bias addition (`[batch, hidden] + [hidden]`) without
8737    /// the caller writing the broadcast out explicitly.
8738    ///
8739    /// # Panics
8740    ///
8741    /// Panics if any operand belongs to a different [`Graph`] than the one this
8742    /// builder is building into. Operand identity is graph-scoped and checked by
8743    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8744    /// deliberate and replaces the hang a cross-graph handle used to produce.
8745    /// Build every operand from one graph, or use a `Result`-returning entry
8746    /// point where one exists.
8747    pub fn broadcast_add(&self, other: &NodeHandle) -> NodeHandle {
8748        let (a, b) = self.auto_broadcast_pair("broadcast_add", other);
8749        a.add(&b)
8750    }
8751
8752    /// Element-wise subtraction with automatic broadcasting.
8753    ///
8754    /// # Panics
8755    ///
8756    /// Panics if any operand belongs to a different [`Graph`] than the one this
8757    /// builder is building into. Operand identity is graph-scoped and checked by
8758    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8759    /// deliberate and replaces the hang a cross-graph handle used to produce.
8760    /// Build every operand from one graph, or use a `Result`-returning entry
8761    /// point where one exists.
8762    pub fn broadcast_sub(&self, other: &NodeHandle) -> NodeHandle {
8763        let (a, b) = self.auto_broadcast_pair("broadcast_sub", other);
8764        a.sub(&b)
8765    }
8766
8767    /// Element-wise multiplication with automatic broadcasting.
8768    ///
8769    /// # Panics
8770    ///
8771    /// Panics if any operand belongs to a different [`Graph`] than the one this
8772    /// builder is building into. Operand identity is graph-scoped and checked by
8773    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8774    /// deliberate and replaces the hang a cross-graph handle used to produce.
8775    /// Build every operand from one graph, or use a `Result`-returning entry
8776    /// point where one exists.
8777    pub fn broadcast_mul(&self, other: &NodeHandle) -> NodeHandle {
8778        let (a, b) = self.auto_broadcast_pair("broadcast_mul", other);
8779        a.mul(&b)
8780    }
8781
8782    /// Element-wise division with automatic broadcasting.
8783    ///
8784    /// # Panics
8785    ///
8786    /// Panics if any operand belongs to a different [`Graph`] than the one this
8787    /// builder is building into. Operand identity is graph-scoped and checked by
8788    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8789    /// deliberate and replaces the hang a cross-graph handle used to produce.
8790    /// Build every operand from one graph, or use a `Result`-returning entry
8791    /// point where one exists.
8792    pub fn broadcast_div(&self, other: &NodeHandle) -> NodeHandle {
8793        let (a, b) = self.auto_broadcast_pair("broadcast_div", other);
8794        a.div(&b)
8795    }
8796
8797    /// Build both operands broadcast to their common shape. Used by the
8798    /// `broadcast_*` wrappers above. Inserts explicit `BroadcastTo` nodes
8799    /// on whichever side needs them — either or both may pass through
8800    /// unchanged if already at the target shape.
8801    fn auto_broadcast_pair(
8802        &self,
8803        op: &'static str,
8804        other: &NodeHandle,
8805    ) -> (NodeHandle, NodeHandle) {
8806        assert!(
8807            Arc::ptr_eq(&self.graph, &other.graph),
8808            "{op}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8809             each `from_*` constructor mints a NEW graph, so build the second operand with \
8810             `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8811            self.graph_id(),
8812            other.graph_id(),
8813        );
8814        assert_eq!(
8815            self.dtype(),
8816            other.dtype(),
8817            "{op}: dtype mismatch {:?} vs {:?}",
8818            self.dtype(),
8819            other.dtype(),
8820        );
8821        let a_shape = self.shape();
8822        let b_shape = other.shape();
8823        let target_dims = compute_broadcast_shape(a_shape.dims(), b_shape.dims());
8824        let target = Shape::from_dims(&target_dims);
8825        let a = if a_shape.dims() == target.dims() {
8826            self.clone()
8827        } else {
8828            self.broadcast_to(target.clone())
8829        };
8830        let b = if b_shape.dims() == target.dims() {
8831            other.clone()
8832        } else {
8833            other.broadcast_to(target)
8834        };
8835        (a, b)
8836    }
8837
8838    /// Append an `IndexAdd` node — the functional inverse of
8839    /// `IndexSelect`. Returns `base` with `src` added at positions given
8840    /// by `indices` along `dim`.
8841    ///
8842    /// # Panics
8843    ///
8844    /// Panics if any operand belongs to a different [`Graph`] than the one this
8845    /// builder is building into. Operand identity is graph-scoped and checked by
8846    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8847    /// deliberate and replaces the hang a cross-graph handle used to produce.
8848    /// Build every operand from one graph, or use a `Result`-returning entry
8849    /// point where one exists.
8850    pub fn index_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8851        assert!(
8852            Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8853            "index_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8854        );
8855        assert_eq!(indices.dtype(), DType::U32, "index_add: index must be U32");
8856        assert_eq!(
8857            self.dtype(),
8858            src.dtype(),
8859            "index_add: base and src dtypes must match"
8860        );
8861        let base_dims = self.shape();
8862        let src_dims = src.shape();
8863        assert_eq!(
8864            base_dims.dims().len(),
8865            src_dims.dims().len(),
8866            "index_add: base and src must have the same rank",
8867        );
8868        assert_eq!(
8869            indices.shape().dims().len(),
8870            1,
8871            "index_add: index must be rank 1",
8872        );
8873        assert_eq!(
8874            src_dims.dims()[dim],
8875            indices.shape().dims()[0],
8876            "index_add: src dim {dim} ({}) must match index length ({})",
8877            src_dims.dims()[dim],
8878            indices.shape().dims()[0],
8879        );
8880        let dtype = self.dtype();
8881        let out_shape = base_dims;
8882        let id = self.graph.write().unwrap().push(Node {
8883            op: Op::IndexAdd { dim },
8884            inputs: vec![self.id, indices.id, src.id],
8885            shape: out_shape,
8886            dtype,
8887        });
8888        Self {
8889            graph: self.graph.clone(),
8890            id,
8891        }
8892    }
8893
8894    /// Append a `ScatterAdd` node — the functional inverse of `Gather`.
8895    /// Returns `base` with values from `src` accumulated at positions
8896    /// given by `indices` (with `indices[p]` substituted at `dim`).
8897    ///
8898    /// # Panics
8899    ///
8900    /// Panics if any operand belongs to a different [`Graph`] than the one this
8901    /// builder is building into. Operand identity is graph-scoped and checked by
8902    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8903    /// deliberate and replaces the hang a cross-graph handle used to produce.
8904    /// Build every operand from one graph, or use a `Result`-returning entry
8905    /// point where one exists.
8906    pub fn scatter_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8907        assert!(
8908            Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8909            "scatter_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8910        );
8911        assert_eq!(
8912            indices.dtype(),
8913            DType::U32,
8914            "scatter_add: index must be U32"
8915        );
8916        assert_eq!(
8917            self.dtype(),
8918            src.dtype(),
8919            "scatter_add: base and src dtypes must match"
8920        );
8921        assert_eq!(
8922            indices.shape().dims(),
8923            src.shape().dims(),
8924            "scatter_add: index and src must have the same shape",
8925        );
8926        let dtype = self.dtype();
8927        let out_shape = self.shape();
8928        let id = self.graph.write().unwrap().push(Node {
8929            op: Op::ScatterAdd { dim },
8930            inputs: vec![self.id, indices.id, src.id],
8931            shape: out_shape,
8932            dtype,
8933        });
8934        Self {
8935            graph: self.graph.clone(),
8936            id,
8937        }
8938    }
8939
8940    // --- internal helpers for the new builders ---
8941
8942    fn scalar_reduction(&self, op: Op) -> NodeHandle {
8943        let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
8944            .expect("scalar_reduction: single input always infers a rank-0 shape");
8945        let id = self.graph.write().unwrap().push(Node {
8946            op,
8947            inputs: vec![self.id],
8948            shape,
8949            dtype,
8950        });
8951        Self {
8952            graph: self.graph.clone(),
8953            id,
8954        }
8955    }
8956
8957    fn axis_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
8958        let in_shape = self.shape();
8959        assert!(
8960            dim < in_shape.dims().len(),
8961            "{name}: dim {dim} out of bounds for shape {:?}",
8962            in_shape.dims(),
8963        );
8964        let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8965            .expect("axis_reduction: dim validated above");
8966        let id = self.graph.write().unwrap().push(Node {
8967            op,
8968            inputs: vec![self.id],
8969            shape,
8970            dtype,
8971        });
8972        Self {
8973            graph: self.graph.clone(),
8974            id,
8975        }
8976    }
8977
8978    // Internal helpers. Both shape-validate and append.
8979
8980    /// Build-time graph-affinity check for a `Result`-returning builder.
8981    ///
8982    /// Node ids index ONE graph's arena, so an operand from a different graph
8983    /// records an id pointing at an unrelated node — a malformed dependency
8984    /// graph whose failure mode is a **realize-time hang**, not a panic or an
8985    /// error. Checking here converts a silent deadlock into a typed build-time
8986    /// error naming both graphs, per "validate at graph-build time".
8987    fn require_same_graph(
8988        &self,
8989        other: &NodeHandle,
8990        op: &str,
8991        role: &str,
8992    ) -> std::result::Result<(), fuel_ir::Error> {
8993        if !Arc::ptr_eq(&self.graph, &other.graph) {
8994            return Err(fuel_ir::Error::Msg(format!(
8995                "{op}: operands must live on the same graph — self is on graph #{}, \
8996                 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8997                 build the other operand with `from_*_on(self.graph(), ..)` or \
8998                 `const_*_like`",
8999                self.graph_id(),
9000                other.graph_id(),
9001            ))
9002            .bt());
9003        }
9004        Ok(())
9005    }
9006
9007    /// Panicking sibling of [`Self::require_same_graph`] for the builders that
9008    /// return `NodeHandle` rather than `Result` — same convention as `matmul`,
9009    /// `qmatmul`, `conv2d` and `paged_attn`. A panic at the build site is far
9010    /// better than the hang it replaces: it names the operand and both graphs.
9011    fn assert_same_graph(&self, other: &NodeHandle, op: &str, role: &str) {
9012        assert!(
9013            Arc::ptr_eq(&self.graph, &other.graph),
9014            "{op}: operands must live on the same graph — self is on graph #{}, \
9015             {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
9016             build the other operand with `from_*_on(self.graph(), ..)` or \
9017             `const_*_like`",
9018            self.graph_id(),
9019            other.graph_id(),
9020        );
9021    }
9022
9023    fn binary_op(
9024        &self,
9025        name: &'static str,
9026        op: Op,
9027        other: &NodeHandle,
9028        out_shape: Shape,
9029    ) -> NodeHandle {
9030        assert!(
9031            Arc::ptr_eq(&self.graph, &other.graph),
9032            "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
9033                 each `from_*` constructor mints a NEW graph, so build the second operand with \
9034                 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
9035            self.graph_id(),
9036            other.graph_id(),
9037        );
9038        assert_eq!(
9039            self.dtype(),
9040            other.dtype(),
9041            "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
9042            self.dtype(),
9043            other.dtype(),
9044        );
9045        assert_eq!(
9046            self.shape().dims(),
9047            other.shape().dims(),
9048            "{name}: shape mismatch: lhs={:?}, rhs={:?}",
9049            self.shape().dims(),
9050            other.shape().dims(),
9051        );
9052        let dtype = self.dtype();
9053        let id = self.graph.write().unwrap().push(Node {
9054            op,
9055            inputs: vec![self.id, other.id],
9056            shape: out_shape,
9057            dtype,
9058        });
9059        Self {
9060            graph: self.graph.clone(),
9061            id,
9062        }
9063    }
9064
9065    /// Result-returning sibling of [`Self::binary_op`]. Validates the
9066    /// graph/dtype/shape preconditions and returns `Err` rather than
9067    /// panicking — the production-correct shape new builders should
9068    /// use. Existing panicking sites are kept for back-compat; new
9069    /// ops should call this directly.
9070    fn try_binary_op(
9071        &self,
9072        name: &'static str,
9073        op: Op,
9074        other: &NodeHandle,
9075        out_shape: Shape,
9076    ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
9077        if !Arc::ptr_eq(&self.graph, &other.graph) {
9078            return Err(fuel_ir::Error::Msg(format!(
9079                "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
9080                 each `from_*` constructor mints a NEW graph, so build the second operand with \
9081                 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
9082            self.graph_id(),
9083            other.graph_id(),
9084            )).bt());
9085        }
9086        if self.dtype() != other.dtype() {
9087            return Err(fuel_ir::Error::Msg(format!(
9088                "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
9089                self.dtype(),
9090                other.dtype(),
9091            ))
9092            .bt());
9093        }
9094        if self.shape().dims() != other.shape().dims() {
9095            return Err(fuel_ir::Error::Msg(format!(
9096                "{name}: shape mismatch: lhs={:?}, rhs={:?}",
9097                self.shape().dims(),
9098                other.shape().dims(),
9099            ))
9100            .bt());
9101        }
9102        let dtype = self.dtype();
9103        let id = self.graph.write().unwrap().push(Node {
9104            op,
9105            inputs: vec![self.id, other.id],
9106            shape: out_shape,
9107            dtype,
9108        });
9109        Ok(Self {
9110            graph: self.graph.clone(),
9111            id,
9112        })
9113    }
9114
9115    fn unary_op(&self, op: Op) -> NodeHandle {
9116        let shape = self.shape();
9117        let dtype = self.dtype();
9118        let id = self.graph.write().unwrap().push(Node {
9119            op,
9120            inputs: vec![self.id],
9121            shape,
9122            dtype,
9123        });
9124        Self {
9125            graph: self.graph.clone(),
9126            id,
9127        }
9128    }
9129
9130    /// Binary builder for ops whose inputs share dtype/shape but whose
9131    /// output is a `U8` mask (`Op::Equal` and the rest of the
9132    /// comparison family). Differs from [`Self::binary_op`] only in the
9133    /// node's output dtype: always `DType::U8` regardless of input
9134    /// dtype.
9135    fn binary_compare_op(&self, name: &'static str, op: Op, other: &NodeHandle) -> NodeHandle {
9136        assert!(
9137            Arc::ptr_eq(&self.graph, &other.graph),
9138            "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
9139                 each `from_*` constructor mints a NEW graph, so build the second operand with \
9140                 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
9141            self.graph_id(),
9142            other.graph_id(),
9143        );
9144        assert_eq!(
9145            self.dtype(),
9146            other.dtype(),
9147            "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
9148            self.dtype(),
9149            other.dtype(),
9150        );
9151        assert_eq!(
9152            self.shape().dims(),
9153            other.shape().dims(),
9154            "{name}: shape mismatch: lhs={:?}, rhs={:?}",
9155            self.shape().dims(),
9156            other.shape().dims(),
9157        );
9158        let shape = self.shape();
9159        let id = self.graph.write().unwrap().push(Node {
9160            op,
9161            inputs: vec![self.id, other.id],
9162            shape,
9163            // GAP-168(c): comparisons yield a `Bool` mask. This BUILDER path is
9164            // the one eq/ne/lt/le/gt/ge take; it must agree with the
9165            // `primitive_shape` comparison arm (fuel-graph/src/shape.rs), which
9166            // is the OTHER site that decides this dtype (reached on re-lowering).
9167            dtype: DType::Bool,
9168        });
9169        Self {
9170            graph: self.graph.clone(),
9171            id,
9172        }
9173    }
9174
9175    /// Build the backward graph from `self`, treating `self` as the output
9176    /// whose gradient drives the rest of the computation.
9177    ///
9178    /// Walks the forward graph in reverse topological order, applies the
9179    /// per-op gradient rule to each node, and emits new graph nodes for
9180    /// the gradient with respect to every node reachable from `self`. The
9181    /// returned [`GradMap`] lets you look up the gradient tensor for any
9182    /// forward tensor from the same graph.
9183    ///
9184    /// The initial upstream gradient is a ones tensor of the same shape
9185    /// and dtype as `self` — the conventional `dL/dL = 1` seed for
9186    /// backprop. For a scalar loss this is `[1.0]`; for a non-scalar
9187    /// output it is "each element of the output contributes with weight 1
9188    /// to the total derivative."
9189    ///
9190    /// ## Supported ops in the MVP
9191    ///
9192    /// `Const`, `Add`, `Mul`, `MatMul`, `Transpose`, `Sqr`, `Exp` all have
9193    /// gradient rules implemented. `Relu` panics — its gradient needs a
9194    /// `Step`/`Where`/`Sign` op that is not yet in the catalog and will
9195    /// land in a follow-up once an indicator-valued op is defined.
9196    ///
9197    /// ## Ownership and the forward graph
9198    ///
9199    /// Backward extends the same graph that held the forward pass. The
9200    /// gradient nodes live alongside the forward nodes in one arena. After
9201    /// `backward()`, realizing a gradient tensor re-executes whatever part
9202    /// of the forward pass the gradient depends on — the executor walks
9203    /// the combined graph as one.
9204    pub fn backward(&self) -> GradMap {
9205        let graph_handle = self.graph.clone();
9206
9207        // C3 pre-pass (Op::Scan Phase 2): lower every reachable Op::Scan to
9208        // primitives + decompose the SSM fused recipes BEFORE the topo order is
9209        // taken, so the reverse walk sees only differentiable primitives. On a
9210        // scan-free graph it is a near-no-op — two topo scans (Pass 1's SSM
9211        // collect + Pass 2's first iteration, which finds no scans and breaks),
9212        // no rewiring. The (possibly remapped) root replaces self.id below.
9213        let root = lower_scans_for_backward(&graph_handle, self.id);
9214
9215        // Compute topological order of reachable nodes, then reverse it
9216        // so we walk from the root (output) toward the leaves (inputs).
9217        let mut order = topo_order(&graph_handle.read().unwrap(), root);
9218        order.reverse();
9219
9220        // Initial upstream gradient for the root: ones tensor of matching
9221        // shape and dtype. For a scalar loss this is [1.0]; for vector
9222        // outputs it seeds each element with weight 1.
9223        let (root_shape, root_dtype) = {
9224            let g = graph_handle.read().unwrap();
9225            let n = g.node(root);
9226            (n.shape.clone(), n.dtype)
9227        };
9228        let ones_id = build_ones(&graph_handle, root_shape, root_dtype);
9229
9230        let mut upstream: HashMap<NodeId, NodeId> = HashMap::new();
9231        upstream.insert(root, ones_id);
9232
9233        for id in order {
9234            let up_id = match upstream.get(&id).copied() {
9235                Some(v) => v,
9236                None => continue, // unreachable from the root, no gradient to propagate
9237            };
9238            // Snapshot the op and its input IDs so we can drop the read
9239            // borrow before taking a mutable borrow to append new nodes.
9240            let (op, inputs) = {
9241                let g = graph_handle.read().unwrap();
9242                let node = g.node(id);
9243                (node.op.clone(), node.inputs.clone())
9244            };
9245
9246            // Symbolic-autograd dispatch (Phase 6d Track 2). If a
9247            // `GradientRule` is registered for this op, use it. Ops
9248            // that haven't migrated yet fall through to the legacy
9249            // inline `match` below.
9250            if let Some(grads) =
9251                crate::grad::dispatch_gradient(&graph_handle, &op, &inputs, id, up_id)
9252            {
9253                debug_assert_eq!(
9254                    grads.len(),
9255                    inputs.len(),
9256                    "GradientRule for {:?} returned {} gradients but op has {} inputs",
9257                    op.short_name(),
9258                    grads.len(),
9259                    inputs.len(),
9260                );
9261                for (input_id, grad) in inputs.iter().zip(grads.iter()) {
9262                    if let Some(g) = grad {
9263                        accumulate_grad(&mut upstream, *input_id, *g, &graph_handle);
9264                    }
9265                }
9266                continue;
9267            }
9268
9269            match op {
9270                Op::Const => {
9271                    // Leaf. The upstream value has already been stored and
9272                    // is what `GradMap::get` will return for this input.
9273                }
9274                Op::Iota { .. } => {
9275                    // Leaf, non-differentiable: a constant position
9276                    // generator with no inputs — no gradient to propagate.
9277                }
9278                Op::NonZeroIndices { .. } => {
9279                    // Produces discrete indices + a runtime count; both
9280                    // are integer/non-differentiable. No gradient flows to
9281                    // the input. (A differentiated graph that reaches this
9282                    // op surfaces as a usage error in the grad-emitting
9283                    // pass, matching the ArgMaxDim/ArgMinDim precedent.)
9284                }
9285                Op::Add => {
9286                    // d(a + b)/da = 1, d(a + b)/db = 1.
9287                    // Upstream flows unchanged into both inputs.
9288                    accumulate_grad(&mut upstream, inputs[0], up_id, &graph_handle);
9289                    accumulate_grad(&mut upstream, inputs[1], up_id, &graph_handle);
9290                }
9291                Op::Mul => {
9292                    // d(a * b)/da = b, d(a * b)/db = a.
9293                    // Upstream * b goes to a; upstream * a goes to b.
9294                    let a = inputs[0];
9295                    let b = inputs[1];
9296                    let a_shape = node_shape(&graph_handle, a);
9297                    let b_shape = node_shape(&graph_handle, b);
9298                    let dtype = node_dtype(&graph_handle, a);
9299                    let grad_a = push_node(&graph_handle, Op::Mul, vec![up_id, b], a_shape, dtype);
9300                    let grad_b = push_node(&graph_handle, Op::Mul, vec![up_id, a], b_shape, dtype);
9301                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9302                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9303                }
9304                Op::MatMul => {
9305                    // Forward: Y = A @ B,  A: [m, k], B: [k, n], Y: [m, n]
9306                    // Backward: dA = dY @ B^T,  dB = A^T @ dY.
9307                    let a = inputs[0];
9308                    let b = inputs[1];
9309                    let a_shape = node_shape(&graph_handle, a);
9310                    let b_shape = node_shape(&graph_handle, b);
9311                    let dtype = node_dtype(&graph_handle, a);
9312                    // B^T: shape [n, k]
9313                    let b_t_shape = transposed_shape(&b_shape);
9314                    let b_t = push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
9315                    // dA = upstream @ B^T, shape [m, k] = a_shape
9316                    let grad_a = push_node(
9317                        &graph_handle,
9318                        Op::MatMul,
9319                        vec![up_id, b_t],
9320                        a_shape.clone(),
9321                        dtype,
9322                    );
9323                    // A^T: shape [k, m]
9324                    let a_t_shape = transposed_shape(&a_shape);
9325                    let a_t = push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
9326                    // dB = A^T @ upstream, shape [k, n] = b_shape
9327                    let grad_b =
9328                        push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
9329                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9330                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9331                }
9332                Op::Transpose => {
9333                    // d(x^T)/dx is a transpose on the way back.
9334                    let x = inputs[0];
9335                    let x_shape = node_shape(&graph_handle, x);
9336                    let dtype = node_dtype(&graph_handle, x);
9337                    let grad_x =
9338                        push_node(&graph_handle, Op::Transpose, vec![up_id], x_shape, dtype);
9339                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9340                }
9341                Op::Permute(ref axes) => {
9342                    // Backward: apply the inverse permutation to upstream.
9343                    // If forward permutes with `axes` (out[i] = in[axes[i]]),
9344                    // the inverse `inv` satisfies `inv[axes[i]] = i`.
9345                    let x = inputs[0];
9346                    let x_shape = node_shape(&graph_handle, x);
9347                    let dtype = node_dtype(&graph_handle, x);
9348                    let mut inv = vec![0_usize; axes.len()];
9349                    for (i, &ax) in axes.iter().enumerate() {
9350                        inv[ax] = i;
9351                    }
9352                    let grad_x =
9353                        push_node(&graph_handle, Op::Permute(inv), vec![up_id], x_shape, dtype);
9354                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9355                }
9356                Op::Sqr => {
9357                    // d(x^2)/dx = 2x. Expressed as `x + x` to avoid
9358                    // needing a scalar constant broadcast — both sums
9359                    // have the same shape as x, the existing Add op
9360                    // handles them natively.
9361                    let x = inputs[0];
9362                    let x_shape = node_shape(&graph_handle, x);
9363                    let dtype = node_dtype(&graph_handle, x);
9364                    let two_x =
9365                        push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
9366                    let grad_x =
9367                        push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
9368                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9369                }
9370                Op::Exp => {
9371                    // d(e^x)/dx = e^x, which is the forward output — i.e.
9372                    // this node `id`. Reuse it directly instead of
9373                    // recomputing.
9374                    let x = inputs[0];
9375                    let out_shape = node_shape(&graph_handle, id);
9376                    let dtype = node_dtype(&graph_handle, id);
9377                    let grad_x =
9378                        push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
9379                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9380                }
9381                Op::Sub => {
9382                    // d(a - b)/da = 1, d(a - b)/db = -1.
9383                    let a = inputs[0];
9384                    let b = inputs[1];
9385                    accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9386                    let b_shape = node_shape(&graph_handle, b);
9387                    let dtype = node_dtype(&graph_handle, b);
9388                    let neg_up = push_node(&graph_handle, Op::Neg, vec![up_id], b_shape, dtype);
9389                    accumulate_grad(&mut upstream, b, neg_up, &graph_handle);
9390                }
9391                Op::Div => {
9392                    // y = a / b
9393                    // dy/da = 1/b     →  grad_a = upstream / b
9394                    // dy/db = -a/b²   →  grad_b = -(upstream * a / (b*b))
9395                    let a = inputs[0];
9396                    let b = inputs[1];
9397                    let a_shape = node_shape(&graph_handle, a);
9398                    let b_shape = node_shape(&graph_handle, b);
9399                    let dtype = node_dtype(&graph_handle, a);
9400                    // grad_a
9401                    let grad_a = push_node(
9402                        &graph_handle,
9403                        Op::Div,
9404                        vec![up_id, b],
9405                        a_shape.clone(),
9406                        dtype,
9407                    );
9408                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9409                    // grad_b: -(upstream * a / (b*b))
9410                    let b_sq = push_node(&graph_handle, Op::Sqr, vec![b], b_shape.clone(), dtype);
9411                    let up_times_a =
9412                        push_node(&graph_handle, Op::Mul, vec![up_id, a], a_shape, dtype);
9413                    let quotient = push_node(
9414                        &graph_handle,
9415                        Op::Div,
9416                        vec![up_times_a, b_sq],
9417                        b_shape.clone(),
9418                        dtype,
9419                    );
9420                    let grad_b = push_node(&graph_handle, Op::Neg, vec![quotient], b_shape, dtype);
9421                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9422                }
9423                Op::Neg => {
9424                    // d(-x)/dx = -1. grad_x = -upstream.
9425                    let x = inputs[0];
9426                    let x_shape = node_shape(&graph_handle, x);
9427                    let dtype = node_dtype(&graph_handle, x);
9428                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
9429                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9430                }
9431                Op::Sqrt => {
9432                    // y = sqrt(x), dy/dx = 1/(2*sqrt(x)) = 1/(2y).
9433                    // grad_x = upstream / (y + y). Reuse the forward node.
9434                    let x = inputs[0];
9435                    let x_shape = node_shape(&graph_handle, x);
9436                    let dtype = node_dtype(&graph_handle, x);
9437                    let two_y =
9438                        push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
9439                    let grad_x =
9440                        push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
9441                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9442                }
9443                Op::Log => {
9444                    // d(ln(x))/dx = 1/x. grad_x = upstream / x.
9445                    let x = inputs[0];
9446                    let x_shape = node_shape(&graph_handle, x);
9447                    let dtype = node_dtype(&graph_handle, x);
9448                    let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
9449                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9450                }
9451                Op::Sin => {
9452                    // d(sin(x))/dx = cos(x). grad_x = upstream * cos(x).
9453                    let x = inputs[0];
9454                    let x_shape = node_shape(&graph_handle, x);
9455                    let dtype = node_dtype(&graph_handle, x);
9456                    let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
9457                    let grad_x =
9458                        push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
9459                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9460                }
9461                Op::Cos => {
9462                    // d(cos(x))/dx = -sin(x). grad_x = -(upstream * sin(x)).
9463                    let x = inputs[0];
9464                    let x_shape = node_shape(&graph_handle, x);
9465                    let dtype = node_dtype(&graph_handle, x);
9466                    let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
9467                    let up_sin = push_node(
9468                        &graph_handle,
9469                        Op::Mul,
9470                        vec![up_id, sin_x],
9471                        x_shape.clone(),
9472                        dtype,
9473                    );
9474                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
9475                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9476                }
9477                Op::Tanh => {
9478                    // y = tanh(x), dy/dx = 1 - y². grad_x = upstream * (1 - y*y).
9479                    // Build: ones_of_y_shape - y*y, then multiply by upstream.
9480                    let x = inputs[0];
9481                    let y_shape = node_shape(&graph_handle, id);
9482                    let dtype = node_dtype(&graph_handle, id);
9483                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
9484                    let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9485                    let one_minus_sq = push_node(
9486                        &graph_handle,
9487                        Op::Sub,
9488                        vec![ones, y_sq],
9489                        y_shape.clone(),
9490                        dtype,
9491                    );
9492                    let grad_x = push_node(
9493                        &graph_handle,
9494                        Op::Mul,
9495                        vec![up_id, one_minus_sq],
9496                        y_shape,
9497                        dtype,
9498                    );
9499                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9500                }
9501                Op::Sigmoid => {
9502                    // y = sigmoid(x), dy/dx = y * (1 - y).
9503                    // grad_x = upstream * y * (1 - y).
9504                    let x = inputs[0];
9505                    let y_shape = node_shape(&graph_handle, id);
9506                    let dtype = node_dtype(&graph_handle, id);
9507                    let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9508                    let one_minus_y = push_node(
9509                        &graph_handle,
9510                        Op::Sub,
9511                        vec![ones, id],
9512                        y_shape.clone(),
9513                        dtype,
9514                    );
9515                    let y_times_1my = push_node(
9516                        &graph_handle,
9517                        Op::Mul,
9518                        vec![id, one_minus_y],
9519                        y_shape.clone(),
9520                        dtype,
9521                    );
9522                    let grad_x = push_node(
9523                        &graph_handle,
9524                        Op::Mul,
9525                        vec![up_id, y_times_1my],
9526                        y_shape,
9527                        dtype,
9528                    );
9529                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9530                }
9531                Op::Silu => {
9532                    // y = x * sigmoid(x)
9533                    // dy/dx = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
9534                    //       = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
9535                    //
9536                    // Simpler: let s = sigmoid(x). dy/dx = s + y * (1 - s),
9537                    // where y = x * s is the forward output (this node).
9538                    // grad_x = upstream * (s + y * (1 - s)).
9539                    let x = inputs[0];
9540                    let x_shape = node_shape(&graph_handle, x);
9541                    let dtype = node_dtype(&graph_handle, x);
9542                    let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
9543                    let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
9544                    let one_minus_s = push_node(
9545                        &graph_handle,
9546                        Op::Sub,
9547                        vec![ones, s],
9548                        x_shape.clone(),
9549                        dtype,
9550                    );
9551                    let y_times_1ms = push_node(
9552                        &graph_handle,
9553                        Op::Mul,
9554                        vec![id, one_minus_s],
9555                        x_shape.clone(),
9556                        dtype,
9557                    );
9558                    let inner = push_node(
9559                        &graph_handle,
9560                        Op::Add,
9561                        vec![s, y_times_1ms],
9562                        x_shape.clone(),
9563                        dtype,
9564                    );
9565                    let grad_x =
9566                        push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
9567                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9568                }
9569                Op::GeluTanh => {
9570                    let x = inputs[0];
9571                    let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
9572                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9573                }
9574                Op::Relu => {
9575                    // d(relu(x))/dx = step(x). grad_x = upstream * step(x).
9576                    let x = inputs[0];
9577                    let x_shape = node_shape(&graph_handle, x);
9578                    let dtype = node_dtype(&graph_handle, x);
9579                    let step_x =
9580                        push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
9581                    let grad_x =
9582                        push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
9583                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9584                }
9585                Op::Step => {
9586                    // d(step(x))/dx is 0 almost everywhere (and a Dirac
9587                    // delta at 0 which has no finite representation). The
9588                    // standard move is to treat the derivative as 0 and
9589                    // stop propagation — Step's backward is silently a
9590                    // no-op. Callers that need a smooth surrogate should
9591                    // use Sigmoid or Tanh instead.
9592                }
9593                Op::Recip => {
9594                    // y = 1/x, dy/dx = -1/x² = -y².
9595                    // grad_x = -upstream * y * y. Reuse forward output (id)
9596                    // so we don't recompute the reciprocal.
9597                    let x = inputs[0];
9598                    let x_shape = node_shape(&graph_handle, x);
9599                    let dtype = node_dtype(&graph_handle, x);
9600                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9601                    let up_y_sq = push_node(
9602                        &graph_handle,
9603                        Op::Mul,
9604                        vec![up_id, y_sq],
9605                        x_shape.clone(),
9606                        dtype,
9607                    );
9608                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
9609                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9610                }
9611                Op::Abs => {
9612                    // y = |x|, dy/dx = sign(x), with sign(0)=0 by
9613                    // subgradient convention. Simplified to a direct
9614                    // `Op::Sign` use after Op::Sign landed in PR B2;
9615                    // the previous form synthesized `step(x) - step(-x)`
9616                    // (5 backward nodes) but Sign expresses the same
9617                    // function in 1 node, so the chain shrinks to
9618                    // `Mul(upstream, Sign(x))` — 2 nodes total.
9619                    let x = inputs[0];
9620                    let x_shape = node_shape(&graph_handle, x);
9621                    let dtype = node_dtype(&graph_handle, x);
9622                    let sign_x =
9623                        push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
9624                    let grad_x =
9625                        push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
9626                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9627                }
9628                Op::Where => {
9629                    // Handled by `WhereRule` via `dispatch_gradient`;
9630                    // this arm only exists for exhaustiveness.
9631                }
9632                Op::Floor | Op::Ceil | Op::Round | Op::Sign => {
9633                    // d(floor(x))/dx, d(ceil(x))/dx, d(round(x))/dx,
9634                    // d(sign(x))/dx are all 0 almost everywhere (with
9635                    // a Dirac train at integer / half-integer / zero
9636                    // that has no finite representation). Treat the
9637                    // derivative as 0 and stop propagation — mirrors
9638                    // `Op::Step`'s backward.
9639                }
9640                Op::Erf => {
9641                    // y = erf(x). dy/dx = (2/√π) * exp(-x²).
9642                    // grad_x = upstream * (2/√π) * exp(-x²).
9643                    // Decomposes to: Sqr(x) → Neg → Exp → MulScalar(2/√π)
9644                    //                → Mul(upstream, .).
9645                    // 2/√π = 1.1283791670955125738961589031...
9646                    const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
9647                    let x = inputs[0];
9648                    let x_shape = node_shape(&graph_handle, x);
9649                    let dtype = node_dtype(&graph_handle, x);
9650                    let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9651                    let neg_x_sq =
9652                        push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
9653                    let exp_neg_x_sq = push_node(
9654                        &graph_handle,
9655                        Op::Exp,
9656                        vec![neg_x_sq],
9657                        x_shape.clone(),
9658                        dtype,
9659                    );
9660                    let scaled = push_node(
9661                        &graph_handle,
9662                        Op::MulScalar(TWO_OVER_SQRT_PI),
9663                        vec![exp_neg_x_sq],
9664                        x_shape.clone(),
9665                        dtype,
9666                    );
9667                    let grad_x =
9668                        push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9669                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9670                }
9671                Op::Flip { dim } => {
9672                    // y = flip(x, dim). Backward is another Flip on
9673                    // the same dim — Flip is its own inverse
9674                    // (involutive). One backward node, exact gradient.
9675                    let x = inputs[0];
9676                    let x_shape = node_shape(&graph_handle, x);
9677                    let dtype = node_dtype(&graph_handle, x);
9678                    let grad_x =
9679                        push_node(&graph_handle, Op::Flip { dim }, vec![up_id], x_shape, dtype);
9680                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9681                }
9682                Op::Pad {
9683                    padding,
9684                    mode,
9685                    value: _,
9686                } => {
9687                    // Backward delegates to Op::PadBackward — a single
9688                    // node that handles all three modes uniformly via
9689                    // its kernel. Constant: slice the unpadded region.
9690                    // Reflect/Replicate: accumulate gradient at the
9691                    // mirrored / replicated positions.
9692                    let padding = padding.clone();
9693                    let x = inputs[0];
9694                    let x_shape = node_shape(&graph_handle, x);
9695                    let dtype = node_dtype(&graph_handle, x);
9696                    let grad_x = push_node(
9697                        &graph_handle,
9698                        Op::PadBackward {
9699                            in_shape: x_shape.clone(),
9700                            padding,
9701                            mode,
9702                        },
9703                        vec![up_id],
9704                        x_shape,
9705                        dtype,
9706                    );
9707                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9708                }
9709                Op::PadBackward { .. } => {
9710                    // Backward helper — typically a leaf in autograd
9711                    // (the upstream gradient itself never gets a
9712                    // higher-order backward in v1). No-op arm for
9713                    // exhaustiveness; if higher-order autograd needs
9714                    // PadBackward's backward, that's its own scope.
9715                }
9716                Op::CumSum { dim } => {
9717                    // y[..., i, ...] = sum_{k=0..=i} x[..., k, ...]
9718                    // dL/dx[..., i, ...] = sum_{k=i..n} dL/dy[..., k, ...]
9719                    // i.e. reverse cumsum. Express via Flip → CumSum → Flip.
9720                    let x = inputs[0];
9721                    let x_shape = node_shape(&graph_handle, x);
9722                    let dtype = node_dtype(&graph_handle, x);
9723                    let flip1 = push_node(
9724                        &graph_handle,
9725                        Op::Flip { dim },
9726                        vec![up_id],
9727                        x_shape.clone(),
9728                        dtype,
9729                    );
9730                    let cs = push_node(
9731                        &graph_handle,
9732                        Op::CumSum { dim },
9733                        vec![flip1],
9734                        x_shape.clone(),
9735                        dtype,
9736                    );
9737                    let grad_x =
9738                        push_node(&graph_handle, Op::Flip { dim }, vec![cs], x_shape, dtype);
9739                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9740                }
9741                Op::Roll { dim, shift } => {
9742                    // y = roll(x, dim, shift). Backward is the opposite
9743                    // shift along the same dim. One backward node.
9744                    let x = inputs[0];
9745                    let x_shape = node_shape(&graph_handle, x);
9746                    let dtype = node_dtype(&graph_handle, x);
9747                    let grad_x = push_node(
9748                        &graph_handle,
9749                        Op::Roll { dim, shift: -shift },
9750                        vec![up_id],
9751                        x_shape,
9752                        dtype,
9753                    );
9754                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9755                }
9756                Op::Triu { diagonal } => {
9757                    // y = triu(x, diagonal). Mask is a binary indicator
9758                    // — gradient passes through kept positions and is
9759                    // zero on the masked half. Same op on the upstream.
9760                    let x = inputs[0];
9761                    let x_shape = node_shape(&graph_handle, x);
9762                    let dtype = node_dtype(&graph_handle, x);
9763                    let grad_x = push_node(
9764                        &graph_handle,
9765                        Op::Triu { diagonal },
9766                        vec![up_id],
9767                        x_shape,
9768                        dtype,
9769                    );
9770                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9771                }
9772                Op::Tril { diagonal } => {
9773                    // Mirror of Op::Triu — same mask gradient.
9774                    let x = inputs[0];
9775                    let x_shape = node_shape(&graph_handle, x);
9776                    let dtype = node_dtype(&graph_handle, x);
9777                    let grad_x = push_node(
9778                        &graph_handle,
9779                        Op::Tril { diagonal },
9780                        vec![up_id],
9781                        x_shape,
9782                        dtype,
9783                    );
9784                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9785                }
9786                Op::LogSoftmaxLastDim => {
9787                    // grad_x = upstream - exp(y) * sum(upstream, last_dim, keepdim).
9788                    // Folded into Op::LogSoftmaxLastDimBackward — takes
9789                    // (forward_output, upstream), avoids re-evaluating
9790                    // the softmax outside the kernel.
9791                    let x = inputs[0];
9792                    let x_shape = node_shape(&graph_handle, x);
9793                    let dtype = node_dtype(&graph_handle, x);
9794                    let grad_x = push_node(
9795                        &graph_handle,
9796                        Op::LogSoftmaxLastDimBackward,
9797                        vec![id, up_id],
9798                        x_shape,
9799                        dtype,
9800                    );
9801                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9802                }
9803                Op::LogSoftmaxLastDimBackward => {
9804                    // Backward helper — no higher-order autograd in v1.
9805                }
9806                Op::MaskedFill { value: _ } => {
9807                    // y = mask ? value : x. dy/dx = (mask == 0).
9808                    // grad_x = MaskedFill(upstream, mask, value=0_of_dtype).
9809                    // The mask is integer-only; no gradient flows to it.
9810                    let x = inputs[0];
9811                    let mask = inputs[1];
9812                    let x_shape = node_shape(&graph_handle, x);
9813                    let dtype = node_dtype(&graph_handle, x);
9814                    let zero = match fuel_ir::Scalar::zero(dtype) {
9815                        Ok(z) => z,
9816                        Err(_) => {
9817                            // A packed/scale dtype has no zero scalar. MaskedFill
9818                            // on such a dtype is a build-time bug (a future D5
9819                            // graph-build guard forbids it), so this is
9820                            // unreachable in a well-formed graph. debug_assert
9821                            // catches it in debug; release skips this gradient
9822                            // rather than panicking (never-panic invariant).
9823                            debug_assert!(false, "MaskedFill backward on non-real dtype {dtype:?}");
9824                            continue;
9825                        }
9826                    };
9827                    let grad_x = push_node(
9828                        &graph_handle,
9829                        Op::MaskedFill { value: zero },
9830                        vec![up_id, mask],
9831                        x_shape,
9832                        dtype,
9833                    );
9834                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9835                    // No gradient to mask: it's discrete.
9836                }
9837                Op::Rem => {
9838                    // y = a - floor(a/b) * b (PyTorch convention).
9839                    // d/da = 1 (the floor term is treated as a constant
9840                    //          w.r.t. a almost everywhere; the actual
9841                    //          derivative has a Dirac component at
9842                    //          integer a/b ratios that we drop, matching
9843                    //          PyTorch's autograd convention).
9844                    // d/db = -floor(a/b)
9845                    // grad_a = upstream
9846                    // grad_b = upstream * (-floor(a/b))
9847                    let a = inputs[0];
9848                    let b = inputs[1];
9849                    let a_shape = node_shape(&graph_handle, a);
9850                    let dtype = node_dtype(&graph_handle, a);
9851                    accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9852                    let div_ab =
9853                        push_node(&graph_handle, Op::Div, vec![a, b], a_shape.clone(), dtype);
9854                    let floor_div = push_node(
9855                        &graph_handle,
9856                        Op::Floor,
9857                        vec![div_ab],
9858                        a_shape.clone(),
9859                        dtype,
9860                    );
9861                    let neg_floor = push_node(
9862                        &graph_handle,
9863                        Op::Neg,
9864                        vec![floor_div],
9865                        a_shape.clone(),
9866                        dtype,
9867                    );
9868                    let grad_b = push_node(
9869                        &graph_handle,
9870                        Op::Mul,
9871                        vec![up_id, neg_floor],
9872                        a_shape,
9873                        dtype,
9874                    );
9875                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9876                }
9877                Op::Rsqrt => {
9878                    // y = x^(-1/2). dy/dx = -0.5 * x^(-3/2).
9879                    // Identity: y² = 1/x, so x^(-3/2) = y/x = y * y² = y³.
9880                    // grad_x = -0.5 * upstream * y³.
9881                    // Reuses the forward output id for y; never touches
9882                    // x directly (avoids the divide-by-zero singularity
9883                    // that the obvious `-0.5 * upstream * y / x` form
9884                    // would have).
9885                    let x = inputs[0];
9886                    let x_shape = node_shape(&graph_handle, x);
9887                    let dtype = node_dtype(&graph_handle, x);
9888                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9889                    let y_cu = push_node(
9890                        &graph_handle,
9891                        Op::Mul,
9892                        vec![id, y_sq],
9893                        x_shape.clone(),
9894                        dtype,
9895                    );
9896                    let scaled = push_node(
9897                        &graph_handle,
9898                        Op::MulScalar(-0.5),
9899                        vec![y_cu],
9900                        x_shape.clone(),
9901                        dtype,
9902                    );
9903                    let grad_x =
9904                        push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9905                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9906                }
9907                Op::Pow => {
9908                    // y = pow(a, b).
9909                    // d/da = b * pow(a, b-1)
9910                    // d/db = y * ln(a)
9911                    // grad_a = upstream * b * pow(a, b-1)
9912                    // grad_b = upstream * y * ln(a)
9913                    // The forward output `id` IS y; we reuse it.
9914                    let a = inputs[0];
9915                    let b = inputs[1];
9916                    let a_shape = node_shape(&graph_handle, a);
9917                    let dtype = node_dtype(&graph_handle, a);
9918                    // d/da branch: pow(a, b - 1)
9919                    let b_minus_one = push_node(
9920                        &graph_handle,
9921                        Op::AddScalar(-1.0),
9922                        vec![b],
9923                        a_shape.clone(),
9924                        dtype,
9925                    );
9926                    let pow_a_bm1 = push_node(
9927                        &graph_handle,
9928                        Op::Pow,
9929                        vec![a, b_minus_one],
9930                        a_shape.clone(),
9931                        dtype,
9932                    );
9933                    let b_times_pow = push_node(
9934                        &graph_handle,
9935                        Op::Mul,
9936                        vec![b, pow_a_bm1],
9937                        a_shape.clone(),
9938                        dtype,
9939                    );
9940                    let grad_a = push_node(
9941                        &graph_handle,
9942                        Op::Mul,
9943                        vec![up_id, b_times_pow],
9944                        a_shape.clone(),
9945                        dtype,
9946                    );
9947                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9948                    // d/db branch: y * ln(a)
9949                    let log_a = push_node(&graph_handle, Op::Log, vec![a], a_shape.clone(), dtype);
9950                    let y_log_a = push_node(
9951                        &graph_handle,
9952                        Op::Mul,
9953                        vec![id, log_a],
9954                        a_shape.clone(),
9955                        dtype,
9956                    );
9957                    let grad_b =
9958                        push_node(&graph_handle, Op::Mul, vec![up_id, y_log_a], a_shape, dtype);
9959                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9960                }
9961                Op::Gelu => {
9962                    // y = 0.5 * x * (1 + erf(x/√2)).
9963                    // dy/dx = Φ(x) + x · φ(x)
9964                    //       = 0.5 * (1 + erf(x/√2))
9965                    //       + x * (1/√(2π)) * exp(-x²/2)
9966                    // where Φ is the standard-normal CDF (= y/x for x≠0;
9967                    // we recompute it explicitly so the backward stays
9968                    // safe at x=0) and φ is the PDF.
9969                    //
9970                    // Chain (12 nodes):
9971                    //   x_over_sqrt2 = MulScalar(1/√2)(x)
9972                    //   erf_arg      = Erf(x_over_sqrt2)
9973                    //   plus_one     = AddScalar(1.0)(erf_arg)
9974                    //   cdf_term     = MulScalar(0.5)(plus_one)
9975                    //   x_sq         = Sqr(x)
9976                    //   half_x_sq    = MulScalar(0.5)(x_sq)
9977                    //   neg_half_x_sq= Neg(half_x_sq)
9978                    //   exp_term     = Exp(neg_half_x_sq)
9979                    //   phi          = MulScalar(1/√(2π))(exp_term)
9980                    //   pdf_term     = Mul(x, phi)
9981                    //   d_gelu       = Add(cdf_term, pdf_term)
9982                    //   grad_x       = Mul(upstream, d_gelu)
9983                    const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
9984                    // 1/√(2π) = 0.39894228040143267793994605993...
9985                    const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
9986                    let x = inputs[0];
9987                    let x_shape = node_shape(&graph_handle, x);
9988                    let dtype = node_dtype(&graph_handle, x);
9989                    // CDF half: 0.5 * (1 + erf(x/√2)).
9990                    let x_over_sqrt2 = push_node(
9991                        &graph_handle,
9992                        Op::MulScalar(INV_SQRT_2),
9993                        vec![x],
9994                        x_shape.clone(),
9995                        dtype,
9996                    );
9997                    let erf_arg = push_node(
9998                        &graph_handle,
9999                        Op::Erf,
10000                        vec![x_over_sqrt2],
10001                        x_shape.clone(),
10002                        dtype,
10003                    );
10004                    let plus_one = push_node(
10005                        &graph_handle,
10006                        Op::AddScalar(1.0),
10007                        vec![erf_arg],
10008                        x_shape.clone(),
10009                        dtype,
10010                    );
10011                    let cdf_term = push_node(
10012                        &graph_handle,
10013                        Op::MulScalar(0.5),
10014                        vec![plus_one],
10015                        x_shape.clone(),
10016                        dtype,
10017                    );
10018                    // PDF half: x * (1/√(2π)) * exp(-x²/2).
10019                    let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
10020                    let half_x_sq = push_node(
10021                        &graph_handle,
10022                        Op::MulScalar(0.5),
10023                        vec![x_sq],
10024                        x_shape.clone(),
10025                        dtype,
10026                    );
10027                    let neg_half_x_sq = push_node(
10028                        &graph_handle,
10029                        Op::Neg,
10030                        vec![half_x_sq],
10031                        x_shape.clone(),
10032                        dtype,
10033                    );
10034                    let exp_term = push_node(
10035                        &graph_handle,
10036                        Op::Exp,
10037                        vec![neg_half_x_sq],
10038                        x_shape.clone(),
10039                        dtype,
10040                    );
10041                    let phi = push_node(
10042                        &graph_handle,
10043                        Op::MulScalar(INV_SQRT_2PI),
10044                        vec![exp_term],
10045                        x_shape.clone(),
10046                        dtype,
10047                    );
10048                    let pdf_term =
10049                        push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
10050                    // Sum the two halves and apply upstream.
10051                    let d_gelu = push_node(
10052                        &graph_handle,
10053                        Op::Add,
10054                        vec![cdf_term, pdf_term],
10055                        x_shape.clone(),
10056                        dtype,
10057                    );
10058                    let grad_x =
10059                        push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
10060                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10061                }
10062                Op::Equal | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => {
10063                    // Comparison family: handled by `NoGradientBinaryRule`
10064                    // via `dispatch_gradient`. The `if let Some(grads) =
10065                    // dispatch_gradient(...) { continue; }` block above
10066                    // intercepts before we get here. This arm exists only
10067                    // for exhaustiveness; it should be unreachable in
10068                    // practice. Keeping it as a no-op rather than
10069                    // `unreachable!()` defends against a future hand-edit
10070                    // that removes the dispatcher arm by mistake — the
10071                    // graph still terminates traversal cleanly.
10072                }
10073                Op::Cast(_) => {
10074                    // Forward: y = cast(x, target_dtype).
10075                    // Backward: dL/dx = cast(upstream, source_dtype).
10076                    let x = inputs[0];
10077                    let x_dtype = node_dtype(&graph_handle, x);
10078                    let x_shape = node_shape(&graph_handle, x);
10079                    let grad_x = push_node(
10080                        &graph_handle,
10081                        Op::Cast(x_dtype),
10082                        vec![up_id],
10083                        x_shape,
10084                        x_dtype,
10085                    );
10086                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10087                }
10088                Op::SumAll => {
10089                    // Forward: y = sum(x), scalar.
10090                    // Backward: dL/dx = broadcast_to(upstream, x.shape).
10091                    let x = inputs[0];
10092                    let x_shape = node_shape(&graph_handle, x);
10093                    let dtype = node_dtype(&graph_handle, x);
10094                    let grad_x = push_node(
10095                        &graph_handle,
10096                        Op::BroadcastTo(x_shape.clone()),
10097                        vec![up_id],
10098                        x_shape,
10099                        dtype,
10100                    );
10101                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10102                }
10103                Op::MeanAll => {
10104                    // Forward: y = mean(x) = sum(x) / n, scalar.
10105                    // Backward: dL/dx = broadcast_to(upstream / n, x.shape).
10106                    // We build `ones / n` as a constant of shape x.shape
10107                    // and multiply by broadcast_to(upstream, x.shape).
10108                    // Simpler: broadcast upstream, then divide by an n-const.
10109                    let x = inputs[0];
10110                    let x_shape = node_shape(&graph_handle, x);
10111                    let dtype = node_dtype(&graph_handle, x);
10112                    let n_elem = x_shape.elem_count();
10113                    let broadcast_up = push_node(
10114                        &graph_handle,
10115                        Op::BroadcastTo(x_shape.clone()),
10116                        vec![up_id],
10117                        x_shape.clone(),
10118                        dtype,
10119                    );
10120                    let n_const =
10121                        build_filled_const(&graph_handle, x_shape.clone(), dtype, n_elem as f64);
10122                    let grad_x = push_node(
10123                        &graph_handle,
10124                        Op::Div,
10125                        vec![broadcast_up, n_const],
10126                        x_shape,
10127                        dtype,
10128                    );
10129                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10130                }
10131                Op::BroadcastTo(_) => {
10132                    // Forward: y = broadcast_to(x, target).
10133                    // Backward: dL/dx = reduce_sum_to(upstream, x.shape) —
10134                    // sum away every dim that was expanded or newly added.
10135                    let x = inputs[0];
10136                    let x_shape = node_shape(&graph_handle, x);
10137                    let dtype = node_dtype(&graph_handle, x);
10138                    let grad_x = push_node(
10139                        &graph_handle,
10140                        Op::ReduceSumTo(x_shape.clone()),
10141                        vec![up_id],
10142                        x_shape,
10143                        dtype,
10144                    );
10145                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10146                }
10147                Op::Reshape(_) => {
10148                    // Forward: y = reshape(x, target). Data unchanged.
10149                    // Backward: reshape upstream back to x.shape.
10150                    let x = inputs[0];
10151                    let x_shape = node_shape(&graph_handle, x);
10152                    let dtype = node_dtype(&graph_handle, x);
10153                    let grad_x = push_node(
10154                        &graph_handle,
10155                        Op::Reshape(x_shape.clone()),
10156                        vec![up_id],
10157                        x_shape,
10158                        dtype,
10159                    );
10160                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10161                }
10162                Op::Contiguize => {
10163                    // Forward: y = contiguize(x). Identity at the
10164                    // value level; only the layout differs. Backward:
10165                    // pass upstream through unchanged. The
10166                    // downstream `accumulate_grad` will sum this
10167                    // into x's gradient regardless of x's own layout.
10168                    let x = inputs[0];
10169                    accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10170                }
10171                Op::Unsqueeze { dim: _ } => {
10172                    // Forward: y = unsqueeze(x, dim) — inserts a size-1
10173                    // axis without touching bytes. Backward: drop that
10174                    // axis. Bytes are unchanged either direction; a
10175                    // Reshape to x.shape is the simplest expression of
10176                    // "same bytes, different rank" that the executor
10177                    // handles natively.
10178                    let x = inputs[0];
10179                    let x_shape = node_shape(&graph_handle, x);
10180                    let dtype = node_dtype(&graph_handle, x);
10181                    let grad_x = push_node(
10182                        &graph_handle,
10183                        Op::Reshape(x_shape.clone()),
10184                        vec![up_id],
10185                        x_shape,
10186                        dtype,
10187                    );
10188                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10189                }
10190                Op::Squeeze { dim } => {
10191                    // Forward: y = squeeze(x, dim) — drops a size-1 axis,
10192                    // metadata-only. Backward: re-insert the axis at the
10193                    // same position via Unsqueeze. Both directions are
10194                    // metadata-only views (no bytes touched).
10195                    let x = inputs[0];
10196                    let x_shape = node_shape(&graph_handle, x);
10197                    let dtype = node_dtype(&graph_handle, x);
10198                    let grad_x = push_node(
10199                        &graph_handle,
10200                        Op::Unsqueeze { dim },
10201                        vec![up_id],
10202                        x_shape,
10203                        dtype,
10204                    );
10205                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10206                }
10207                Op::ReduceSumTo(_) => {
10208                    // Forward: y = reduce_sum_to(x, target).
10209                    // Backward: broadcast upstream back to x.shape.
10210                    let x = inputs[0];
10211                    let x_shape = node_shape(&graph_handle, x);
10212                    let dtype = node_dtype(&graph_handle, x);
10213                    let grad_x = push_node(
10214                        &graph_handle,
10215                        Op::BroadcastTo(x_shape.clone()),
10216                        vec![up_id],
10217                        x_shape,
10218                        dtype,
10219                    );
10220                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10221                }
10222                Op::MaxAll | Op::MinAll => {
10223                    // For y = max(x) (or min), the gradient is an
10224                    // indicator at the argmax positions, distributed
10225                    // across ties. Expressed without a dedicated argmax
10226                    // op using the Step trick:
10227                    //
10228                    //   broadcasted_y = broadcast_to(y, x.shape)
10229                    //   diff = broadcasted_y - x   (for Max)
10230                    //        | x - broadcasted_y   (for Min)
10231                    //   indicator = ones - step(diff)
10232                    //   grad_x    = broadcast_to(upstream, x.shape) * indicator
10233                    //
10234                    // At argmax positions `diff == 0`, `step(0) == 0`, so
10235                    // the indicator is 1. Elsewhere `diff > 0` so step is
10236                    // 1 and the indicator is 0. Ties share the gradient.
10237                    let x = inputs[0];
10238                    let x_shape = node_shape(&graph_handle, x);
10239                    let dtype = node_dtype(&graph_handle, x);
10240                    let is_max = matches!(op, Op::MaxAll);
10241                    let broadcasted_y = push_node(
10242                        &graph_handle,
10243                        Op::BroadcastTo(x_shape.clone()),
10244                        vec![id],
10245                        x_shape.clone(),
10246                        dtype,
10247                    );
10248                    let diff = if is_max {
10249                        push_node(
10250                            &graph_handle,
10251                            Op::Sub,
10252                            vec![broadcasted_y, x],
10253                            x_shape.clone(),
10254                            dtype,
10255                        )
10256                    } else {
10257                        push_node(
10258                            &graph_handle,
10259                            Op::Sub,
10260                            vec![x, broadcasted_y],
10261                            x_shape.clone(),
10262                            dtype,
10263                        )
10264                    };
10265                    let step_diff =
10266                        push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10267                    let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10268                    let indicator = push_node(
10269                        &graph_handle,
10270                        Op::Sub,
10271                        vec![ones, step_diff],
10272                        x_shape.clone(),
10273                        dtype,
10274                    );
10275                    let broadcast_up = push_node(
10276                        &graph_handle,
10277                        Op::BroadcastTo(x_shape.clone()),
10278                        vec![up_id],
10279                        x_shape.clone(),
10280                        dtype,
10281                    );
10282                    let grad_x = push_node(
10283                        &graph_handle,
10284                        Op::Mul,
10285                        vec![broadcast_up, indicator],
10286                        x_shape,
10287                        dtype,
10288                    );
10289                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10290                }
10291                Op::SumDim(dim) => {
10292                    // Insert a size-1 at `dim` via reshape, then broadcast
10293                    // back to x.shape.
10294                    let x = inputs[0];
10295                    let x_shape = node_shape(&graph_handle, x);
10296                    let dtype = node_dtype(&graph_handle, x);
10297                    let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10298                    let reshaped = push_node(
10299                        &graph_handle,
10300                        Op::Reshape(keepdim_shape.clone()),
10301                        vec![up_id],
10302                        keepdim_shape,
10303                        dtype,
10304                    );
10305                    let grad_x = push_node(
10306                        &graph_handle,
10307                        Op::BroadcastTo(x_shape.clone()),
10308                        vec![reshaped],
10309                        x_shape,
10310                        dtype,
10311                    );
10312                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10313                }
10314                Op::MeanDim(dim) => {
10315                    // SumDim-style backward, then divide by the reduced dim size.
10316                    let x = inputs[0];
10317                    let x_shape = node_shape(&graph_handle, x);
10318                    let dtype = node_dtype(&graph_handle, x);
10319                    let reduced_size = x_shape.dims()[dim];
10320                    let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10321                    let reshaped = push_node(
10322                        &graph_handle,
10323                        Op::Reshape(keepdim_shape.clone()),
10324                        vec![up_id],
10325                        keepdim_shape,
10326                        dtype,
10327                    );
10328                    let broadcast = push_node(
10329                        &graph_handle,
10330                        Op::BroadcastTo(x_shape.clone()),
10331                        vec![reshaped],
10332                        x_shape.clone(),
10333                        dtype,
10334                    );
10335                    let n_const = build_filled_const(
10336                        &graph_handle,
10337                        x_shape.clone(),
10338                        dtype,
10339                        reduced_size as f64,
10340                    );
10341                    let grad_x = push_node(
10342                        &graph_handle,
10343                        Op::Div,
10344                        vec![broadcast, n_const],
10345                        x_shape,
10346                        dtype,
10347                    );
10348                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10349                }
10350                Op::MaxDim(dim) | Op::MinDim(dim) => {
10351                    // Same indicator trick as MaxAll/MinAll, but apply the
10352                    // "reshape to keepdim then broadcast" pattern to both
10353                    // the forward output and upstream before multiplying.
10354                    let x = inputs[0];
10355                    let x_shape = node_shape(&graph_handle, x);
10356                    let dtype = node_dtype(&graph_handle, x);
10357                    let is_max = matches!(op, Op::MaxDim(_));
10358                    let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10359                    let y_keepdim = push_node(
10360                        &graph_handle,
10361                        Op::Reshape(keepdim_shape.clone()),
10362                        vec![id],
10363                        keepdim_shape.clone(),
10364                        dtype,
10365                    );
10366                    let broadcasted_y = push_node(
10367                        &graph_handle,
10368                        Op::BroadcastTo(x_shape.clone()),
10369                        vec![y_keepdim],
10370                        x_shape.clone(),
10371                        dtype,
10372                    );
10373                    let diff = if is_max {
10374                        push_node(
10375                            &graph_handle,
10376                            Op::Sub,
10377                            vec![broadcasted_y, x],
10378                            x_shape.clone(),
10379                            dtype,
10380                        )
10381                    } else {
10382                        push_node(
10383                            &graph_handle,
10384                            Op::Sub,
10385                            vec![x, broadcasted_y],
10386                            x_shape.clone(),
10387                            dtype,
10388                        )
10389                    };
10390                    let step_diff =
10391                        push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10392                    let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10393                    let indicator = push_node(
10394                        &graph_handle,
10395                        Op::Sub,
10396                        vec![ones, step_diff],
10397                        x_shape.clone(),
10398                        dtype,
10399                    );
10400                    let up_keepdim = push_node(
10401                        &graph_handle,
10402                        Op::Reshape(keepdim_shape.clone()),
10403                        vec![up_id],
10404                        keepdim_shape,
10405                        dtype,
10406                    );
10407                    let broadcast_up = push_node(
10408                        &graph_handle,
10409                        Op::BroadcastTo(x_shape.clone()),
10410                        vec![up_keepdim],
10411                        x_shape.clone(),
10412                        dtype,
10413                    );
10414                    let grad_x = push_node(
10415                        &graph_handle,
10416                        Op::Mul,
10417                        vec![broadcast_up, indicator],
10418                        x_shape,
10419                        dtype,
10420                    );
10421                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10422                }
10423                // Phase 7.6 step 5 (2026-05-11): the legacy
10424                // `Op::SoftmaxLastDim` / `Op::LayerNormLastDim` /
10425                // `Op::RmsNormLastDim` / `Op::Rope` /
10426                // `Op::Conv2D` / `Op::FusedLinear` arms have been
10427                // dropped together with the variants themselves; the
10428                // `Op::Fused(fid, _)` arm below dispatches per id and
10429                // is the single source of truth for migrated forward
10430                // ops' backward.
10431                Op::ArgMaxDim(_) | Op::ArgMinDim(_) => {
10432                    // Argmax/argmin produce integer indices, which are
10433                    // non-differentiable. Panic rather than silently
10434                    // zero-propagating — if the user has one of these in
10435                    // their differentiated graph, they've almost
10436                    // certainly made a mistake.
10437                    panic!(
10438                        "backward: ArgMaxDim/ArgMinDim produce integer \
10439                         indices and cannot be differentiated through. \
10440                         Use MaxDim/MinDim if you want a differentiable \
10441                         selection."
10442                    );
10443                }
10444                Op::ReduceMaxTo(_) => {
10445                    // Forward: y = reduce_max_to(x, target).
10446                    // Backward: route upstream to position(s) where
10447                    // x equals its per-window max via the fused
10448                    // backward helper Op::Fused(REDUCE_MAX_TO_BACKWARD,
10449                    // _) (takes (x, upstream) and emits grad_x of
10450                    // x.shape). Tied maxes share the gradient equally
10451                    // (fair-share subgradient). Note this is the
10452                    // backward of a *primitive* (Op::ReduceMaxTo),
10453                    // not a fused forward — no BackwardKind::Fused
10454                    // edge in the registry drives this; the explicit
10455                    // emission is the source of truth.
10456                    let x = inputs[0];
10457                    let x_shape = node_shape(&graph_handle, x);
10458                    let dtype = node_dtype(&graph_handle, x);
10459                    let grad_x = push_node(
10460                        &graph_handle,
10461                        Op::Fused(
10462                            crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD,
10463                            crate::registry::FusedOpParams::ReduceMaxToBackward,
10464                        ),
10465                        vec![x, up_id],
10466                        x_shape,
10467                        dtype,
10468                    );
10469                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10470                }
10471                // Phase 7.6 step 5 (final, 2026-05-11): legacy
10472                // `Op::QMatMul` arm dropped with the variant; QMatMul
10473                // backward panics via the Op::Fused arm below.
10474                // Phase 7.6 step 5 (2026-05-11): the legacy
10475                // `Op::SoftmaxLastDimBackward | Op::LayerNormLastDimBackward |
10476                // Op::RmsNormLastDimBackward | Op::ReduceMaxToBackward`
10477                // higher-order panic arm has been dropped together
10478                // with the variants themselves. The Op::Fused arm
10479                // below panics for those four ids.
10480                Op::IndexSelect { dim } => {
10481                    // Forward: out = index_select(data, dim, indices).
10482                    // Backward: grad_data = index_add(zeros_like(data), dim, indices, upstream).
10483                    let data = inputs[0];
10484                    let idx = inputs[1];
10485                    let data_shape = node_shape(&graph_handle, data);
10486                    let dtype = node_dtype(&graph_handle, data);
10487                    let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10488                    let grad_data = push_node(
10489                        &graph_handle,
10490                        Op::IndexAdd { dim },
10491                        vec![zeros, idx, up_id],
10492                        data_shape,
10493                        dtype,
10494                    );
10495                    accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10496                    // Index tensor is itself non-differentiable (integer dtype).
10497                }
10498                Op::Gather { dim } => {
10499                    // Forward: out = gather(data, dim, indices).
10500                    // Backward: grad_data = scatter_add(zeros_like(data), dim, indices, upstream).
10501                    let data = inputs[0];
10502                    let idx = inputs[1];
10503                    let data_shape = node_shape(&graph_handle, data);
10504                    let dtype = node_dtype(&graph_handle, data);
10505                    let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10506                    let grad_data = push_node(
10507                        &graph_handle,
10508                        Op::ScatterAdd { dim },
10509                        vec![zeros, idx, up_id],
10510                        data_shape,
10511                        dtype,
10512                    );
10513                    accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10514                }
10515                Op::IndexAdd { dim } => {
10516                    // Forward: out = index_add(base, dim, indices, src).
10517                    // Backward:
10518                    //   grad_base = upstream (pass-through — base flows
10519                    //               through the non-indexed positions and
10520                    //               the accumulated positions don't zero
10521                    //               it out, they add to it)
10522                    //   grad_src  = index_select(upstream, dim, indices)
10523                    //               (the pieces of upstream that came from
10524                    //                src in the forward).
10525                    let base = inputs[0];
10526                    let idx = inputs[1];
10527                    let src = inputs[2];
10528                    let src_shape = node_shape(&graph_handle, src);
10529                    let dtype = node_dtype(&graph_handle, src);
10530                    // grad_base: upstream passes through.
10531                    accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10532                    // grad_src: select from upstream at the indices.
10533                    let grad_src = push_node(
10534                        &graph_handle,
10535                        Op::IndexSelect { dim },
10536                        vec![up_id, idx],
10537                        src_shape,
10538                        dtype,
10539                    );
10540                    accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10541                }
10542                Op::Concat { dim } => {
10543                    // Forward: out = concat(inputs.., dim).
10544                    // Backward: split upstream along `dim` into one slice per
10545                    // input at the cumulative offset, routing each slice to its
10546                    // input. N-ary (unroll_scan stacks N per-step ys into a
10547                    // single Concat; the SSM/Hopfield BPTT unroll relies on
10548                    // this). Duplicate inputs accumulate via accumulate_grad.
10549                    let mut start = 0usize;
10550                    for &inp in &inputs {
10551                        let in_shape = node_shape(&graph_handle, inp);
10552                        let dtype = node_dtype(&graph_handle, inp);
10553                        let len = in_shape.dims()[dim];
10554                        let grad_in = push_node(
10555                            &graph_handle,
10556                            Op::Slice { dim, start, len },
10557                            vec![up_id],
10558                            in_shape,
10559                            dtype,
10560                        );
10561                        accumulate_grad(&mut upstream, inp, grad_in, &graph_handle);
10562                        start += len;
10563                    }
10564                }
10565                Op::Slice { dim, start, len: _ } => {
10566                    // Forward: out = slice(x, dim, start, len).
10567                    // Backward: build a zeros tensor of x.shape, then
10568                    // scatter the upstream into the slice range. We use
10569                    // a concat of three pieces: left zeros, upstream,
10570                    // right zeros (along `dim`).
10571                    let x = inputs[0];
10572                    let x_shape = node_shape(&graph_handle, x);
10573                    let dtype = node_dtype(&graph_handle, x);
10574                    let x_dims = x_shape.dims();
10575                    let dim_size = x_dims[dim];
10576                    let up_len = x_dims[dim].min(node_shape(&graph_handle, up_id).dims()[dim]);
10577                    let left_len = start;
10578                    let right_len = dim_size - start - up_len;
10579                    // Build left zero pad if needed.
10580                    let mut pieces: Vec<NodeId> = Vec::new();
10581                    if left_len > 0 {
10582                        let mut left_dims: Vec<usize> = x_dims.to_vec();
10583                        left_dims[dim] = left_len;
10584                        let left_shape = Shape::from_dims(&left_dims);
10585                        pieces.push(build_filled_const(&graph_handle, left_shape, dtype, 0.0));
10586                    }
10587                    pieces.push(up_id);
10588                    if right_len > 0 {
10589                        let mut right_dims: Vec<usize> = x_dims.to_vec();
10590                        right_dims[dim] = right_len;
10591                        let right_shape = Shape::from_dims(&right_dims);
10592                        pieces.push(build_filled_const(&graph_handle, right_shape, dtype, 0.0));
10593                    }
10594                    // Fold concat-left-to-right.
10595                    let mut current = pieces[0];
10596                    let mut current_dims: Vec<usize> = {
10597                        let n = graph_handle.read().unwrap();
10598                        n.node(current).shape.dims().to_vec()
10599                    };
10600                    for &next in &pieces[1..] {
10601                        let next_dims: Vec<usize> = {
10602                            let n = graph_handle.read().unwrap();
10603                            n.node(next).shape.dims().to_vec()
10604                        };
10605                        let mut combined = current_dims.clone();
10606                        combined[dim] = current_dims[dim] + next_dims[dim];
10607                        let combined_shape = Shape::from_dims(&combined);
10608                        current = push_node(
10609                            &graph_handle,
10610                            Op::Concat { dim },
10611                            vec![current, next],
10612                            combined_shape,
10613                            dtype,
10614                        );
10615                        current_dims = combined;
10616                    }
10617                    accumulate_grad(&mut upstream, x, current, &graph_handle);
10618                }
10619                Op::AddScalar(_) => {
10620                    // y = x + c, dy/dx = 1. Upstream passes through.
10621                    let x = inputs[0];
10622                    accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10623                }
10624                Op::MulScalar(c) => {
10625                    // y = x * c, dy/dx = c. Multiply upstream by c via
10626                    // another MulScalar node.
10627                    let x = inputs[0];
10628                    let x_shape = node_shape(&graph_handle, x);
10629                    let dtype = node_dtype(&graph_handle, x);
10630                    let grad_x =
10631                        push_node(&graph_handle, Op::MulScalar(c), vec![up_id], x_shape, dtype);
10632                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10633                }
10634                Op::PowI(n) => {
10635                    // y = x^n, dy/dx = n * x^(n-1).
10636                    // grad_x = upstream * n * x^(n-1). Emitted as a
10637                    // single fused PowIBackward node; the executor
10638                    // routes it to baracuda's `unary_powi_backward_*`
10639                    // kernel (alpha.31) on CUDA, or falls back to the
10640                    // primitive decomposition (PowI(n-1) → MulScalar →
10641                    // Mul) on backends that haven't registered the
10642                    // fused kernel.
10643                    let x = inputs[0];
10644                    let x_shape = node_shape(&graph_handle, x);
10645                    let dtype = node_dtype(&graph_handle, x);
10646                    let grad_x = push_node(
10647                        &graph_handle,
10648                        Op::Fused(
10649                            crate::registry::FusedOps::POWI_BACKWARD,
10650                            crate::registry::FusedOpParams::PowIBackward { exp: n },
10651                        ),
10652                        vec![x, up_id],
10653                        x_shape,
10654                        dtype,
10655                    );
10656                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10657                }
10658                Op::Clamp { min, max } => {
10659                    // Subgradient: 1 where min <= x <= max, 0 elsewhere.
10660                    // Expressed via (step(x - min) - step(x - max))
10661                    // which is 1 in the interior (x > min and x <= max...
10662                    // actually step(0) = 0, so the right end is a bit
10663                    // tricky). For a reference implementation the
10664                    // simplest approach is a dedicated "clamp backward"
10665                    // indicator. We build it out of the existing ops:
10666                    //
10667                    //   lower_ok = step(x - min)   // 1 where x > min
10668                    //   upper_ok = step(max - x)   // 1 where x < max
10669                    //   indicator = lower_ok * upper_ok
10670                    //   grad_x = upstream * indicator
10671                    //
10672                    // This underestimates the gradient on the exact
10673                    // boundary by a measure-zero amount — standard.
10674                    let x = inputs[0];
10675                    let x_shape = node_shape(&graph_handle, x);
10676                    let dtype = node_dtype(&graph_handle, x);
10677                    let min_shifted = push_node(
10678                        &graph_handle,
10679                        Op::AddScalar(-min),
10680                        vec![x],
10681                        x_shape.clone(),
10682                        dtype,
10683                    );
10684                    let lower_ok = push_node(
10685                        &graph_handle,
10686                        Op::Step,
10687                        vec![min_shifted],
10688                        x_shape.clone(),
10689                        dtype,
10690                    );
10691                    let max_minus_x = push_node(
10692                        &graph_handle,
10693                        Op::MulScalar(-1.0),
10694                        vec![x],
10695                        x_shape.clone(),
10696                        dtype,
10697                    );
10698                    let max_minus_x = push_node(
10699                        &graph_handle,
10700                        Op::AddScalar(max),
10701                        vec![max_minus_x],
10702                        x_shape.clone(),
10703                        dtype,
10704                    );
10705                    let upper_ok = push_node(
10706                        &graph_handle,
10707                        Op::Step,
10708                        vec![max_minus_x],
10709                        x_shape.clone(),
10710                        dtype,
10711                    );
10712                    let indicator = push_node(
10713                        &graph_handle,
10714                        Op::Mul,
10715                        vec![lower_ok, upper_ok],
10716                        x_shape.clone(),
10717                        dtype,
10718                    );
10719                    let grad_x = push_node(
10720                        &graph_handle,
10721                        Op::Mul,
10722                        vec![up_id, indicator],
10723                        x_shape,
10724                        dtype,
10725                    );
10726                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10727                }
10728                Op::Maximum => {
10729                    // y_i = max(a_i, b_i). Gradient flows to whichever
10730                    // input was the max at that position:
10731                    //   mask_a = step(a - b)   (1 where a > b, else 0)
10732                    //   mask_b = 1 - mask_a    (approximately — at ties
10733                    //                          gradient goes to b due to
10734                    //                          step(0) = 0)
10735                    //   grad_a = upstream * mask_a
10736                    //   grad_b = upstream * mask_b
10737                    let a = inputs[0];
10738                    let b = inputs[1];
10739                    let shape = node_shape(&graph_handle, a);
10740                    let dtype = node_dtype(&graph_handle, a);
10741                    let diff = push_node(&graph_handle, Op::Sub, vec![a, b], shape.clone(), dtype);
10742                    let mask_a =
10743                        push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10744                    let ones = build_ones(&graph_handle, shape.clone(), dtype);
10745                    let mask_b = push_node(
10746                        &graph_handle,
10747                        Op::Sub,
10748                        vec![ones, mask_a],
10749                        shape.clone(),
10750                        dtype,
10751                    );
10752                    let grad_a = push_node(
10753                        &graph_handle,
10754                        Op::Mul,
10755                        vec![up_id, mask_a],
10756                        shape.clone(),
10757                        dtype,
10758                    );
10759                    let grad_b =
10760                        push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10761                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10762                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10763                }
10764                Op::Minimum => {
10765                    // Symmetric to Maximum. mask_a = step(b - a).
10766                    let a = inputs[0];
10767                    let b = inputs[1];
10768                    let shape = node_shape(&graph_handle, a);
10769                    let dtype = node_dtype(&graph_handle, a);
10770                    let diff = push_node(&graph_handle, Op::Sub, vec![b, a], shape.clone(), dtype);
10771                    let mask_a =
10772                        push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10773                    let ones = build_ones(&graph_handle, shape.clone(), dtype);
10774                    let mask_b = push_node(
10775                        &graph_handle,
10776                        Op::Sub,
10777                        vec![ones, mask_a],
10778                        shape.clone(),
10779                        dtype,
10780                    );
10781                    let grad_a = push_node(
10782                        &graph_handle,
10783                        Op::Mul,
10784                        vec![up_id, mask_a],
10785                        shape.clone(),
10786                        dtype,
10787                    );
10788                    let grad_b =
10789                        push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10790                    accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10791                    accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10792                }
10793                Op::ScatterAdd { dim } => {
10794                    // Forward: out = scatter_add(base, dim, indices, src).
10795                    // Backward:
10796                    //   grad_base = upstream (pass-through)
10797                    //   grad_src  = gather(upstream, dim, indices)
10798                    let base = inputs[0];
10799                    let idx = inputs[1];
10800                    let src = inputs[2];
10801                    let src_shape = node_shape(&graph_handle, src);
10802                    let dtype = node_dtype(&graph_handle, src);
10803                    accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10804                    let grad_src = push_node(
10805                        &graph_handle,
10806                        Op::Gather { dim },
10807                        vec![up_id, idx],
10808                        src_shape,
10809                        dtype,
10810                    );
10811                    accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10812                }
10813                Op::Copy { .. } => {
10814                    // Forward: out = copy(x, target). Backward: the
10815                    // gradient flows back to `x`'s original device, so
10816                    // the reverse would be another Copy. The source
10817                    // device is x's residency — we don't have the typed
10818                    // "where was x?" here without tracking it, so we
10819                    // fall back to the graph's placement hint on x (if
10820                    // any) or trust the scheduler to re-insert the
10821                    // correct copy during Phase 4. For Phase 3 we
10822                    // assume inference-only use and pass upstream through.
10823                    let x = inputs[0];
10824                    accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10825                }
10826                Op::Release => {
10827                    // Release has no data output and no gradient to
10828                    // propagate. Input is destroyed; any downstream
10829                    // node that needs gradient through the original
10830                    // tensor must get it from a sibling Copy's backward
10831                    // path, not this one.
10832                }
10833                Op::Move { .. } => {
10834                    // Move is Copy + destroy-source. For backward,
10835                    // treat it the same as Copy — gradient flows back
10836                    // through the move. The Phase 3-style assumption
10837                    // still applies: we pass upstream through and rely
10838                    // on the scheduler to re-insert the correct reverse
10839                    // transfer in a training pass. For inference-only
10840                    // use (the current case), this is a no-op.
10841                    let x = inputs[0];
10842                    accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10843                }
10844                Op::WriteSlice { .. } => {
10845                    // KV-cache writes are forward-only — the slab being
10846                    // written *into* gets mutated in place, and the
10847                    // source slab is read non-destructively. There is
10848                    // no meaningful gradient through a mutating write
10849                    // in fuel's tape-based autograd model. If a use
10850                    // case needs differentiable scatter, the gradient
10851                    // path is a `Gather` (read the slab back) plus an
10852                    // accumulating `IndexAdd` on the destination —
10853                    // express that explicitly in forward.
10854                    panic!(
10855                        "NodeHandle::backward: Op::WriteSlice is non-differentiable. \
10856                         Use Gather + IndexAdd if you need a differentiable scatter."
10857                    );
10858                }
10859                Op::WriteSliceRotating { .. } => {
10860                    // Same forward-only contract as WriteSlice — the
10861                    // ring buffer's bytes are mutated in place at a
10862                    // dynamic offset. Sliding-window KV caches don't
10863                    // need a gradient path; a differentiable scatter
10864                    // is expressible as Gather + IndexAdd in forward.
10865                    panic!(
10866                        "NodeHandle::backward: Op::WriteSliceRotating is non-differentiable. \
10867                         Use Gather + IndexAdd if you need a differentiable scatter."
10868                    );
10869                }
10870                Op::WriteSliceDoff { .. } => {
10871                    // Forward-only, like WriteSlice/WriteSliceRotating —
10872                    // the KV-cache buffer is mutated in place at a
10873                    // device-resident offset. Decode-time append; no
10874                    // gradient path.
10875                    panic!(
10876                        "NodeHandle::backward: Op::WriteSliceDoff is non-differentiable. \
10877                         Use Gather + IndexAdd if you need a differentiable scatter."
10878                    );
10879                }
10880                // Phase 7.6 step 5 (2026-05-11): the legacy
10881                // `Op::Conv2D { stride, padding, groups }` backward
10882                // arm has been dropped together with the variant;
10883                // `Op::Fused(CONV2D, _)` below carries the full
10884                // backward logic (including the inner dW Conv2D
10885                // emission, which itself goes through Op::Fused).
10886                // Phase 7.6 step 4 (final): the builders for
10887                // ConvTranspose2D, FlashAttn, and PagedAttn now emit
10888                // `Op::Fused(<id>, _)`; these legacy backward arms
10889                // still fire for direct legacy-variant constructions
10890                // Phase 7.6 step 5 (final, 2026-05-11): the legacy
10891                // `Op::ConvTranspose2D` / `Op::FlashAttn` /
10892                // `Op::PagedAttn` / `Op::FusedLinear` backward arms
10893                // have all been dropped together with the variants;
10894                // `Op::Fused(<id>, _)` below panics for each id.
10895                Op::Fused(fid, params) => {
10896                    // Per-id backward dispatch. Each migrated fused op
10897                    // gets a branch here that emits the appropriate
10898                    // gradient subgraph.
10899                    if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM {
10900                        // grad_x = softmax_last_dim_backward(y, upstream).
10901                        // Phase 7.6 step 4 (backward-helper batch):
10902                        // emits Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, _)
10903                        // — the architecturally-correct registry form,
10904                        // matching the BackwardKind::Fused edge on
10905                        // SOFTMAX_LAST_DIM's entry.
10906                        let x = inputs[0];
10907                        let y_shape = node_shape(&graph_handle, id);
10908                        let dtype = node_dtype(&graph_handle, id);
10909                        let grad_x = push_node(
10910                            &graph_handle,
10911                            Op::Fused(
10912                                crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
10913                                crate::registry::FusedOpParams::SoftmaxLastDimBackward,
10914                            ),
10915                            vec![id, up_id],
10916                            y_shape,
10917                            dtype,
10918                        );
10919                        accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10920                    } else if fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM {
10921                        // grad_x = layer_norm_last_dim_backward(x, upstream, eps).
10922                        // Phase 7.6 step 4 (backward-helper batch): emits
10923                        // registry form Op::Fused(LAYER_NORM_LAST_DIM_BACKWARD, _).
10924                        let eps = match params {
10925                            crate::registry::FusedOpParams::LayerNormLastDim { eps } => eps,
10926                            _ => panic!(
10927                                "NodeHandle::backward: Op::Fused(LAYER_NORM_LAST_DIM, _) \
10928                                 expected FusedOpParams::LayerNormLastDim, got {params:?}",
10929                            ),
10930                        };
10931                        let x = inputs[0];
10932                        let x_shape = node_shape(&graph_handle, x);
10933                        let dtype = node_dtype(&graph_handle, x);
10934                        let grad_x = push_node(
10935                            &graph_handle,
10936                            Op::Fused(
10937                                crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
10938                                crate::registry::FusedOpParams::LayerNormLastDimBackward { eps },
10939                            ),
10940                            vec![x, up_id],
10941                            x_shape,
10942                            dtype,
10943                        );
10944                        accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10945                    } else if fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM {
10946                        // grad_x = rms_norm_last_dim_backward(x, upstream, eps).
10947                        // Phase 7.6 step 4 (backward-helper batch): emits
10948                        // registry form Op::Fused(RMS_NORM_LAST_DIM_BACKWARD, _).
10949                        let eps = match params {
10950                            crate::registry::FusedOpParams::RmsNormLastDim { eps } => eps,
10951                            _ => panic!(
10952                                "NodeHandle::backward: Op::Fused(RMS_NORM_LAST_DIM, _) \
10953                                 expected FusedOpParams::RmsNormLastDim, got {params:?}",
10954                            ),
10955                        };
10956                        let x = inputs[0];
10957                        let x_shape = node_shape(&graph_handle, x);
10958                        let dtype = node_dtype(&graph_handle, x);
10959                        let grad_x = push_node(
10960                            &graph_handle,
10961                            Op::Fused(
10962                                crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
10963                                crate::registry::FusedOpParams::RmsNormLastDimBackward { eps },
10964                            ),
10965                            vec![x, up_id],
10966                            x_shape,
10967                            dtype,
10968                        );
10969                        accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10970                    } else if fid == crate::registry::FusedOps::ROPE {
10971                        // grad_x = rope(upstream, cos, -sin) — same
10972                        // formula as the legacy Op::Rope arm above.
10973                        // Emit the registry form for the backward
10974                        // Rope node so the gradient subgraph routes
10975                        // through the same Op::Fused dispatch as the
10976                        // forward.
10977                        let x = inputs[0];
10978                        let cos = inputs[1];
10979                        let sin = inputs[2];
10980                        let x_shape = node_shape(&graph_handle, x);
10981                        let sin_shape = node_shape(&graph_handle, sin);
10982                        let dtype = node_dtype(&graph_handle, x);
10983                        let neg_sin =
10984                            push_node(&graph_handle, Op::Neg, vec![sin], sin_shape, dtype);
10985                        let grad_x = push_node(
10986                            &graph_handle,
10987                            Op::Fused(
10988                                crate::registry::FusedOps::ROPE,
10989                                crate::registry::FusedOpParams::Rope,
10990                            ),
10991                            vec![up_id, cos, neg_sin],
10992                            x_shape,
10993                            dtype,
10994                        );
10995                        accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10996                    } else if fid == crate::registry::FusedOps::FUSED_LINEAR {
10997                        // (a @ b) + bias backward — same three-grad
10998                        // decomposition as the legacy Op::FusedLinear
10999                        // arm above. We reuse MatMul backward (no
11000                        // intermediate matmul output is cached, so the
11001                        // grad computes from upstream + a, b directly).
11002                        let a = inputs[0];
11003                        let b = inputs[1];
11004                        let bias = inputs[2];
11005                        let a_shape = node_shape(&graph_handle, a);
11006                        let b_shape = node_shape(&graph_handle, b);
11007                        let bias_shape = node_shape(&graph_handle, bias);
11008                        let dtype = node_dtype(&graph_handle, a);
11009                        let b_t_shape = transposed_shape(&b_shape);
11010                        let b_t =
11011                            push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
11012                        let grad_a = push_node(
11013                            &graph_handle,
11014                            Op::MatMul,
11015                            vec![up_id, b_t],
11016                            a_shape.clone(),
11017                            dtype,
11018                        );
11019                        let a_t_shape = transposed_shape(&a_shape);
11020                        let a_t =
11021                            push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
11022                        let grad_b =
11023                            push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
11024                        let grad_bias = push_node(
11025                            &graph_handle,
11026                            Op::ReduceSumTo(bias_shape.clone()),
11027                            vec![up_id],
11028                            bias_shape,
11029                            dtype,
11030                        );
11031                        accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
11032                        accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
11033                        accumulate_grad(&mut upstream, bias, grad_bias, &graph_handle);
11034                    } else if fid == crate::registry::FusedOps::CONV2D {
11035                        // Same backward formulation as the legacy
11036                        // Op::Conv2D arm above. The inner Conv2D node
11037                        // emitted for grad_w also goes through the
11038                        // registry (Op::Fused(CONV2D, _)) so the
11039                        // gradient subgraph routes consistently. The
11040                        // ConvTranspose2D node stays as a primitive
11041                        // variant until that op migrates in its own
11042                        // step-4 commit.
11043                        let (stride, padding, groups) = match params {
11044                            crate::registry::FusedOpParams::Conv2D {
11045                                stride,
11046                                padding,
11047                                groups,
11048                            } => (stride, padding, groups),
11049                            _ => panic!(
11050                                "NodeHandle::backward: Op::Fused(CONV2D, _) \
11051                                 expected FusedOpParams::Conv2D, got {params:?}",
11052                            ),
11053                        };
11054                        let x = inputs[0];
11055                        let weight = inputs[1];
11056                        let x_shape = node_shape(&graph_handle, x);
11057                        let w_shape = node_shape(&graph_handle, weight);
11058                        let dtype = node_dtype(&graph_handle, x);
11059
11060                        // dX via transposed conv (see legacy arm for derivation).
11061                        let x_dims = x_shape.dims();
11062                        let w_dims = w_shape.dims();
11063                        let dy_dims = node_shape(&graph_handle, id).dims().to_vec();
11064                        let (sh, sw) = stride;
11065                        let (ph, pw) = padding;
11066                        let (kh, kw) = (w_dims[2], w_dims[3]);
11067                        let (h_in, w_in) = (x_dims[2], x_dims[3]);
11068                        let (dy_h, dy_w) = (dy_dims[2], dy_dims[3]);
11069                        let base_h = (dy_h - 1) * sh + (kh - 1) + 1;
11070                        let base_w = (dy_w - 1) * sw + (kw - 1) + 1;
11071                        let want_h = h_in + 2 * ph;
11072                        let want_w = w_in + 2 * pw;
11073                        let out_pad_h = want_h.saturating_sub(base_h);
11074                        let out_pad_w = want_w.saturating_sub(base_w);
11075                        if groups != 1 {
11076                            panic!(
11077                                "NodeHandle::backward: Op::Fused(CONV2D) groups>1 \
11078                                 backward not yet implemented (got groups={groups}). \
11079                                 The stride/padding/groups=1 case is wired; grouped \
11080                                 backward needs a per-group weight reshape.",
11081                            );
11082                        }
11083                        let perm_01 = vec![1usize, 0, 2, 3];
11084                        // Phase 7.6 step 4 (final): emit registry form
11085                        // for the inner dX node so the gradient subgraph
11086                        // routes consistently through Op::Fused dispatch.
11087                        let grad_x = push_node(
11088                            &graph_handle,
11089                            Op::Fused(
11090                                crate::registry::FusedOps::CONV_TRANSPOSE2D,
11091                                crate::registry::FusedOpParams::ConvTranspose2D {
11092                                    stride,
11093                                    padding,
11094                                    output_padding: (out_pad_h, out_pad_w),
11095                                    dilation: (1, 1),
11096                                    groups,
11097                                },
11098                            ),
11099                            vec![up_id, weight],
11100                            x_shape.clone(),
11101                            dtype,
11102                        );
11103                        accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11104
11105                        // dW via correlation expressed as a conv2d.
11106                        if sh != 1 || sw != 1 {
11107                            panic!(
11108                                "NodeHandle::backward: Op::Fused(CONV2D) stride>1 \
11109                                 backward not yet implemented (got stride={stride:?}). \
11110                                 Conv2D needs a `dilation` field to express this \
11111                                 without composing extra ops.",
11112                            );
11113                        }
11114                        let x_swapped_shape = {
11115                            let d = x_dims;
11116                            Shape::from_dims(&[d[1], d[0], d[2], d[3]])
11117                        };
11118                        let x_swapped = push_node(
11119                            &graph_handle,
11120                            Op::Permute(perm_01.clone()),
11121                            vec![x],
11122                            x_swapped_shape,
11123                            dtype,
11124                        );
11125                        let dy_swapped_shape =
11126                            Shape::from_dims(&[dy_dims[1], dy_dims[0], dy_dims[2], dy_dims[3]]);
11127                        let dy_swapped = push_node(
11128                            &graph_handle,
11129                            Op::Permute(perm_01.clone()),
11130                            vec![up_id],
11131                            dy_swapped_shape,
11132                            dtype,
11133                        );
11134                        let conv_out_shape =
11135                            Shape::from_dims(&[w_dims[1], w_dims[0], w_dims[2], w_dims[3]]);
11136                        let grad_w_pre_transpose = push_node(
11137                            &graph_handle,
11138                            Op::Fused(
11139                                crate::registry::FusedOps::CONV2D,
11140                                crate::registry::FusedOpParams::Conv2D {
11141                                    stride: (1, 1),
11142                                    padding,
11143                                    groups: 1,
11144                                },
11145                            ),
11146                            vec![x_swapped, dy_swapped],
11147                            conv_out_shape,
11148                            dtype,
11149                        );
11150                        let grad_w = push_node(
11151                            &graph_handle,
11152                            Op::Permute(perm_01),
11153                            vec![grad_w_pre_transpose],
11154                            w_shape,
11155                            dtype,
11156                        );
11157                        accumulate_grad(&mut upstream, weight, grad_w, &graph_handle);
11158
11159                        // Bias (if present): sum dY over N, H, W via
11160                        // ReduceSumTo([1, Cout, 1, 1]) then reshape to
11161                        // [Cout]. Same path as the legacy arm.
11162                        if inputs.len() >= 3 {
11163                            let bias = inputs[2];
11164                            let bias_shape = node_shape(&graph_handle, bias);
11165                            let cout_4d = Shape::from_dims(&[1, dy_dims[1], 1, 1]);
11166                            let reduced = push_node(
11167                                &graph_handle,
11168                                Op::ReduceSumTo(cout_4d.clone()),
11169                                vec![up_id],
11170                                cout_4d,
11171                                dtype,
11172                            );
11173                            let grad_b = push_node(
11174                                &graph_handle,
11175                                Op::Reshape(bias_shape.clone()),
11176                                vec![reduced],
11177                                bias_shape,
11178                                dtype,
11179                            );
11180                            accumulate_grad(&mut upstream, bias, grad_b, &graph_handle);
11181                        }
11182                    } else if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD
11183                        || fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD
11184                        || fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
11185                        || fid == crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD
11186                    {
11187                        // Higher-order gradients through backward
11188                        // helpers panic.
11189                        panic!(
11190                            "backward: higher-order gradients through \
11191                             softmax/layer_norm/rms_norm/reduce_max_to backward \
11192                             helpers are not yet supported in the MVP."
11193                        );
11194                    } else if fid == crate::registry::FusedOps::CONV_TRANSPOSE2D {
11195                        // Higher-order grad of the transposed conv
11196                        // isn't needed for Conv2D's backward (which
11197                        // only consumes the forward output). Adding
11198                        // it requires the same dilation-as-stride
11199                        // trick as Conv2D's dW. Punt until a real
11200                        // consumer asks for it.
11201                        panic!(
11202                            "NodeHandle::backward: ConvTranspose2D does \
11203                             not yet have its own gradient rule \
11204                             (only used in the forward path of \
11205                             Conv2D's backward).",
11206                        );
11207                    } else if fid == crate::registry::FusedOps::FLASH_ATTN {
11208                        // Emit three backward nodes: dQ via
11209                        // FLASH_ATTN_BACKWARD_Q, dK via _K, dV via _V.
11210                        // Each takes (q, k, v, dO, [alibi]) and
11211                        // recomputes the softmax state independently
11212                        // in CPU's math-definition path. GPU kernels
11213                        // (when they ship) can fuse the recompute.
11214                        let q = inputs[0];
11215                        let k = inputs[1];
11216                        let v = inputs[2];
11217                        let alibi = inputs.get(3).copied();
11218                        let q_shape = node_shape(&graph_handle, q);
11219                        let k_shape = node_shape(&graph_handle, k);
11220                        let v_shape = node_shape(&graph_handle, v);
11221                        let dtype = node_dtype(&graph_handle, q);
11222                        let (scale, causal, wl, wr, sc) = match params {
11223                            crate::registry::FusedOpParams::FlashAttn {
11224                                softmax_scale,
11225                                causal,
11226                                window_size_left,
11227                                window_size_right,
11228                                softcap,
11229                                // Backward over the static (full-K) flash
11230                                // only; the runtime-k_len capacity form is
11231                                // forward-only (decode). k_len is ignored
11232                                // here.
11233                                k_len: _,
11234                            } => (
11235                                softmax_scale,
11236                                causal,
11237                                window_size_left,
11238                                window_size_right,
11239                                softcap,
11240                            ),
11241                            other => panic!(
11242                                "NodeHandle::backward: FlashAttn node carries \
11243                                 unexpected params {other:?}",
11244                            ),
11245                        };
11246                        let bw_params = crate::registry::FusedOpParams::FlashAttnBackward {
11247                            softmax_scale: scale,
11248                            causal,
11249                            window_size_left: wl,
11250                            window_size_right: wr,
11251                            softcap: sc,
11252                        };
11253                        let mut bw_inputs = vec![q, k, v, up_id];
11254                        if let Some(a) = alibi {
11255                            bw_inputs.push(a);
11256                        }
11257                        let grad_q = push_node(
11258                            &graph_handle,
11259                            Op::Fused(
11260                                crate::registry::FusedOps::FLASH_ATTN_BACKWARD_Q,
11261                                bw_params.clone(),
11262                            ),
11263                            bw_inputs.clone(),
11264                            q_shape,
11265                            dtype,
11266                        );
11267                        let grad_k = push_node(
11268                            &graph_handle,
11269                            Op::Fused(
11270                                crate::registry::FusedOps::FLASH_ATTN_BACKWARD_K,
11271                                bw_params.clone(),
11272                            ),
11273                            bw_inputs.clone(),
11274                            k_shape,
11275                            dtype,
11276                        );
11277                        let grad_v = push_node(
11278                            &graph_handle,
11279                            Op::Fused(crate::registry::FusedOps::FLASH_ATTN_BACKWARD_V, bw_params),
11280                            bw_inputs,
11281                            v_shape,
11282                            dtype,
11283                        );
11284                        accumulate_grad(&mut upstream, q, grad_q, &graph_handle);
11285                        accumulate_grad(&mut upstream, k, grad_k, &graph_handle);
11286                        accumulate_grad(&mut upstream, v, grad_v, &graph_handle);
11287                    } else if fid == crate::registry::FusedOps::PAGED_ATTN {
11288                        // Paged attention is decode-side only by
11289                        // construction (variable-length KV cache, no
11290                        // training pass writes through it). No
11291                        // gradient rule.
11292                        panic!(
11293                            "NodeHandle::backward: PagedAttn is \
11294                             decode-only; no gradient rule exists.",
11295                        );
11296                    } else if fid == crate::registry::FusedOps::QMATMUL {
11297                        // Quantized matmul: weights are frozen
11298                        // bytes; activation gradient isn't
11299                        // implemented today. Dequantize-then-matmul
11300                        // is the workaround if differentiable
11301                        // quantized inference is needed.
11302                        panic!(
11303                            "backward: QMatMul is not differentiable \
11304                             (quantized weights are frozen). Use a \
11305                             dequantize + standard matmul if you \
11306                             need gradients through this input."
11307                        );
11308                    } else {
11309                        panic!(
11310                            "NodeHandle::backward: Op::Fused id {fid:?} has no \
11311                             backward arm wired yet. This is a programming \
11312                             bug — extend the match when the op migrates \
11313                             to the registry.",
11314                        );
11315                    }
11316                }
11317                Op::Alloc { .. } => {
11318                    // Op::Alloc is a source op (zero inputs) that
11319                    // produces a fresh zero-init buffer. No upstream
11320                    // gradient to propagate — the alloc's "input" is
11321                    // the abstract notion of fresh memory, which has
11322                    // no derivative. Mirrors Op::Const's treatment.
11323                    // (Phase 3a of bridge-retirement; see
11324                    // `WorkItemKind::Alloc` in fuel-storage.)
11325                }
11326                Op::ZeroFill => {
11327                    // Op::ZeroFill writes deterministic constants
11328                    // (zeros) to its input's bytes. The output is
11329                    // a constant tensor; gradient w.r.t. it is
11330                    // meaningless. Like Op::Const / Op::Alloc, no
11331                    // gradient propagates back.
11332                }
11333                Op::ScatterIntoSlot { .. } => {
11334                    // Item 4 IR-only scaffold — the backward graph
11335                    // emits this op as the producer's gradient
11336                    // assembler, but `ScatterIntoSlot` itself has no
11337                    // backward (it's a structural op composing
11338                    // already-differentiated slot gradients). No
11339                    // gradient propagates back; matches the
11340                    // Op::Const / Op::Alloc / Op::ZeroFill treatment.
11341                }
11342                Op::Branch { .. } => {
11343                    // PR-A0 inert scaffold. `Op::Branch` is the
11344                    // multi-path phi/merge node; it is never constructed
11345                    // in A0, so this arm is unreachable today. When the
11346                    // PR-A1 builders land, gradient flow through a Branch
11347                    // routes via its arms (each an `inputs[i]` route exit)
11348                    // and reconverges at `reconverge_at` — not through the
11349                    // merge node itself. `backward` is infallible
11350                    // (`-> GradMap`), so the no-panic inert handling is to
11351                    // drop the gradient at the structural node, matching
11352                    // the Op::Const / Op::ScatterIntoSlot treatment above.
11353                    // The real per-arm routing lands with the builders.
11354                }
11355                Op::Scan { .. } => {
11356                    // Defensive `panic!` — `backward() -> GradMap` is infallible
11357                    // (no Err channel), so this is an internal-error guard in the
11358                    // same infallible walk that already panics for QMatMul /
11359                    // PagedAttn, NOT a recoverable typed error. It is unreachable
11360                    // via the public builders: the C3 pre-pass
11361                    // (lower_scans_for_backward) unrolls every Op::Scan to
11362                    // primitives before the topo order is taken, and the builders
11363                    // always emit the View consumers the pre-pass's remap +
11364                    // never-hang guard lower away. Reaching here means the
11365                    // pre-pass did not run (an internal bug).
11366                    panic!(
11367                        "NodeHandle::backward: Op::Scan reached the reverse walk un-lowered — \
11368                            the C3 lower_scans_for_backward pre-pass did not run (internal bug)."
11369                    );
11370                }
11371                Op::ScanPlaceholder { .. } => {
11372                    // Inert body-hole leaf (no inputs) — never a real
11373                    // differentiation target. Drop gradient like Op::Const /
11374                    // Op::Iota; a live backward never reaches it (the body is
11375                    // materialized by unroll_scan before any realize).
11376                }
11377                Op::View { slot } | Op::ViewOwned { slot } => {
11378                    // Multi-output projection — item 4 backward
11379                    // composition (Option C, 2026-06-01).
11380                    //
11381                    // Forward (Op::View): shares the producer's
11382                    // bundled Storage Arc and exposes one slot's
11383                    // typed window. Forward (Op::ViewOwned): memcpys
11384                    // the slot's bytes into a fresh Storage.
11385                    //
11386                    // Backward: scatter the upstream gradient into
11387                    // the slot's byte range of a fresh zero-bundle of
11388                    // the producer's primary shape, then accumulate
11389                    // that partial-bundle gradient as the producer's
11390                    // input gradient. Multiple View consumers of the
11391                    // same producer accumulate via the standard
11392                    // sum-of-partials path:
11393                    //   bundle_grad =
11394                    //     ScatterIntoSlot{0}(0, g_y)  +
11395                    //     ScatterIntoSlot{1}(0, g_state) + ...
11396                    //
11397                    // **Status (item 4)**: IR-level wiring only —
11398                    // emits the scatter chain in the backward graph,
11399                    // but no Op::ScatterIntoSlot kernel is registered.
11400                    // The production multi-output producers
11401                    // (SelectiveScan, SsdChunkScan) are
11402                    // `BackwardKind::NotDifferentiable`, so autograd
11403                    // panics at the producer before this scatter is
11404                    // realized. When a differentiable multi-output op
11405                    // materializes (Mamba training, FSCE loss+grad
11406                    // fused), it lights up the ScatterIntoSlot CPU
11407                    // kernel + tests alongside its own backward.
11408                    let producer = inputs[0];
11409                    let producer_shape = node_shape(&graph_handle, producer);
11410                    let producer_dtype = node_dtype(&graph_handle, producer);
11411                    let zero = build_filled_const(
11412                        &graph_handle,
11413                        producer_shape.clone(),
11414                        producer_dtype,
11415                        0.0,
11416                    );
11417                    let scattered = push_node(
11418                        &graph_handle,
11419                        Op::ScatterIntoSlot { slot },
11420                        vec![zero, up_id],
11421                        producer_shape,
11422                        producer_dtype,
11423                    );
11424                    accumulate_grad(&mut upstream, producer, scattered, &graph_handle);
11425                }
11426                Op::ReluInplace => {
11427                    // Same backward as Op::Relu — d(relu(x))/dx = step(x).
11428                    // The view-aware `derive_ordering` (Phase 4a) pins
11429                    // `Op::Step(x)` to run BEFORE Op::ReluInplace, so the
11430                    // step kernel sees x's original bytes.
11431                    let x = inputs[0];
11432                    let x_shape = node_shape(&graph_handle, x);
11433                    let dtype = node_dtype(&graph_handle, x);
11434                    let step_x =
11435                        push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
11436                    let grad_x =
11437                        push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
11438                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11439                }
11440                Op::SiluInplace => {
11441                    // Same backward as Op::Silu — grad_x = upstream * (s + y*(1-s))
11442                    // where s = sigmoid(x) and y = silu(x) = this in-place node's
11443                    // output. The post-mutation bytes at `id` ARE silu(x) (the
11444                    // in-place op runs after the Sigmoid(x) read because of the
11445                    // alias-aware ordering pass). `Op::Sigmoid(x)` reads x's
11446                    // pre-mutation bytes; `Op::Mul(id, ...)` reads post-mutation
11447                    // bytes — both correct.
11448                    let x = inputs[0];
11449                    let x_shape = node_shape(&graph_handle, x);
11450                    let dtype = node_dtype(&graph_handle, x);
11451                    let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
11452                    let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
11453                    let one_minus_s = push_node(
11454                        &graph_handle,
11455                        Op::Sub,
11456                        vec![ones, s],
11457                        x_shape.clone(),
11458                        dtype,
11459                    );
11460                    let y_times_1ms = push_node(
11461                        &graph_handle,
11462                        Op::Mul,
11463                        vec![id, one_minus_s],
11464                        x_shape.clone(),
11465                        dtype,
11466                    );
11467                    let inner = push_node(
11468                        &graph_handle,
11469                        Op::Add,
11470                        vec![s, y_times_1ms],
11471                        x_shape.clone(),
11472                        dtype,
11473                    );
11474                    let grad_x =
11475                        push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
11476                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11477                }
11478                Op::TanhInplace => {
11479                    // Same backward as Op::Tanh — grad_x = upstream * (1 - y²)
11480                    // where y = tanh(x) = this in-place node's output. `Op::Sqr(id)`
11481                    // reads post-mutation bytes (= tanh(x) by definition of the
11482                    // in-place op); no need to reference x at all.
11483                    let x = inputs[0];
11484                    let y_shape = node_shape(&graph_handle, id);
11485                    let dtype = node_dtype(&graph_handle, id);
11486                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
11487                    let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11488                    let one_minus_sq = push_node(
11489                        &graph_handle,
11490                        Op::Sub,
11491                        vec![ones, y_sq],
11492                        y_shape.clone(),
11493                        dtype,
11494                    );
11495                    let grad_x = push_node(
11496                        &graph_handle,
11497                        Op::Mul,
11498                        vec![up_id, one_minus_sq],
11499                        y_shape,
11500                        dtype,
11501                    );
11502                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11503                }
11504                Op::SigmoidInplace => {
11505                    // Same backward as Op::Sigmoid — grad_x = upstream * y * (1 - y)
11506                    // where y = sigmoid(x) = this in-place node's output.
11507                    let x = inputs[0];
11508                    let y_shape = node_shape(&graph_handle, id);
11509                    let dtype = node_dtype(&graph_handle, id);
11510                    let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11511                    let one_minus_y = push_node(
11512                        &graph_handle,
11513                        Op::Sub,
11514                        vec![ones, id],
11515                        y_shape.clone(),
11516                        dtype,
11517                    );
11518                    let y_times_1my = push_node(
11519                        &graph_handle,
11520                        Op::Mul,
11521                        vec![id, one_minus_y],
11522                        y_shape.clone(),
11523                        dtype,
11524                    );
11525                    let grad_x = push_node(
11526                        &graph_handle,
11527                        Op::Mul,
11528                        vec![up_id, y_times_1my],
11529                        y_shape,
11530                        dtype,
11531                    );
11532                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11533                }
11534                Op::GeluTanhInplace => {
11535                    // Same backward as Op::GeluTanh. The formula reads only the
11536                    // pre-mutation input `x` (like SiluInplace's Sigmoid(x) read),
11537                    // which the alias-aware ordering pass keeps ahead of the
11538                    // in-place write.
11539                    let x = inputs[0];
11540                    let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
11541                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11542                }
11543                Op::NegInplace => {
11544                    // Same backward as Op::Neg — grad_x = -upstream. No
11545                    // dependency on x or y; Phase 4a ordering not needed.
11546                    let x = inputs[0];
11547                    let x_shape = node_shape(&graph_handle, x);
11548                    let dtype = node_dtype(&graph_handle, x);
11549                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
11550                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11551                }
11552                Op::AbsInplace => {
11553                    // Same backward as Op::Abs — grad_x = sign(x) * upstream.
11554                    // `Op::Sign(x)` reads x's pre-mutation bytes (Phase 4a
11555                    // pins the in-place op after the Sign read).
11556                    let x = inputs[0];
11557                    let x_shape = node_shape(&graph_handle, x);
11558                    let dtype = node_dtype(&graph_handle, x);
11559                    let sign_x =
11560                        push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
11561                    let grad_x =
11562                        push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
11563                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11564                }
11565                Op::SqrInplace => {
11566                    // Same backward as Op::Sqr — grad_x = 2x * upstream,
11567                    // expressed as `x + x` to avoid a scalar broadcast.
11568                    // `x + x` reads pre-mutation bytes (Phase 4a).
11569                    let x = inputs[0];
11570                    let x_shape = node_shape(&graph_handle, x);
11571                    let dtype = node_dtype(&graph_handle, x);
11572                    let two_x =
11573                        push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
11574                    let grad_x =
11575                        push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
11576                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11577                }
11578                Op::SqrtInplace => {
11579                    // Same backward as Op::Sqrt — y = √x, grad_x = upstream/(2y).
11580                    // Reads only the forward output `id`, which is post-mutation =
11581                    // √x by definition; no pre-mutation x access needed.
11582                    let x = inputs[0];
11583                    let x_shape = node_shape(&graph_handle, x);
11584                    let dtype = node_dtype(&graph_handle, x);
11585                    let two_y =
11586                        push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
11587                    let grad_x =
11588                        push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
11589                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11590                }
11591                Op::RsqrtInplace => {
11592                    // Same backward as Op::Rsqrt — y = x^(-1/2),
11593                    // grad_x = -0.5 * upstream * y³. Reads forward output (id)
11594                    // only — post-mutation = y by definition.
11595                    let x = inputs[0];
11596                    let x_shape = node_shape(&graph_handle, x);
11597                    let dtype = node_dtype(&graph_handle, x);
11598                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11599                    let y_cu = push_node(
11600                        &graph_handle,
11601                        Op::Mul,
11602                        vec![id, y_sq],
11603                        x_shape.clone(),
11604                        dtype,
11605                    );
11606                    let scaled = push_node(
11607                        &graph_handle,
11608                        Op::MulScalar(-0.5),
11609                        vec![y_cu],
11610                        x_shape.clone(),
11611                        dtype,
11612                    );
11613                    let grad_x =
11614                        push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11615                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11616                }
11617                Op::RecipInplace => {
11618                    // Same backward as Op::Recip — y = 1/x, grad_x = -upstream * y².
11619                    // Reads forward output (id) only — post-mutation = 1/x.
11620                    let x = inputs[0];
11621                    let x_shape = node_shape(&graph_handle, x);
11622                    let dtype = node_dtype(&graph_handle, x);
11623                    let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11624                    let up_y_sq = push_node(
11625                        &graph_handle,
11626                        Op::Mul,
11627                        vec![up_id, y_sq],
11628                        x_shape.clone(),
11629                        dtype,
11630                    );
11631                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
11632                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11633                }
11634                Op::ExpInplace => {
11635                    // Same backward as Op::Exp — d(exp(x))/dx = exp(x) = y = id.
11636                    // grad_x = upstream * y. Reads forward output (id) only.
11637                    let x = inputs[0];
11638                    let out_shape = node_shape(&graph_handle, id);
11639                    let dtype = node_dtype(&graph_handle, id);
11640                    let grad_x =
11641                        push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
11642                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11643                }
11644                Op::LogInplace => {
11645                    // Same backward as Op::Log — grad_x = upstream / x.
11646                    // `Op::Div(up, x)` reads pre-mutation bytes of x (Phase 4a).
11647                    let x = inputs[0];
11648                    let x_shape = node_shape(&graph_handle, x);
11649                    let dtype = node_dtype(&graph_handle, x);
11650                    let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
11651                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11652                }
11653                Op::SinInplace => {
11654                    // Same backward as Op::Sin — grad_x = upstream * cos(x).
11655                    // `Op::Cos(x)` reads pre-mutation x via Phase 4a ordering.
11656                    let x = inputs[0];
11657                    let x_shape = node_shape(&graph_handle, x);
11658                    let dtype = node_dtype(&graph_handle, x);
11659                    let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
11660                    let grad_x =
11661                        push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
11662                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11663                }
11664                Op::CosInplace => {
11665                    // Same backward as Op::Cos — grad_x = -(upstream * sin(x)).
11666                    let x = inputs[0];
11667                    let x_shape = node_shape(&graph_handle, x);
11668                    let dtype = node_dtype(&graph_handle, x);
11669                    let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
11670                    let up_sin = push_node(
11671                        &graph_handle,
11672                        Op::Mul,
11673                        vec![up_id, sin_x],
11674                        x_shape.clone(),
11675                        dtype,
11676                    );
11677                    let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
11678                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11679                }
11680                Op::SignInplace | Op::FloorInplace | Op::CeilInplace | Op::RoundInplace => {
11681                    // Same backward as Op::{Sign, Floor, Ceil, Round} —
11682                    // derivative is 0 almost everywhere; drop gradient
11683                    // (no accumulation, mirroring Op::Step's pattern).
11684                }
11685                Op::ErfInplace => {
11686                    // Same backward as Op::Erf — grad_x = upstream * (2/√π) * exp(-x²).
11687                    // `Op::Sqr(x)` reads pre-mutation x via Phase 4a ordering.
11688                    const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
11689                    let x = inputs[0];
11690                    let x_shape = node_shape(&graph_handle, x);
11691                    let dtype = node_dtype(&graph_handle, x);
11692                    let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11693                    let neg_x_sq =
11694                        push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
11695                    let exp_neg = push_node(
11696                        &graph_handle,
11697                        Op::Exp,
11698                        vec![neg_x_sq],
11699                        x_shape.clone(),
11700                        dtype,
11701                    );
11702                    let scaled = push_node(
11703                        &graph_handle,
11704                        Op::MulScalar(TWO_OVER_SQRT_PI),
11705                        vec![exp_neg],
11706                        x_shape.clone(),
11707                        dtype,
11708                    );
11709                    let grad_x =
11710                        push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11711                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11712                }
11713                Op::ClampInplace { min, max } => {
11714                    // Same backward as Op::Clamp — indicator is 1 where
11715                    // min ≤ x ≤ max, 0 elsewhere. Reads pre-mutation x via
11716                    // Phase 4a ordering.
11717                    let x = inputs[0];
11718                    let x_shape = node_shape(&graph_handle, x);
11719                    let dtype = node_dtype(&graph_handle, x);
11720                    let min_shifted = push_node(
11721                        &graph_handle,
11722                        Op::AddScalar(-min),
11723                        vec![x],
11724                        x_shape.clone(),
11725                        dtype,
11726                    );
11727                    let lower_ok = push_node(
11728                        &graph_handle,
11729                        Op::Step,
11730                        vec![min_shifted],
11731                        x_shape.clone(),
11732                        dtype,
11733                    );
11734                    let neg_x = push_node(
11735                        &graph_handle,
11736                        Op::MulScalar(-1.0),
11737                        vec![x],
11738                        x_shape.clone(),
11739                        dtype,
11740                    );
11741                    let max_minus_x = push_node(
11742                        &graph_handle,
11743                        Op::AddScalar(max),
11744                        vec![neg_x],
11745                        x_shape.clone(),
11746                        dtype,
11747                    );
11748                    let upper_ok = push_node(
11749                        &graph_handle,
11750                        Op::Step,
11751                        vec![max_minus_x],
11752                        x_shape.clone(),
11753                        dtype,
11754                    );
11755                    let indicator = push_node(
11756                        &graph_handle,
11757                        Op::Mul,
11758                        vec![lower_ok, upper_ok],
11759                        x_shape.clone(),
11760                        dtype,
11761                    );
11762                    let grad_x = push_node(
11763                        &graph_handle,
11764                        Op::Mul,
11765                        vec![up_id, indicator],
11766                        x_shape,
11767                        dtype,
11768                    );
11769                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11770                }
11771                Op::PowIInplace(n) => {
11772                    // Same backward as Op::PowI — single fused
11773                    // POWI_BACKWARD node `(x, upstream) → exp · x^(exp-1) ·
11774                    // upstream`. Reads pre-mutation x via Phase 4a ordering.
11775                    let x = inputs[0];
11776                    let x_shape = node_shape(&graph_handle, x);
11777                    let dtype = node_dtype(&graph_handle, x);
11778                    let grad_x = push_node(
11779                        &graph_handle,
11780                        Op::Fused(
11781                            crate::registry::FusedOps::POWI_BACKWARD,
11782                            crate::registry::FusedOpParams::PowIBackward { exp: n },
11783                        ),
11784                        vec![x, up_id],
11785                        x_shape,
11786                        dtype,
11787                    );
11788                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11789                }
11790                Op::GeluInplace => {
11791                    // Same backward as Op::Gelu — exact-GELU derivative
11792                    // is Φ(x) + x·φ(x). Both halves read pre-mutation x via
11793                    // Phase 4a ordering. Identical 12-node chain to Op::Gelu.
11794                    const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
11795                    const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
11796                    let x = inputs[0];
11797                    let x_shape = node_shape(&graph_handle, x);
11798                    let dtype = node_dtype(&graph_handle, x);
11799                    let x_over_sqrt2 = push_node(
11800                        &graph_handle,
11801                        Op::MulScalar(INV_SQRT_2),
11802                        vec![x],
11803                        x_shape.clone(),
11804                        dtype,
11805                    );
11806                    let erf_arg = push_node(
11807                        &graph_handle,
11808                        Op::Erf,
11809                        vec![x_over_sqrt2],
11810                        x_shape.clone(),
11811                        dtype,
11812                    );
11813                    let plus_one = push_node(
11814                        &graph_handle,
11815                        Op::AddScalar(1.0),
11816                        vec![erf_arg],
11817                        x_shape.clone(),
11818                        dtype,
11819                    );
11820                    let cdf_term = push_node(
11821                        &graph_handle,
11822                        Op::MulScalar(0.5),
11823                        vec![plus_one],
11824                        x_shape.clone(),
11825                        dtype,
11826                    );
11827                    let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11828                    let half_x_sq = push_node(
11829                        &graph_handle,
11830                        Op::MulScalar(0.5),
11831                        vec![x_sq],
11832                        x_shape.clone(),
11833                        dtype,
11834                    );
11835                    let neg_half = push_node(
11836                        &graph_handle,
11837                        Op::Neg,
11838                        vec![half_x_sq],
11839                        x_shape.clone(),
11840                        dtype,
11841                    );
11842                    let exp_term = push_node(
11843                        &graph_handle,
11844                        Op::Exp,
11845                        vec![neg_half],
11846                        x_shape.clone(),
11847                        dtype,
11848                    );
11849                    let phi = push_node(
11850                        &graph_handle,
11851                        Op::MulScalar(INV_SQRT_2PI),
11852                        vec![exp_term],
11853                        x_shape.clone(),
11854                        dtype,
11855                    );
11856                    let pdf_term =
11857                        push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
11858                    let d_gelu = push_node(
11859                        &graph_handle,
11860                        Op::Add,
11861                        vec![cdf_term, pdf_term],
11862                        x_shape.clone(),
11863                        dtype,
11864                    );
11865                    let grad_x =
11866                        push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
11867                    accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11868                }
11869            }
11870        }
11871
11872        GradMap {
11873            graph: graph_handle,
11874            forward_to_grad: upstream,
11875        }
11876    }
11877}
11878
11879/// Map from forward-graph node IDs to the IDs of their accumulated
11880/// backward-graph gradient nodes, returned by [`NodeHandle::backward`].
11881///
11882/// All gradient nodes live on the same graph as the forward nodes. Getting
11883/// a gradient by calling [`GradMap::get`] returns a new [`NodeHandle`] handle
11884/// pointing at the gradient node so callers can realize it, plug it into
11885/// further computation, or back-propagate through it again.
11886pub struct GradMap {
11887    graph: SharedGraph,
11888    forward_to_grad: HashMap<NodeId, NodeId>,
11889}
11890
11891impl GradMap {
11892    /// Get the gradient tensor for a forward tensor from the same graph.
11893    ///
11894    /// Returns `None` if the forward tensor was not reachable from the
11895    /// root passed to `backward` (i.e. not part of the computation being
11896    /// differentiated).
11897    ///
11898    /// # Panics
11899    ///
11900    /// Panics if any operand belongs to a different [`Graph`] than the one this
11901    /// builder is building into. Operand identity is graph-scoped and checked by
11902    /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
11903    /// deliberate and replaces the hang a cross-graph handle used to produce.
11904    /// Build every operand from one graph, or use a `Result`-returning entry
11905    /// point where one exists.
11906    pub fn get(&self, forward: &NodeHandle) -> Option<NodeHandle> {
11907        assert!(
11908            Arc::ptr_eq(&self.graph, &forward.graph),
11909            "GradMap::get: tensor is from a different graph",
11910        );
11911        let &grad_id = self.forward_to_grad.get(&forward.id)?;
11912        Some(NodeHandle {
11913            graph: self.graph.clone(),
11914            id: grad_id,
11915        })
11916    }
11917
11918    /// Number of forward nodes that have a recorded gradient.
11919    pub fn len(&self) -> usize {
11920        self.forward_to_grad.len()
11921    }
11922
11923    /// Whether this map has no gradients (e.g. a backward over a lone const).
11924    pub fn is_empty(&self) -> bool {
11925        self.forward_to_grad.is_empty()
11926    }
11927}
11928
11929// -------- internal helpers shared by the backward pass --------------------
11930
11931/// Does the registry declare this fused op's backward to be "lower it via its
11932/// total `decompose`, then differentiate the primitives"?
11933fn lowers_for_backward(fid: crate::registry::FusedOpId) -> bool {
11934    crate::registry::default_registry()
11935        .entry(fid)
11936        .is_some_and(|e| e.backward == crate::registry::BackwardKind::Decompose)
11937}
11938
11939/// The generic decompose-backward hook (Op::Scan Phase 2, C3): before the
11940/// reverse walk takes its topo order, lower every reachable `Op::Scan` to
11941/// `bound` primitives and decompose the two SSM `Op::Fused` recipes into their
11942/// `Op::Scan` form, rewiring consumers so the walk sees only differentiable
11943/// primitives. BPTT differentiates the static-`bound` unroll (the runtime
11944/// early-exit predicate is a forward-only optimization, ignored here — spec C3
11945/// static-horizon note). Operates in place on the shared graph (a `backward()`
11946/// caller is a training step that wants the unrolled activations anyway).
11947/// Returns the (possibly remapped) root NodeId to walk from.
11948fn lower_scans_for_backward(graph: &SharedGraph, root: NodeId) -> NodeId {
11949    use std::collections::HashMap;
11950    let mut root = root;
11951    // helper: apply a remap to every consumer's inputs + the root, in place.
11952    fn apply_remap(graph: &SharedGraph, remap: &HashMap<NodeId, NodeId>, root: &mut NodeId) {
11953        if remap.is_empty() {
11954            return;
11955        }
11956        let mut g = graph.write().unwrap();
11957        let n = g.len();
11958        for nid in 0..n {
11959            let ilen = g.node(NodeId(nid)).inputs.len();
11960            for i in 0..ilen {
11961                let cur = g.node(NodeId(nid)).inputs[i];
11962                if let Some(&new) = remap.get(&cur) {
11963                    g.rewrite_input(NodeId(nid), cur, new);
11964                }
11965            }
11966        }
11967        if let Some(&new) = remap.get(root) {
11968            *root = new;
11969        }
11970    }
11971
11972    // --- Pass 1: decompose every reachable Op::Fused whose registry entry declares
11973    // `BackwardKind::Decompose` (the SSM recipes into Op::Scan, which pass 2 then
11974    // unrolls; single-output recipes such as NF4/AWQ matmul and causal conv1d
11975    // straight to primitives). The registry is the source of truth: an id with
11976    // a hand-written backward arm in the reverse walk is `Fused(..)` or
11977    // `NotDifferentiable` there, never `Decompose`.
11978    {
11979        let targets: Vec<(
11980            NodeId,
11981            crate::registry::FusedOpId,
11982            crate::registry::FusedOpParams,
11983        )> = {
11984            let g = graph.read().unwrap();
11985            crate::topo_order(&g, root)
11986                .into_iter()
11987                .filter_map(|id| match &g.node(id).op {
11988                    Op::Fused(fid, params) if lowers_for_backward(*fid) => {
11989                        Some((id, *fid, params.clone()))
11990                    }
11991                    _ => None,
11992                })
11993                .collect()
11994        };
11995        let mut remap = HashMap::new();
11996        for (id, fid, params) in targets {
11997            if let Some(entry) = crate::registry::default_registry().entry(fid) {
11998                let y = {
11999                    let mut g = graph.write().unwrap();
12000                    (entry.decompose)(&mut g, id, &params)
12001                };
12002                if y != id {
12003                    remap.insert(id, y);
12004                    // Collapse the fused node's slot-0 View consumers DIRECTLY to
12005                    // the decompose output. Slot 0 is the primary value (the
12006                    // multi-output authoring contract: Node.shape == slot-0
12007                    // shape), and the SSM decompose re-presents its primary AS
12008                    // slot 0, so `View{0}(y) == y`. Without this collapse the
12009                    // outer View{0} survives into the reverse walk and emits an
12010                    // `Op::ScatterIntoSlot` (which has no CPU realize kernel),
12011                    // so realizing the gradient would fail. Slot-1 (last_state)
12012                    // consumers keep their `View{1}(y)` re-projection via the
12013                    // default input rewrite (remap[id] = y) and are not
12014                    // differentiated on this path.
12015                    let g = graph.read().unwrap();
12016                    for nid in 0..g.len() {
12017                        let node = g.node(NodeId(nid));
12018                        if let Op::View { slot: 0 } | Op::ViewOwned { slot: 0 } = node.op
12019                            && node.inputs.first() == Some(&id)
12020                        {
12021                            remap.insert(NodeId(nid), y);
12022                        }
12023                    }
12024                }
12025            }
12026        }
12027        apply_remap(graph, &remap, &mut root);
12028    }
12029
12030    // --- Pass 2: unroll every reachable Op::Scan to `bound` primitives.
12031    loop {
12032        let scans: Vec<(NodeId, usize, ScanEmit)> = {
12033            let g = graph.read().unwrap();
12034            crate::topo_order(&g, root)
12035                .into_iter()
12036                .filter_map(|id| match &g.node(id).op {
12037                    Op::Scan { bound, emit, .. } => Some((id, *bound, *emit)),
12038                    _ => None,
12039                })
12040                .collect()
12041        };
12042        if scans.is_empty() {
12043            break;
12044        }
12045        let mut remap = HashMap::new();
12046        for (scan_id, bound, emit) in scans {
12047            let (a, b) = {
12048                let mut g = graph.write().unwrap();
12049                match crate::scan::unroll_scan(&mut g, scan_id, bound) {
12050                    Ok(pair) => pair,
12051                    Err(_) => continue, // malformed scan: leave it; the C4 guard describes it.
12052                }
12053            };
12054            // Normalize to (slot 0 = stacked_ys, slots 1.. = final carries).
12055            //
12056            // GAP-303: `unroll_scan` now returns (selected, complementary) as
12057            // VECS. The `ys` side is always exactly one node; the carry side is
12058            // `n_carries` wide. At `n_carries == 1` this is byte-for-byte the old
12059            // behaviour -- one ys, one carry, slot 1 the only carry slot.
12060            let (ys_v, carries) = match emit {
12061                ScanEmit::All => (a, b),
12062                ScanEmit::Final => (b, a),
12063            };
12064            let Some(&slot0) = ys_v.first() else {
12065                continue; // malformed: no stacked ys; the C4 guard describes it.
12066            };
12067            // Remap the scan's View{slot}/ViewOwned{slot} consumers to the unroll outputs.
12068            let g = graph.read().unwrap();
12069            for nid in 0..g.len() {
12070                let node = g.node(NodeId(nid));
12071                if let Op::View { slot } | Op::ViewOwned { slot } = node.op
12072                    && node.inputs.first() == Some(&scan_id)
12073                {
12074                    // ⚠️ Slot 0 is `ys`; slot k>=1 is carry k-1. The old form was
12075                    // `if slot == 0 { slot0 } else { slot1 }`, which folded EVERY
12076                    // slot above 0 onto the single carry -- a fifth site of the
12077                    // 2-slot assumption. Out-of-range slots are LEFT UNMAPPED for
12078                    // the C4 guard rather than indexed (never-panic).
12079                    let target = if slot == 0 {
12080                        Some(slot0)
12081                    } else {
12082                        carries.get(slot as usize - 1).copied()
12083                    };
12084                    if let Some(t) = target {
12085                        remap.insert(NodeId(nid), t);
12086                    }
12087                }
12088            }
12089        }
12090        // Defensive never-hang guard: if a full pass lowered no scan to a
12091        // consumer remap (e.g. a malformed scan that unroll rejects, or a raw
12092        // scan producer with no View consumers), stop rather than re-scanning
12093        // the same unchanged graph forever. Any residual Op::Scan then reaches
12094        // the C4 defensive `panic!` guard (backward is infallible, so it cannot
12095        // return an error) — an internal-bug signal, never an infinite loop.
12096        if remap.is_empty() {
12097            break;
12098        }
12099        apply_remap(graph, &remap, &mut root);
12100        // Unrolled graphs contain no Op::Scan, so a well-formed graph terminates
12101        // in <= 2 iterations (the loop re-scans in case a decomposed body itself
12102        // contained a scan; the current SSM decompose does not).
12103    }
12104    root
12105}
12106
12107/// Read a node's shape without holding the borrow past the call site.
12108fn node_shape(graph: &SharedGraph, id: NodeId) -> Shape {
12109    graph.read().unwrap().node(id).shape.clone()
12110}
12111
12112/// Read a node's dtype without holding the borrow past the call site.
12113fn node_dtype(graph: &SharedGraph, id: NodeId) -> DType {
12114    graph.read().unwrap().node(id).dtype
12115}
12116
12117/// Shape with its last two dims swapped. Used by MatMul's backward rule
12118/// to construct transpose-node output shapes for any rank ≥ 2.
12119fn transposed_shape(shape: &Shape) -> Shape {
12120    let d = shape.dims();
12121    assert!(
12122        d.len() >= 2,
12123        "transposed_shape: expected rank ≥ 2, got {d:?}",
12124    );
12125    let rank = d.len();
12126    let mut out: Vec<usize> = d.to_vec();
12127    out.swap(rank - 2, rank - 1);
12128    Shape::from_dims(&out)
12129}
12130
12131/// Given a full tensor shape and a dim that was reduced away, produce the
12132/// keepdim shape — i.e. the full shape with size 1 at `dim`. Used by
12133/// axis-reduction backward rules to reshape the reduced upstream back to
12134/// a shape that broadcasts against the original input.
12135fn reshape_to_keepdim(full_dims: &[usize], dim: usize) -> Shape {
12136    assert!(
12137        dim < full_dims.len(),
12138        "reshape_to_keepdim: dim {dim} out of bounds for {full_dims:?}",
12139    );
12140    let mut out: Vec<usize> = full_dims.to_vec();
12141    out[dim] = 1;
12142    Shape::from_dims(&out)
12143}
12144
12145/// Validate that `src` can be broadcast to `dst` using NumPy rules:
12146/// right-align, pad the shorter shape with 1s on the left, and for each
12147/// aligned dimension the src size must equal the dst size or be 1.
12148fn check_broadcast_compatible(src: &[usize], dst: &[usize]) {
12149    assert!(
12150        src.len() <= dst.len(),
12151        "broadcast_to: source rank {} exceeds target rank {}",
12152        src.len(),
12153        dst.len(),
12154    );
12155    let pad = dst.len() - src.len();
12156    for (i, &s) in src.iter().enumerate() {
12157        let d = dst[pad + i];
12158        assert!(
12159            s == d || s == 1,
12160            "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
12161            pad + i,
12162        );
12163    }
12164}
12165
12166/// Result-returning sibling of [`check_broadcast_compatible`].
12167fn try_check_broadcast_compatible(
12168    src: &[usize],
12169    dst: &[usize],
12170) -> std::result::Result<(), fuel_ir::Error> {
12171    if src.len() > dst.len() {
12172        return Err(fuel_ir::Error::Msg(format!(
12173            "broadcast_to: source rank {} exceeds target rank {}",
12174            src.len(),
12175            dst.len(),
12176        ))
12177        .bt());
12178    }
12179    let pad = dst.len() - src.len();
12180    for (i, &s) in src.iter().enumerate() {
12181        let d = dst[pad + i];
12182        if s != d && s != 1 {
12183            return Err(fuel_ir::Error::Msg(format!(
12184                "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
12185                pad + i,
12186            ))
12187            .bt());
12188        }
12189    }
12190    Ok(())
12191}
12192
12193/// Compute the NumPy broadcast shape of two input shapes. Right-align,
12194/// pad the shorter with leading 1s, and take the element-wise max at
12195/// each position. Panics if the shapes are incompatible (neither can
12196/// expand to match the other at some dim).
12197fn compute_broadcast_shape(a: &[usize], b: &[usize]) -> Vec<usize> {
12198    let n = a.len().max(b.len());
12199    let a_pad = n - a.len();
12200    let b_pad = n - b.len();
12201    let mut out = Vec::with_capacity(n);
12202    for i in 0..n {
12203        let ai = if i < a_pad { 1 } else { a[i - a_pad] };
12204        let bi = if i < b_pad { 1 } else { b[i - b_pad] };
12205        let oi = if ai == bi {
12206            ai
12207        } else if ai == 1 {
12208            bi
12209        } else if bi == 1 {
12210            ai
12211        } else {
12212            panic!(
12213                "compute_broadcast_shape: incompatible shapes {a:?} vs {b:?} at axis {i}: {ai} vs {bi}",
12214            );
12215        };
12216        out.push(oi);
12217    }
12218    out
12219}
12220
12221/// Push a node to the graph and return its ID. Used by backward to append
12222/// gradient-computing nodes without going through the public builders,
12223/// which would re-validate shapes the backward pass has already derived.
12224fn push_node(
12225    graph: &SharedGraph,
12226    op: Op,
12227    inputs: Vec<NodeId>,
12228    shape: Shape,
12229    dtype: DType,
12230) -> NodeId {
12231    graph.write().unwrap().push(Node {
12232        op,
12233        inputs,
12234        shape,
12235        dtype,
12236    })
12237}
12238
12239/// Build a ones tensor of the given shape and dtype as a `Const` node.
12240/// Used to seed the initial upstream gradient at the root of the backward
12241/// pass (`dL/dL = 1`).
12242/// Backward of the tanh-approximation GELU, `y = 0.5 x (1 + tanh(u))` with
12243/// `u = c (x + k x^3)`, `c = sqrt(2/pi)`, `k = 0.044715`:
12244///
12245/// `dy/dx = 0.5 (1 + t) + 0.5 x (1 - t^2) c (1 + 3 k x^2)`, `t = tanh(u)`.
12246///
12247/// Returns `upstream * dy/dx` as a new node. Built from existing primitives
12248/// (no new Op); `t` is recomputed from `x` so the rule is safe at `x = 0`.
12249fn build_gelu_tanh_grad(graph: &SharedGraph, x: NodeId, upstream: NodeId) -> NodeId {
12250    // sqrt(2/pi), the constant the forward kernels use.
12251    const C: f64 = 0.797_884_560_802_865_4;
12252    const K: f64 = 0.044_715;
12253    let shape = node_shape(graph, x);
12254    let dtype = node_dtype(graph, x);
12255    let un = |op: Op, input: NodeId| push_node(graph, op, vec![input], shape.clone(), dtype);
12256    let x_sq = un(Op::Sqr, x);
12257    let x_cu = push_node(graph, Op::Mul, vec![x_sq, x], shape.clone(), dtype);
12258    let k_x_cu = un(Op::MulScalar(K), x_cu);
12259    let inner = push_node(graph, Op::Add, vec![x, k_x_cu], shape.clone(), dtype);
12260    let u = un(Op::MulScalar(C), inner);
12261    let t = un(Op::Tanh, u);
12262    // 0.5 (1 + t)
12263    let t_plus_one = un(Op::AddScalar(1.0), t);
12264    let half_one_plus_t = un(Op::MulScalar(0.5), t_plus_one);
12265    // 1 - t^2
12266    let t_sq = un(Op::Sqr, t);
12267    let ones = build_ones(graph, shape.clone(), dtype);
12268    let one_minus_t_sq = push_node(graph, Op::Sub, vec![ones, t_sq], shape.clone(), dtype);
12269    // du/dx = c + 3 c k x^2
12270    let scaled_x_sq = un(Op::MulScalar(3.0 * C * K), x_sq);
12271    let du = un(Op::AddScalar(C), scaled_x_sq);
12272    // 0.5 x (1 - t^2) du/dx
12273    let dt = push_node(
12274        graph,
12275        Op::Mul,
12276        vec![one_minus_t_sq, du],
12277        shape.clone(),
12278        dtype,
12279    );
12280    let x_dt = push_node(graph, Op::Mul, vec![x, dt], shape.clone(), dtype);
12281    let half_x_dt = un(Op::MulScalar(0.5), x_dt);
12282    let d_gelu = push_node(
12283        graph,
12284        Op::Add,
12285        vec![half_one_plus_t, half_x_dt],
12286        shape.clone(),
12287        dtype,
12288    );
12289    push_node(graph, Op::Mul, vec![upstream, d_gelu], shape, dtype)
12290}
12291
12292fn build_ones(graph: &SharedGraph, shape: Shape, dtype: DType) -> NodeId {
12293    build_filled_const(graph, shape, dtype, 1.0)
12294}
12295
12296/// Build a constant tensor of the given shape and dtype filled with
12297/// `value` (expressed as `f64` and converted to the target dtype). Used
12298/// by backward rules that need a scalar-valued broadcast, for example
12299/// `MeanAll`'s `1/n` factor expressed as "divide by an n-filled const."
12300///
12301/// Build RoPE cos/sin tables for a given `(base, start_pos, seq,
12302/// head_dim)`. Each returned `Vec<f32>` has shape `[seq, head_dim]`
12303/// (row-major) in the half-split layout [`NodeHandle::rope_with_tables`]
12304/// expects: positions `[:, :half]` and `[:, half:]` hold the same
12305/// value for the same `(p, i)`, so a single elementwise multiply with
12306/// `self` does the right thing alongside `rotate_half(self) * sin`.
12307///
12308/// Exposed as a free function so callers can share the tables across
12309/// many RoPE applications (e.g. every attention layer in a transformer
12310/// forward pass).
12311pub fn build_rope_tables(
12312    base: f64,
12313    start_pos: usize,
12314    seq: usize,
12315    head_dim: usize,
12316) -> (Vec<f32>, Vec<f32>) {
12317    assert!(
12318        head_dim.is_multiple_of(2),
12319        "build_rope_tables: head_dim {head_dim} must be even",
12320    );
12321    let half = head_dim / 2;
12322    let inv_freq: Vec<f64> = (0..half)
12323        .map(|i| base.powf(-2.0 * (i as f64) / (head_dim as f64)))
12324        .collect();
12325    build_rope_tables_with_inv_freq(&inv_freq, start_pos, seq, head_dim)
12326}
12327
12328/// [`build_rope_tables`] with the inverse frequencies supplied directly rather
12329/// than derived from a single `base`.
12330///
12331/// Every RoPE variant Fuel supports differs from the default in **exactly** this
12332/// vector: LLaMA-3.1's long-context scaling is a per-dimension transform of the
12333/// same `head_dim / 2` values, and the position loop below is bit-identical
12334/// either way. Splitting the frequency choice out is what lets a scaled model
12335/// reuse the whole decode path — the KV-cache forward, the held-graph persistent
12336/// forward, and their per-token rebinds — instead of needing a parallel copy of
12337/// each.
12338///
12339/// `inv_freq.len()` must be `head_dim / 2`.
12340pub fn build_rope_tables_with_inv_freq(
12341    inv_freq: &[f64],
12342    start_pos: usize,
12343    seq: usize,
12344    head_dim: usize,
12345) -> (Vec<f32>, Vec<f32>) {
12346    assert!(
12347        head_dim.is_multiple_of(2),
12348        "build_rope_tables_with_inv_freq: head_dim {head_dim} must be even",
12349    );
12350    let half = head_dim / 2;
12351    assert_eq!(
12352        inv_freq.len(),
12353        half,
12354        "build_rope_tables_with_inv_freq: inv_freq len {} != head_dim/2 {half}",
12355        inv_freq.len(),
12356    );
12357    let mut cos_data = vec![0.0_f32; seq * head_dim];
12358    let mut sin_data = vec![0.0_f32; seq * head_dim];
12359    for p in 0..seq {
12360        let pos = (start_pos + p) as f64;
12361        for (i, &freq) in inv_freq.iter().enumerate() {
12362            let theta = pos * freq;
12363            let c = theta.cos() as f32;
12364            let s = theta.sin() as f32;
12365            cos_data[p * head_dim + i] = c;
12366            cos_data[p * head_dim + i + half] = c;
12367            sin_data[p * head_dim + i] = s;
12368            sin_data[p * head_dim + i + half] = s;
12369        }
12370    }
12371    (cos_data, sin_data)
12372}
12373
12374/// Only float dtypes are supported here — integer/index tensors never
12375/// appear as gradients, so a `U32` call indicates a bug in a backward
12376/// rule rather than a missing feature.
12377///
12378/// Phase 7.5 G2: gradient consts are slot-populating Op::Const
12379/// nodes. Device is picked from any existing slot (the forward pass
12380/// always populated at least one slot-bearing leaf by the time
12381/// backward runs). For a CPU-rooted graph the device's
12382/// `storage_from_host_buffer_owned_dyn` is a zero-copy wrap; for
12383/// GPU-rooted, an H2D upload (matching today's eval_const path on
12384/// first realize).
12385fn build_filled_const(graph: &SharedGraph, shape: Shape, dtype: DType, value: f64) -> NodeId {
12386    let n = shape.elem_count();
12387    let buf = match dtype {
12388        DType::F32 => fuel_ir::HostBuffer::F32(vec![value as f32; n]),
12389        DType::F64 => fuel_ir::HostBuffer::F64(vec![value; n]),
12390        DType::BF16 => fuel_ir::HostBuffer::BF16(vec![fuel_ir::round::bf16_from_f64(value); n]),
12391        DType::F16 => fuel_ir::HostBuffer::F16(vec![fuel_ir::round::f16_from_f64(value); n]),
12392        other => panic!(
12393            "backward: build_filled_const: unsupported dtype {other:?} \
12394             (gradients are always floats — this would indicate a bug in \
12395             a backward rule that tried to differentiate through an \
12396             integer tensor)",
12397        ),
12398    };
12399    let device = pick_device_from_graph(graph);
12400    let backend_storage = device
12401        .storage_from_host_buffer_owned_dyn(buf)
12402        .expect("build_filled_const: storage_from_host_buffer_owned_dyn failed");
12403    let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
12404    let id = push_node(graph, Op::Const, vec![], shape, dtype);
12405    graph.write().unwrap().set_storage(id, storage_arc);
12406    id
12407}
12408
12409/// G2 helper: walk the graph for any populated slot and return its
12410/// device. Used by gradient builders that don't have an explicit
12411/// device parameter — the graph always has at least one slot-bearing
12412/// Const leaf by the time backward() runs (the forward pass's inputs
12413/// are slot-rooted Const leaves), so this can be relied on.
12414fn pick_device_from_graph(graph: &SharedGraph) -> Arc<dyn fuel_backend_contract::DynBackendDevice> {
12415    let g = graph.read().unwrap();
12416    for i in 0..g.len() {
12417        if let Some(slot_arc) = g.storage_for(NodeId(i)) {
12418            return slot_arc.read().unwrap().device();
12419        }
12420    }
12421    panic!(
12422        "build_filled_const: graph has no populated storage slots; backward \
12423         requires at least one slot-bearing Const leaf to pick a gradient \
12424         device from. Was the forward pass built with G2-migrated \
12425         constructors (from_f32/etc. with explicit &Device)?"
12426    )
12427}
12428
12429/// Accumulate a new gradient contribution into the upstream map.
12430///
12431/// If `forward_id` already has an upstream gradient, emit an `Add` node to
12432/// sum the two contributions. If not, record the new one as-is. This is
12433/// the multi-variable chain rule in its operational form: when a forward
12434/// node has multiple downstream consumers, the gradients from each must
12435/// be summed.
12436fn accumulate_grad(
12437    upstream: &mut HashMap<NodeId, NodeId>,
12438    forward_id: NodeId,
12439    new_grad_id: NodeId,
12440    graph: &SharedGraph,
12441) {
12442    match upstream.get(&forward_id).copied() {
12443        None => {
12444            upstream.insert(forward_id, new_grad_id);
12445        }
12446        Some(existing_id) => {
12447            let shape = node_shape(graph, forward_id);
12448            let dtype = node_dtype(graph, forward_id);
12449            let combined = push_node(graph, Op::Add, vec![existing_id, new_grad_id], shape, dtype);
12450            upstream.insert(forward_id, combined);
12451        }
12452    }
12453}
12454
12455#[cfg(test)]
12456mod tests {
12457    use super::*;
12458
12459    /// Phase 7.5 G2: tests need a real device to allocate slot
12460    /// storage through the new constructor API. `cpu_dev()` returns a
12461    /// stable singleton CpuBackendDevice handle so every call site can
12462    /// just pass `cpu_dev()` without per-test boilerplate.
12463    fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
12464        static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
12465            std::sync::OnceLock::new();
12466        D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
12467    }
12468
12469    /// Operands for a `[2, 64]` activation, `N = 8`, `group_size = 64`
12470    /// (`zeros_w = 2`): weight `[8, 8]` U32, zeros `[8, 2]` U32, scales
12471    /// `[8, 16]` of `scale_dtype`-compatible data.
12472    fn awq_builder_operands(
12473        act: &NodeHandle,
12474        weight_f32: bool,
12475    ) -> (NodeHandle, NodeHandle, NodeHandle) {
12476        let weight = if weight_f32 {
12477            act.const_f32_like(vec![0.0_f32; 64], Shape::from_dims(&[8, 8]))
12478                .unwrap()
12479        } else {
12480            act.const_u32_like(vec![0u32; 64], Shape::from_dims(&[8, 8]))
12481                .unwrap()
12482        };
12483        let zeros = act
12484            .const_u32_like(vec![0u32; 16], Shape::from_dims(&[8, 2]))
12485            .unwrap();
12486        let scales = act
12487            .const_f16_like(vec![f16::ONE; 128], Shape::from_dims(&[8, 16]))
12488            .unwrap();
12489        (weight, zeros, scales)
12490    }
12491
12492    /// `Tensor::awq_matmul`'s public builder end-to-end: a well-formed call
12493    /// produces a `Fused(AWQ_MATMUL, ..)` node with the right output
12494    /// shape/dtype. The decompose MATH is tested at the registry level
12495    /// (`registry::awq_matmul::tests`); this just confirms the builder's
12496    /// own validation + node construction work from the public API.
12497    #[test]
12498    fn awq_matmul_builder_produces_expected_node() {
12499        let act =
12500            NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12501                .unwrap();
12502        let (weight, zeros, scales) = awq_builder_operands(&act, false);
12503        let out = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12504        assert_eq!(out.shape().dims(), &[2, 8]);
12505        assert_eq!(out.dtype(), DType::F32);
12506        assert!(matches!(
12507            out.graph.read().unwrap().node(out.id).op,
12508            Op::Fused(id, _) if id == crate::registry::FusedOps::AWQ_MATMUL
12509        ));
12510    }
12511
12512    /// Born-red: a non-U32 `weight` must panic with a clear message, not
12513    /// silently misinterpret bytes.
12514    #[test]
12515    #[should_panic(expected = "weight must be U32")]
12516    fn awq_matmul_builder_panics_on_wrong_weight_dtype() {
12517        let act =
12518            NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12519                .unwrap();
12520        let (weight, zeros, scales) = awq_builder_operands(&act, true);
12521        let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12522    }
12523
12524    /// Born-red: F32 `scales` (the previous layout) must be refused, since the
12525    /// kernel reads F16.
12526    #[test]
12527    #[should_panic(expected = "scales must be F16")]
12528    fn awq_matmul_builder_panics_on_f32_scales() {
12529        let act =
12530            NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12531                .unwrap();
12532        let (weight, zeros, _) = awq_builder_operands(&act, false);
12533        let scales = act
12534            .const_f32_like(vec![1.0_f32; 128], Shape::from_dims(&[8, 16]))
12535            .unwrap();
12536        let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12537    }
12538
12539    /// Born-red: `zeros` at the un-padded width (`ceil(groups / 8) = 1`, the
12540    /// kernel pads to 2) must be refused.
12541    #[test]
12542    #[should_panic(expected = "zeros [8, 1] must be")]
12543    fn awq_matmul_builder_panics_on_unpadded_zeros() {
12544        let act =
12545            NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12546                .unwrap();
12547        let (weight, _, scales) = awq_builder_operands(&act, false);
12548        let zeros = act
12549            .const_u32_like(vec![0u32; 8], Shape::from_dims(&[8, 1]))
12550            .unwrap();
12551        let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12552    }
12553
12554    #[test]
12555    fn builders_agree_with_primitive_shape() {
12556        // No-drift guard (Convergence A, Task 6): every routed builder's output
12557        // shape/dtype must equal primitive_shape's answer for the same Op. If a
12558        // builder's inline math ever diverged from primitive_shape, this fails.
12559        let x = NodeHandle::from_f32(
12560            vec![0.0_f32; 2 * 3 * 4],
12561            Shape::from_dims(&[2, 3, 4]),
12562            cpu_dev(),
12563        )
12564        .unwrap();
12565        let checks: Vec<(NodeHandle, Op)> = vec![
12566            (
12567                x.slice(1, 0, 2),
12568                Op::Slice {
12569                    dim: 1,
12570                    start: 0,
12571                    len: 2,
12572                },
12573            ),
12574            (x.mean_dim(2), Op::MeanDim(2)),
12575            (
12576                x.try_permute(&[2, 0, 1]).unwrap(),
12577                Op::Permute(vec![2, 0, 1]),
12578            ),
12579            (x.cast(DType::F16), Op::Cast(DType::F16)),
12580        ];
12581        for (t, op) in checks {
12582            let (ps_shape, ps_dtype) =
12583                crate::shape::primitive_shape(&op, &[x.shape()], &[x.dtype()]).unwrap();
12584            assert_eq!(t.shape(), ps_shape, "shape drift for {op:?}");
12585            assert_eq!(t.dtype(), ps_dtype, "dtype drift for {op:?}");
12586        }
12587    }
12588
12589    #[test]
12590    fn destructive_input_release_is_some_zero() {
12591        assert_eq!(Op::Release.destructive_input(), Some(0));
12592    }
12593
12594    /// Phase 7.5 storage-unification B2: target_backend side-table
12595    /// is sparse — empty by default, set explicitly per node.
12596    #[test]
12597    fn target_backend_side_table_starts_empty() {
12598        let mut g = Graph::new();
12599        let id = g.push(Node {
12600            op: Op::Const,
12601            inputs: vec![],
12602            shape: Shape::from_dims(&[1]),
12603            dtype: DType::F32,
12604        });
12605        assert_eq!(g.target_backend(id), None);
12606        assert_eq!(g.target_backend_count(), 0);
12607    }
12608
12609    /// set_target_backend then read returns the same value.
12610    #[test]
12611    fn target_backend_set_and_read() {
12612        let mut g = Graph::new();
12613        let id = g.push(Node {
12614            op: Op::Const,
12615            inputs: vec![],
12616            shape: Shape::from_dims(&[1]),
12617            dtype: DType::F32,
12618        });
12619        g.set_target_backend(id, BackendId::Cpu);
12620        assert_eq!(g.target_backend(id), Some(BackendId::Cpu));
12621        assert_eq!(g.target_backend_count(), 1);
12622    }
12623
12624    /// set_target_backend overwrites prior value.
12625    #[test]
12626    fn target_backend_overwrite() {
12627        let mut g = Graph::new();
12628        let id = g.push(Node {
12629            op: Op::Const,
12630            inputs: vec![],
12631            shape: Shape::from_dims(&[1]),
12632            dtype: DType::F32,
12633        });
12634        g.set_target_backend(id, BackendId::Cpu);
12635        g.set_target_backend(id, BackendId::Cuda);
12636        assert_eq!(g.target_backend(id), Some(BackendId::Cuda));
12637        assert_eq!(g.target_backend_count(), 1);
12638    }
12639
12640    /// Layouts side-table: default fallback returns
12641    /// `Layout::contiguous(node.shape)` for any node without an
12642    /// explicit entry.
12643    #[test]
12644    fn layout_default_is_contiguous_over_node_shape() {
12645        let mut g = Graph::new();
12646        let id = g.push(Node {
12647            op: Op::Const,
12648            inputs: vec![],
12649            shape: Shape::from_dims(&[2, 3]),
12650            dtype: DType::F32,
12651        });
12652        assert!(!g.has_explicit_layout(id));
12653        assert_eq!(g.explicit_layout_count(), 0);
12654        let l = g.layout(id);
12655        assert_eq!(l.shape().dims(), &[2, 3]);
12656        assert!(l.is_contiguous());
12657        assert_eq!(l.start_offset(), 0);
12658    }
12659
12660    /// set_layout records a strided Layout (e.g. for a transpose
12661    /// view). Subsequent reads return the explicit entry.
12662    #[test]
12663    fn layout_explicit_strided_is_remembered() {
12664        let mut g = Graph::new();
12665        let id = g.push(Node {
12666            op: Op::Transpose,
12667            inputs: vec![],
12668            shape: Shape::from_dims(&[3, 2]),
12669            dtype: DType::F32,
12670        });
12671        // Strided view: shape stays [3, 2] (the post-transpose view),
12672        // strides are [1, 3] (row-of-output is column-of-source).
12673        let l = Layout::new(
12674            Shape::from_dims(&[3, 2]),
12675            fuel_ir::StrideVec::from_slice(&[1_isize, 3]),
12676            0,
12677        );
12678        g.set_layout(id, l);
12679        assert!(g.has_explicit_layout(id));
12680        assert_eq!(g.explicit_layout_count(), 1);
12681        assert_eq!(g.layout(id).stride(), &[1, 3]);
12682        assert!(!g.layout(id).is_contiguous());
12683    }
12684
12685    /// set_layout twice with different layouts overwrites.
12686    #[test]
12687    fn layout_set_overwrites() {
12688        use fuel_ir::StrideVec;
12689        let mut g = Graph::new();
12690        let id = g.push(Node {
12691            op: Op::Transpose,
12692            inputs: vec![],
12693            shape: Shape::from_dims(&[2]),
12694            dtype: DType::F32,
12695        });
12696        g.set_layout(id, Layout::contiguous(Shape::from_dims(&[2])));
12697        g.set_layout(
12698            id,
12699            Layout::new(Shape::from_dims(&[2]), StrideVec::from_slice(&[3_isize]), 1),
12700        );
12701        assert_eq!(g.layout(id).start_offset(), 1);
12702        assert_eq!(g.explicit_layout_count(), 1);
12703    }
12704
12705    /// Phase 7.5 work item G — empty-map invariants. End-to-end
12706    /// tests of the storage map (with real `Storage` values) live in
12707    /// fuel-core's `tensor::node_handle_tests`, since constructing a
12708    /// real `Storage` requires a `DynBackendStorage` implementation
12709    /// from a backend crate, and fuel-graph deliberately depends only
12710    /// on fuel-core-types.
12711    #[test]
12712    fn graph_storage_map_starts_empty() {
12713        let g = Graph::new();
12714        assert_eq!(g.storage_len(), 0);
12715        assert!(!g.has_storage(NodeId(0)));
12716        assert!(g.storage_for(NodeId(0)).is_none());
12717    }
12718
12719    #[test]
12720    fn conv2d_builder_emits_conv2d_node_with_right_shape() {
12721        // k=3 s=1 p=1 keeps H and W.
12722        let x = NodeHandle::from_f32(
12723            vec![0.0_f32; 2 * 4 * 4],
12724            Shape::from_dims(&[1, 2, 4, 4]),
12725            cpu_dev(),
12726        )
12727        .unwrap();
12728        let w = x
12729            .const_f32_like(
12730                vec![0.0_f32; 3 * 2 * 3 * 3],
12731                Shape::from_dims(&[3, 2, 3, 3]),
12732            )
12733            .unwrap();
12734        let b = x
12735            .const_f32_like(vec![0.0_f32; 3], Shape::from_dims(&[3]))
12736            .unwrap();
12737        let y = x.conv2d(&w, Some(&b), (1, 1), (1, 1), 1);
12738        assert_eq!(y.shape().dims(), &[1, 3, 4, 4]);
12739    }
12740
12741    #[test]
12742    fn conv2d_builder_stride_and_no_padding() {
12743        // k=3 s=2 p=0 on H=W=8 gives (8-3)/2+1 = 3.
12744        let x = NodeHandle::from_f32(
12745            vec![0.0_f32; 2 * 8 * 8],
12746            Shape::from_dims(&[1, 2, 8, 8]),
12747            cpu_dev(),
12748        )
12749        .unwrap();
12750        let w = x
12751            .const_f32_like(
12752                vec![0.0_f32; 4 * 2 * 3 * 3],
12753                Shape::from_dims(&[4, 2, 3, 3]),
12754            )
12755            .unwrap();
12756        let y = x.conv2d(&w, None, (2, 2), (0, 0), 1);
12757        assert_eq!(y.shape().dims(), &[1, 4, 3, 3]);
12758    }
12759
12760    #[test]
12761    fn conv2d_builder_depthwise_groups() {
12762        // groups=Cin=Cout=4 is the depthwise case. Weight per channel is [Cin/groups=1, kH, kW].
12763        let x = NodeHandle::from_f32(
12764            vec![0.0_f32; 4 * 4 * 4],
12765            Shape::from_dims(&[1, 4, 4, 4]),
12766            cpu_dev(),
12767        )
12768        .unwrap();
12769        let w = x
12770            .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 1, 3, 3]))
12771            .unwrap();
12772        let y = x.conv2d(&w, None, (1, 1), (1, 1), 4);
12773        assert_eq!(y.shape().dims(), &[1, 4, 4, 4]);
12774    }
12775
12776    #[test]
12777    fn conv_transpose2d_builder_emits_node_with_right_shape() {
12778        // Hin=4, Kh=3, s=2, pad=1, out_pad=1 → Hout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12779        let x = NodeHandle::from_f32(
12780            vec![0.0_f32; 2 * 4 * 4],
12781            Shape::from_dims(&[1, 2, 4, 4]),
12782            cpu_dev(),
12783        )
12784        .unwrap();
12785        let w = x
12786            .const_f32_like(
12787                vec![0.0_f32; 2 * 3 * 3 * 3],
12788                Shape::from_dims(&[2, 3, 3, 3]),
12789            )
12790            .unwrap();
12791        let y = x.conv_transpose2d(&w, (2, 2), (1, 1), (1, 1), (1, 1), 1);
12792        assert_eq!(y.shape().dims(), &[1, 3, 8, 8]);
12793    }
12794
12795    #[test]
12796    fn conv_transpose1d_builder_shape_stride_2_pad_1() {
12797        // Lin=4, K=3, s=2, pad=1, out_pad=1, dil=1
12798        // Lout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12799        let x = NodeHandle::from_f32(
12800            vec![0.0_f32; 2 * 4],
12801            Shape::from_dims(&[1, 2, 4]),
12802            cpu_dev(),
12803        )
12804        .unwrap();
12805        let w = x
12806            .const_f32_like(vec![0.0_f32; 2 * 3 * 3], Shape::from_dims(&[2, 3, 3]))
12807            .unwrap();
12808        let y = x.conv_transpose1d(&w, 2, 1, 1, 1, 1);
12809        assert_eq!(y.shape().dims(), &[1, 3, 8]);
12810    }
12811
12812    #[test]
12813    fn conv_transpose1d_builder_shape_stride_4_no_pad() {
12814        // Lin=2, K=4, s=4, pad=0, out_pad=0, dil=1
12815        // Lout = (2-1)*4 + (4-1) + 0 + 1 - 0 = 8.
12816        let x = NodeHandle::from_f32(vec![0.0_f32; 2], Shape::from_dims(&[1, 1, 2]), cpu_dev())
12817            .unwrap();
12818        let w = x
12819            .const_f32_like(vec![0.0_f32; 4], Shape::from_dims(&[1, 1, 4]))
12820            .unwrap();
12821        let y = x.conv_transpose1d(&w, 4, 0, 0, 1, 1);
12822        assert_eq!(y.shape().dims(), &[1, 1, 8]);
12823    }
12824
12825    #[test]
12826    fn conv_transpose1d_builder_with_groups() {
12827        // groups=2: input Cin=4 splits into 2 groups of 2; weight
12828        // Cin=4 first dim matches input; Cout/group=3 → total Cout=6.
12829        // Lin=3, K=3, s=1, pad=0, out_pad=0, dil=1 → Lout = (3-1)*1 + 2 + 0 + 1 = 5.
12830        let x = NodeHandle::from_f32(
12831            vec![0.0_f32; 4 * 3],
12832            Shape::from_dims(&[1, 4, 3]),
12833            cpu_dev(),
12834        )
12835        .unwrap();
12836        let w = x
12837            .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 3, 3]))
12838            .unwrap();
12839        let y = x.conv_transpose1d(&w, 1, 0, 0, 1, 2);
12840        assert_eq!(y.shape().dims(), &[1, 6, 5]);
12841    }
12842
12843    #[test]
12844    fn conv2d_backward_grads_have_input_shapes() {
12845        // Forward Y = conv2d(X, W) with stride=1, pad=1, groups=1 keeps H,W.
12846        // Backward should produce dX with X's shape and dW with W's shape.
12847        let x = NodeHandle::from_f32(
12848            (0..(2 * 4 * 4))
12849                .map(|i| (i as f32) * 0.05 - 0.5)
12850                .collect::<Vec<f32>>(),
12851            Shape::from_dims(&[1, 2, 4, 4]),
12852            cpu_dev(),
12853        )
12854        .unwrap();
12855        let w = x
12856            .const_f32_like(
12857                (0..(3 * 2 * 3 * 3))
12858                    .map(|i| (i as f32) * 0.07 - 0.4)
12859                    .collect::<Vec<f32>>(),
12860                Shape::from_dims(&[3, 2, 3, 3]),
12861            )
12862            .unwrap();
12863        let y = x.conv2d(&w, None, (1, 1), (1, 1), 1);
12864        let scalar_out = y.sum_all();
12865        let grads = scalar_out.backward();
12866        let dx = grads.get(&x).expect("conv2d backward produced no dX");
12867        let dw = grads.get(&w).expect("conv2d backward produced no dW");
12868        assert_eq!(dx.shape().dims(), x.shape().dims());
12869        assert_eq!(dw.shape().dims(), w.shape().dims());
12870    }
12871
12872    #[test]
12873    fn destructive_input_move_is_some_zero() {
12874        assert_eq!(
12875            Op::Move {
12876                target: DeviceLocation::Cpu
12877            }
12878            .destructive_input(),
12879            Some(0)
12880        );
12881    }
12882
12883    #[test]
12884    fn destructive_input_non_destructive_ops_are_none() {
12885        assert_eq!(
12886            Op::Copy {
12887                target: DeviceLocation::Cpu
12888            }
12889            .destructive_input(),
12890            None
12891        );
12892        assert_eq!(Op::Add.destructive_input(), None);
12893        assert_eq!(Op::Mul.destructive_input(), None);
12894        assert_eq!(Op::MatMul.destructive_input(), None);
12895        assert_eq!(Op::Relu.destructive_input(), None);
12896    }
12897
12898    #[test]
12899    fn move_to_device_emits_op_move_node() {
12900        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12901        let moved = a.move_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12902        let g = moved.graph().read().unwrap();
12903        match &g.node(moved.id()).op {
12904            Op::Move { target } => {
12905                assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12906            }
12907            other => panic!("expected Op::Move, got {other:?}"),
12908        }
12909        assert_eq!(g.node(moved.id()).inputs, vec![a.id()]);
12910        // Output has the input's shape (residency changes, data doesn't).
12911        assert_eq!(g.node(moved.id()).shape.elem_count(), 2);
12912    }
12913
12914    #[test]
12915    fn copy_to_device_emits_op_copy_node() {
12916        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12917        let b = a.copy_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12918        let g = b.graph().read().unwrap();
12919        match &g.node(b.id()).op {
12920            Op::Copy { target } => {
12921                assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12922            }
12923            other => panic!("expected Op::Copy, got {other:?}"),
12924        }
12925        // Source stays resident: the original `a` node still in the graph
12926        // and is the input of the Copy node.
12927        assert_eq!(g.node(b.id()).inputs, vec![a.id()]);
12928    }
12929
12930    #[test]
12931    fn release_builder_emits_op_release_node() {
12932        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12933        let released = a.release();
12934        let g = released.graph().read().unwrap();
12935        assert!(matches!(g.node(released.id()).op, Op::Release));
12936        assert_eq!(g.node(released.id()).inputs, vec![a.id()]);
12937        // Output is a zero-element marker.
12938        assert_eq!(g.node(released.id()).shape.elem_count(), 0);
12939    }
12940
12941    #[test]
12942    fn placement_is_none_by_default() {
12943        let a =
12944            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12945        assert_eq!(a.placement(), None);
12946    }
12947
12948    #[test]
12949    fn on_device_sets_placement_hint() {
12950        let a =
12951            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12952        let b = a
12953            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12954            .unwrap();
12955        // Only tag the Add node; the const leaves remain unplaced.
12956        let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
12957        assert_eq!(c.placement(), Some(DeviceLocation::Vulkan { gpu_id: 0 }));
12958        assert_eq!(a.placement(), None);
12959        assert_eq!(b.placement(), None);
12960    }
12961
12962    #[test]
12963    fn placement_survives_graph_re_reads() {
12964        let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12965        let tagged = a.clone().on_device(DeviceLocation::Cpu);
12966        // Re-read from a fresh borrow — round-trips through the side-table.
12967        assert_eq!(
12968            tagged.graph().read().unwrap().placement(tagged.id()),
12969            Some(DeviceLocation::Cpu)
12970        );
12971    }
12972
12973    #[test]
12974    fn from_f32_creates_single_const_node() {
12975        let a =
12976            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12977        assert_eq!(a.graph().read().unwrap().len(), 1);
12978        assert_eq!(a.shape().dims(), &[3]);
12979        assert_eq!(a.dtype(), DType::F32);
12980        let node = a.graph().read().unwrap().node(a.id()).clone();
12981        // Phase 7.5 G2: factory now emits Op::Const + slot.
12982        assert!(matches!(node.op, Op::Const));
12983        assert!(node.inputs.is_empty());
12984        // The slot is populated with F32 storage.
12985        let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12986        assert_eq!(slot.read().unwrap().dtype(), DType::F32);
12987    }
12988
12989    #[test]
12990    fn add_appends_a_node_and_tracks_inputs() {
12991        let a =
12992            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12993        let b = a
12994            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12995            .unwrap();
12996        let c = a.add(&b);
12997        assert_eq!(c.graph().read().unwrap().len(), 3); // const, const, add
12998        let node = c.graph().read().unwrap().node(c.id()).clone();
12999        assert!(matches!(node.op, Op::Add));
13000        assert_eq!(node.inputs.len(), 2);
13001        assert_eq!(node.inputs[0], a.id());
13002        assert_eq!(node.inputs[1], b.id());
13003        assert_eq!(c.shape().dims(), &[3]);
13004    }
13005
13006    #[test]
13007    fn chained_ops_all_share_one_graph() {
13008        let a =
13009            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13010        let b = a
13011            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
13012            .unwrap();
13013        let c = a.add(&b).mul(&a).sqr().relu();
13014        assert_eq!(c.graph().read().unwrap().len(), 6); // 2 consts + add + mul + sqr + relu
13015        assert_eq!(c.shape().dims(), &[3]);
13016    }
13017
13018    #[test]
13019    fn matmul_validates_shapes_and_produces_correct_output_shape() {
13020        let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13021        let b = a
13022            .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13023            .unwrap();
13024        let c = a.matmul(&b);
13025        assert_eq!(c.shape().dims(), &[2, 4]);
13026    }
13027
13028    #[test]
13029    #[should_panic(expected = "shape mismatch")]
13030    fn add_panics_on_shape_mismatch() {
13031        let a =
13032            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13033        let b = a
13034            .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13035            .unwrap();
13036        let _ = a.add(&b);
13037    }
13038
13039    #[test]
13040    #[should_panic(expected = "inner dim mismatch")]
13041    fn matmul_panics_on_inner_dim_mismatch() {
13042        let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13043        let b = a
13044            .const_f32_like(vec![1.0; 8], Shape::from_dims(&[4, 2]))
13045            .unwrap();
13046        let _ = a.matmul(&b);
13047    }
13048
13049    #[test]
13050    #[should_panic(expected = "must live on the same graph")]
13051    fn cross_graph_op_is_rejected() {
13052        let a =
13053            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13054        let b =
13055            NodeHandle::from_f32(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13056        let _ = a.add(&b);
13057    }
13058
13059    // ----- graph identity + graph-scoped construction -----
13060    //
13061    // Two changes land together: (1) every Graph carries a monotonic GraphId so
13062    // an affinity failure can name WHICH graphs rather than only that they
13063    // differ; (2) constructors accept an existing graph, so a consumer never has
13064    // to discover `const_*_like` to build a second tensor.
13065
13066    #[test]
13067    fn each_new_graph_gets_a_distinct_id() {
13068        let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
13069        let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
13070        assert_ne!(a.graph_id(), b.graph_id());
13071    }
13072
13073    #[test]
13074    fn same_graph_tensors_share_one_id() {
13075        let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
13076        let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
13077        assert_eq!(a.graph_id(), b.graph_id());
13078    }
13079
13080    #[test]
13081    fn affinity_panic_names_both_graph_ids() {
13082        let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
13083        let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
13084        let (ia, ib) = (a.graph_id(), b.graph_id());
13085        let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| a.add(&b)))
13086            .expect_err("cross-graph add must panic");
13087        let text = err
13088            .downcast_ref::<String>()
13089            .cloned()
13090            .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
13091            .expect("panic payload is a string");
13092        assert!(
13093            text.contains(&format!("#{ia}")) && text.contains(&format!("#{ib}")),
13094            "affinity panic must name BOTH graph ids so the caller can see it made two; got: {text}",
13095        );
13096    }
13097
13098    #[test]
13099    fn from_f32_on_builds_into_the_given_graph() {
13100        let root =
13101            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13102        let w = NodeHandle::from_f32_on(
13103            root.graph(),
13104            vec![4.0, 5.0, 6.0],
13105            Shape::from_dims(&[3]),
13106            cpu_dev(),
13107        )
13108        .unwrap();
13109        assert_eq!(root.graph_id(), w.graph_id());
13110        assert!(Arc::ptr_eq(root.graph(), w.graph()));
13111    }
13112
13113    #[test]
13114    fn graph_scoped_construction_composes_without_an_anchor() {
13115        // The program that could not previously be written: build two tensors
13116        // and combine them, without discovering `const_*_like`.
13117        let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
13118        let a = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev())
13119            .unwrap();
13120        let b = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[3, 2]), cpu_dev())
13121            .unwrap();
13122        let y = a.matmul(&b);
13123        assert_eq!(y.shape().dims(), &[2, 2]);
13124        assert_eq!(y.graph_id(), a.graph_id());
13125    }
13126
13127    #[test]
13128    fn graph_scoped_constructors_cover_every_dtype() {
13129        let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
13130        let s = Shape::from_dims(&[1]);
13131        let f32t = NodeHandle::from_f32_on(&g, vec![1.0f32], s.clone(), cpu_dev()).unwrap();
13132        let f64t = NodeHandle::from_f64_on(&g, vec![1.0f64], s.clone(), cpu_dev()).unwrap();
13133        let bf16t =
13134            NodeHandle::from_bf16_on(&g, vec![half::bf16::from_f32(1.0)], s.clone(), cpu_dev())
13135                .unwrap();
13136        let f16t =
13137            NodeHandle::from_f16_on(&g, vec![half::f16::from_f32(1.0)], s.clone(), cpu_dev())
13138                .unwrap();
13139        let u32t = NodeHandle::from_u32_on(&g, vec![1u32], s, cpu_dev()).unwrap();
13140        for t in [&f64t, &bf16t, &f16t, &u32t] {
13141            assert_eq!(
13142                t.graph_id(),
13143                f32t.graph_id(),
13144                "all must share the given graph"
13145            );
13146        }
13147        assert_eq!(f64t.dtype(), DType::F64);
13148        assert_eq!(bf16t.dtype(), DType::BF16);
13149        assert_eq!(f16t.dtype(), DType::F16);
13150        assert_eq!(u32t.dtype(), DType::U32);
13151    }
13152
13153    // ----- multi-dtype graph builders -----
13154
13155    #[test]
13156    fn from_f64_tags_node_with_f64_dtype() {
13157        let a =
13158            NodeHandle::from_f64(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13159        assert_eq!(a.dtype(), DType::F64);
13160        let node = a.graph().read().unwrap().node(a.id()).clone();
13161        // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13162        assert!(matches!(node.op, Op::Const));
13163        let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13164        assert_eq!(slot.read().unwrap().dtype(), DType::F64);
13165    }
13166
13167    #[test]
13168    fn from_bf16_tags_node_with_bf16_dtype() {
13169        let a = NodeHandle::from_bf16(
13170            vec![bf16::from_f32(1.0), bf16::from_f32(2.0)],
13171            Shape::from_dims(&[2]),
13172            cpu_dev(),
13173        )
13174        .unwrap();
13175        assert_eq!(a.dtype(), DType::BF16);
13176        let node = a.graph().read().unwrap().node(a.id()).clone();
13177        assert!(matches!(node.op, Op::Const));
13178        let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13179        assert_eq!(slot.read().unwrap().dtype(), DType::BF16);
13180    }
13181
13182    #[test]
13183    fn from_f16_tags_node_with_f16_dtype() {
13184        let a = NodeHandle::from_f16(
13185            vec![f16::from_f32(1.0), f16::from_f32(2.0)],
13186            Shape::from_dims(&[2]),
13187            cpu_dev(),
13188        )
13189        .unwrap();
13190        assert_eq!(a.dtype(), DType::F16);
13191        let node = a.graph().read().unwrap().node(a.id()).clone();
13192        assert!(matches!(node.op, Op::Const));
13193        let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13194        assert_eq!(slot.read().unwrap().dtype(), DType::F16);
13195    }
13196
13197    #[test]
13198    #[should_panic(expected = "dtype mismatch")]
13199    fn add_panics_on_mixed_dtype() {
13200        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13201        let b = a
13202            .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13203            .unwrap();
13204        let _ = a.add(&b);
13205    }
13206
13207    // ----- transpose -----
13208
13209    #[test]
13210    fn transpose_swaps_shape_dims() {
13211        let a = NodeHandle::from_f32(
13212            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13213            Shape::from_dims(&[2, 3]),
13214            cpu_dev(),
13215        )
13216        .unwrap();
13217        let t = a.transpose();
13218        assert_eq!(t.shape().dims(), &[3, 2]);
13219        let node = t.graph().read().unwrap().node(t.id()).clone();
13220        assert!(matches!(node.op, Op::Transpose));
13221        assert_eq!(node.inputs, vec![a.id()]);
13222    }
13223
13224    #[test]
13225    #[should_panic(expected = "rank ≥ 2")]
13226    fn transpose_rejects_rank_1() {
13227        let a =
13228            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13229        let _ = a.transpose();
13230    }
13231
13232    #[test]
13233    fn transpose_on_rank_3_swaps_last_two_dims() {
13234        // [2, 3, 4] → [2, 4, 3]
13235        let a = NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev())
13236            .unwrap();
13237        let t = a.transpose();
13238        assert_eq!(t.shape().dims(), &[2, 4, 3]);
13239    }
13240
13241    // ----- additional builder validation tests -----
13242
13243    #[test]
13244    fn matmul_rank_3_batched_shape() {
13245        // [2, 3, 4] @ [2, 4, 5] → [2, 3, 5]
13246        let a =
13247            NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13248        let b = a
13249            .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
13250            .unwrap();
13251        let c = a.matmul(&b);
13252        assert_eq!(c.shape().dims(), &[2, 3, 5]);
13253    }
13254
13255    #[test]
13256    #[should_panic(expected = "batch dim mismatch")]
13257    fn matmul_rank_3_rejects_batch_dim_mismatch() {
13258        let a =
13259            NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13260        let b = a
13261            .const_f32_like(vec![0.0; 60], Shape::from_dims(&[3, 4, 5]))
13262            .unwrap();
13263        let _ = a.matmul(&b);
13264    }
13265
13266    #[test]
13267    fn matmul_auto_broadcasts_rank_2_rhs_against_batched_lhs() {
13268        // [batch=2, seq=3, k=4] @ [k=4, n=5] → [2, 3, 5]. This is the
13269        // canonical "linear layer across a batch" pattern and should
13270        // Just Work without an explicit broadcast_to on the RHS.
13271        let a =
13272            NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13273        let b = a
13274            .const_f32_like(vec![0.0; 20], Shape::from_dims(&[4, 5]))
13275            .unwrap();
13276        let c = a.matmul(&b);
13277        assert_eq!(c.shape().dims(), &[2, 3, 5]);
13278    }
13279
13280    #[test]
13281    fn matmul_auto_broadcasts_rank_2_lhs_against_batched_rhs() {
13282        // [m=3, k=4] @ [batch=2, k=4, n=5] → [2, 3, 5].
13283        let a = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13284        let b = a
13285            .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
13286            .unwrap();
13287        let c = a.matmul(&b);
13288        assert_eq!(c.shape().dims(), &[2, 3, 5]);
13289    }
13290
13291    #[test]
13292    fn concat_output_shape_sums_along_dim() {
13293        // [2, 3] concat [2, 4] along dim 1 → [2, 7]
13294        let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13295        let b = a
13296            .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13297            .unwrap();
13298        let c = a.concat(&b, 1);
13299        assert_eq!(c.shape().dims(), &[2, 7]);
13300    }
13301
13302    #[test]
13303    #[should_panic(expected = "non-dim shapes")]
13304    fn concat_rejects_nondim_shape_mismatch() {
13305        let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13306        let b = a
13307            .const_f32_like(vec![0.0; 12], Shape::from_dims(&[3, 4]))
13308            .unwrap();
13309        let _ = a.concat(&b, 1);
13310    }
13311
13312    #[test]
13313    #[should_panic(expected = "rank mismatch")]
13314    fn concat_rejects_rank_mismatch() {
13315        let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13316        let b = a
13317            .const_f32_like(vec![0.0; 6], Shape::from_dims(&[6]))
13318            .unwrap();
13319        let _ = a.concat(&b, 0);
13320    }
13321
13322    #[test]
13323    fn slice_shrinks_only_the_slice_dim() {
13324        // [3, 4] slice dim 1, start 1, len 2 → [3, 2]
13325        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13326        let s = x.slice(1, 1, 2);
13327        assert_eq!(s.shape().dims(), &[3, 2]);
13328    }
13329
13330    #[test]
13331    #[should_panic(expected = "exceeds dim size")]
13332    fn slice_rejects_out_of_bounds_range() {
13333        let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13334        let _ = x.slice(1, 1, 3); // start=1, len=3 → would need dim>=4
13335    }
13336
13337    #[test]
13338    fn broadcast_add_shape_promotes_to_common_shape() {
13339        // [4, 1] + [1, 3] → [4, 3]
13340        let a = NodeHandle::from_f32(vec![0.0; 4], Shape::from_dims(&[4, 1]), cpu_dev()).unwrap();
13341        let b = a
13342            .const_f32_like(vec![0.0; 3], Shape::from_dims(&[1, 3]))
13343            .unwrap();
13344        let c = a.broadcast_add(&b);
13345        assert_eq!(c.shape().dims(), &[4, 3]);
13346    }
13347
13348    #[test]
13349    fn broadcast_sub_pads_shorter_shape_with_leading_ones() {
13350        // [3] - [2, 3] → [2, 3]
13351        let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13352        let b = a
13353            .const_f32_like(vec![0.0; 6], Shape::from_dims(&[2, 3]))
13354            .unwrap();
13355        let c = a.broadcast_sub(&b);
13356        assert_eq!(c.shape().dims(), &[2, 3]);
13357    }
13358
13359    #[test]
13360    #[should_panic(expected = "incompatible shapes")]
13361    fn broadcast_add_rejects_incompatible_shapes() {
13362        let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13363        let b = a
13364            .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13365            .unwrap();
13366        let _ = a.broadcast_add(&b);
13367    }
13368
13369    #[test]
13370    fn argmax_dim_is_u32_and_removes_reduced_dim() {
13371        let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13372        let am = x.argmax_dim(1);
13373        assert_eq!(am.dtype(), DType::U32);
13374        assert_eq!(am.shape().dims(), &[2]);
13375    }
13376
13377    #[test]
13378    #[should_panic(expected = "out of bounds")]
13379    fn argmax_dim_rejects_bad_dim() {
13380        let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13381        let _ = x.argmax_dim(5);
13382    }
13383
13384    #[test]
13385    fn index_add_shape_validation() {
13386        let base = NodeHandle::from_f32(vec![0.0; 10], Shape::from_dims(&[10]), cpu_dev()).unwrap();
13387        let idx = base
13388            .const_u32_like(vec![1, 3, 5], Shape::from_dims(&[3]))
13389            .unwrap();
13390        let src = base
13391            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13392            .unwrap();
13393        let out = base.index_add(0, &idx, &src);
13394        assert_eq!(out.shape().dims(), &[10]);
13395    }
13396
13397    #[test]
13398    #[should_panic(expected = "dtypes must match")]
13399    fn index_add_rejects_dtype_mismatch() {
13400        let base = NodeHandle::from_f32(vec![0.0; 5], Shape::from_dims(&[5]), cpu_dev()).unwrap();
13401        let idx = base
13402            .const_u32_like(vec![0, 2], Shape::from_dims(&[2]))
13403            .unwrap();
13404        let src = base
13405            .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13406            .unwrap();
13407        let _ = base.index_add(0, &idx, &src);
13408    }
13409
13410    #[test]
13411    fn scatter_add_validates_index_matches_src() {
13412        let base =
13413            NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13414        let idx = base
13415            .const_u32_like(vec![0, 2, 1, 0], Shape::from_dims(&[2, 2]))
13416            .unwrap();
13417        let src = base
13418            .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13419            .unwrap();
13420        let out = base.scatter_add(1, &idx, &src);
13421        assert_eq!(out.shape().dims(), &[2, 3]);
13422    }
13423
13424    #[test]
13425    #[should_panic(expected = "same shape")]
13426    fn scatter_add_rejects_index_src_shape_mismatch() {
13427        let base =
13428            NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13429        let idx = base
13430            .const_u32_like(vec![0, 1], Shape::from_dims(&[2]))
13431            .unwrap();
13432        let src = base
13433            .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13434            .unwrap();
13435        let _ = base.scatter_add(1, &idx, &src);
13436    }
13437
13438    #[test]
13439    fn reduce_sum_to_validates_compatibility() {
13440        // [3, 4] can reduce to [4] (sum along dim 0) or [3, 1] (sum along dim 1).
13441        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13442        let r1 = x.reduce_sum_to(Shape::from_dims(&[4]));
13443        assert_eq!(r1.shape().dims(), &[4]);
13444        let r2 = x.reduce_sum_to(Shape::from_dims(&[3, 1]));
13445        assert_eq!(r2.shape().dims(), &[3, 1]);
13446    }
13447
13448    #[test]
13449    #[should_panic(expected = "incompatible")]
13450    fn reduce_sum_to_rejects_non_broadcast_target() {
13451        // [3, 4] cannot reduce to [3, 2] — target must be broadcast-into-source.
13452        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13453        let _ = x.reduce_sum_to(Shape::from_dims(&[3, 2]));
13454    }
13455
13456    #[test]
13457    fn unsqueeze_inserts_size_one_dim() {
13458        let x = NodeHandle::from_f32(
13459            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13460            Shape::from_dims(&[2, 3]),
13461            cpu_dev(),
13462        )
13463        .unwrap();
13464        // Insert at position 0: [2, 3] -> [1, 2, 3]
13465        let y0 = x.unsqueeze(0);
13466        assert_eq!(y0.shape().dims(), &[1, 2, 3]);
13467        // Insert at position 1: [2, 3] -> [2, 1, 3]
13468        let y1 = x.unsqueeze(1);
13469        assert_eq!(y1.shape().dims(), &[2, 1, 3]);
13470        // Insert at the end (rank): [2, 3] -> [2, 3, 1]
13471        let y2 = x.unsqueeze(2);
13472        assert_eq!(y2.shape().dims(), &[2, 3, 1]);
13473        // Op variant correctness.
13474        let g = x.graph().read().unwrap();
13475        assert!(matches!(g.node(y0.id()).op, Op::Unsqueeze { dim: 0 }));
13476        assert!(matches!(g.node(y1.id()).op, Op::Unsqueeze { dim: 1 }));
13477        assert!(matches!(g.node(y2.id()).op, Op::Unsqueeze { dim: 2 }));
13478    }
13479
13480    #[test]
13481    #[should_panic(expected = "out of bounds")]
13482    fn unsqueeze_rejects_dim_above_rank() {
13483        let x = NodeHandle::from_f32(vec![1.0; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
13484        // dim=2 > rank=1 → panic.
13485        let _ = x.unsqueeze(2);
13486    }
13487
13488    #[test]
13489    fn unsqueeze_layout_side_table_populated() {
13490        // After Graph::push auto-derives the Layout side-table for view
13491        // ops, an unsqueeze node should have an explicit layout entry
13492        // with a stride-0 axis at the inserted position.
13493        let x = NodeHandle::from_f32(
13494            vec![1.0, 2.0, 3.0, 4.0],
13495            Shape::from_dims(&[2, 2]),
13496            cpu_dev(),
13497        )
13498        .unwrap();
13499        let y = x.unsqueeze(1);
13500        let g = x.graph().read().unwrap();
13501        assert!(
13502            g.has_explicit_layout(y.id()),
13503            "Graph::push should auto-populate layout for view ops"
13504        );
13505        let l = g.layout(y.id());
13506        assert_eq!(l.shape().dims(), &[2, 1, 2]);
13507        // Stride at the inserted axis should be 0 (per the convention
13508        // chosen in Layout::unsqueeze).
13509        assert_eq!(l.stride()[1], 0);
13510    }
13511
13512    #[test]
13513    fn reduce_max_to_validates_compatibility() {
13514        // [3, 4] can reduce to [4] (max along dim 0) or [3, 1] (max along dim 1).
13515        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13516        let r1 = x.reduce_max_to(Shape::from_dims(&[4]));
13517        assert_eq!(r1.shape().dims(), &[4]);
13518        assert!(matches!(
13519            r1.graph().read().unwrap().node(r1.id()).op,
13520            Op::ReduceMaxTo(_)
13521        ));
13522        let r2 = x.reduce_max_to(Shape::from_dims(&[3, 1]));
13523        assert_eq!(r2.shape().dims(), &[3, 1]);
13524    }
13525
13526    #[test]
13527    #[should_panic(expected = "incompatible")]
13528    fn reduce_max_to_rejects_non_broadcast_target() {
13529        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13530        let _ = x.reduce_max_to(Shape::from_dims(&[3, 2]));
13531    }
13532
13533    #[test]
13534    fn reshape_preserves_element_count() {
13535        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13536        let r = x.reshape(Shape::from_dims(&[2, 6]));
13537        assert_eq!(r.shape().dims(), &[2, 6]);
13538    }
13539
13540    #[test]
13541    #[should_panic(expected = "element count mismatch")]
13542    fn reshape_rejects_different_element_count() {
13543        let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13544        let _ = x.reshape(Shape::from_dims(&[3, 3]));
13545    }
13546
13547    #[test]
13548    #[should_panic(expected = "same graph")]
13549    fn concat_across_graphs_panics() {
13550        let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13551        let b = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13552        let _ = a.concat(&b, 0);
13553    }
13554
13555    #[test]
13556    fn scalar_ops_preserve_shape_and_dtype() {
13557        let x =
13558            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13559        let y = x.add_scalar(5.0).mul_scalar(2.0).powi(2).clamp(0.0, 100.0);
13560        assert_eq!(y.shape().dims(), &[3]);
13561        assert_eq!(y.dtype(), DType::F32);
13562    }
13563
13564    #[test]
13565    fn maximum_requires_matching_shapes() {
13566        let a =
13567            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13568        let b = a
13569            .const_f32_like(vec![4.0, 1.0, 5.0], Shape::from_dims(&[3]))
13570            .unwrap();
13571        let m = a.maximum(&b);
13572        assert_eq!(m.shape().dims(), &[3]);
13573    }
13574
13575    #[test]
13576    #[should_panic(expected = "shape mismatch")]
13577    fn maximum_rejects_shape_mismatch() {
13578        let a =
13579            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13580        let b = a
13581            .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13582            .unwrap();
13583        let _ = a.maximum(&b);
13584    }
13585
13586    // ----- topo_order -----
13587
13588    #[test]
13589    fn topo_order_places_inputs_before_dependents() {
13590        // Build: c = (a + b) * a
13591        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13592        let b = a
13593            .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13594            .unwrap();
13595        let sum = a.add(&b);
13596        let c = sum.mul(&a);
13597        let order = topo_order(&c.graph().read().unwrap(), c.id());
13598        // The order should contain exactly 4 nodes (a, b, sum, c) and
13599        // place each input strictly before its dependents.
13600        assert_eq!(order.len(), 4);
13601        let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13602        assert!(pos(a.id()) < pos(sum.id()));
13603        assert!(pos(b.id()) < pos(sum.id()));
13604        assert!(pos(sum.id()) < pos(c.id()));
13605        assert!(pos(a.id()) < pos(c.id()));
13606    }
13607
13608    #[test]
13609    fn topo_order_visits_each_node_once_when_shared() {
13610        // (a + a) — `a` appears twice in the Add's inputs but the topo
13611        // pass should still visit it exactly once.
13612        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13613        let double = a.add(&a);
13614        let order = topo_order(&double.graph().read().unwrap(), double.id());
13615        assert_eq!(order.len(), 2);
13616        assert_eq!(order[0], a.id());
13617        assert_eq!(order[1], double.id());
13618    }
13619
13620    #[test]
13621    fn topo_order_multi_unions_multiple_roots() {
13622        // Build a DAG where two "output" nodes share a common input.
13623        //
13624        //      a ─┬─> add1 (= a + b)  ← root_1
13625        //         └─> add2 (= a + c)  ← root_2
13626        //      b ───> add1
13627        //      c ───> add2
13628        //
13629        // topo_order_multi(&[add1, add2]) must contain all 5 nodes
13630        // (a, b, c, add1, add2) with a before add1/add2 and b before
13631        // add1 and c before add2.
13632        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13633        let b = a
13634            .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13635            .unwrap();
13636        let c = a
13637            .const_f32_like(vec![5.0, 6.0], Shape::from_dims(&[2]))
13638            .unwrap();
13639        let add1 = a.add(&b);
13640        let add2 = a.add(&c);
13641        let order = topo_order_multi(&add1.graph().read().unwrap(), &[add1.id(), add2.id()]);
13642        assert_eq!(order.len(), 5);
13643        let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13644        assert!(pos(a.id()) < pos(add1.id()));
13645        assert!(pos(a.id()) < pos(add2.id()));
13646        assert!(pos(b.id()) < pos(add1.id()));
13647        assert!(pos(c.id()) < pos(add2.id()));
13648    }
13649
13650    // ----- backward -----
13651
13652    #[test]
13653    fn backward_of_lone_const_seeds_ones() {
13654        // backward(a) gives a = 1s (the root's upstream is a ones tensor,
13655        // which is the gradient stored for the root itself).
13656        let a =
13657            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13658        let grads = a.backward();
13659        let g_a = grads.get(&a).expect("root gets a seed gradient");
13660        // The seed is a Const ones node of matching shape. Phase 7.5
13661        // G2: gradient consts are slot-rooted Op::Const — no
13662        // host-side ConstData on the node.
13663        let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13664        assert!(matches!(node.op, Op::Const));
13665        let slot = g_a.graph().read().unwrap().storage_for(g_a.id()).unwrap();
13666        assert_eq!(slot.read().unwrap().dtype(), DType::F32);
13667        assert_eq!(g_a.shape().dims(), &[3]);
13668    }
13669
13670    #[test]
13671    fn backward_of_add_passes_upstream_through() {
13672        // c = a + b  ⇒  dc/da = 1, dc/db = 1.
13673        // Upstream seed is a ones tensor. So grad_a and grad_b are both
13674        // the same ones node (no new math emitted for Add's backward).
13675        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13676        let b = a
13677            .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13678            .unwrap();
13679        let c = a.add(&b);
13680        let grads = c.backward();
13681        let g_a = grads.get(&a).unwrap();
13682        let g_b = grads.get(&b).unwrap();
13683        assert_eq!(g_a.id(), g_b.id(), "Add backward routes upstream unchanged");
13684        assert_eq!(g_a.shape().dims(), &[2]);
13685    }
13686
13687    #[test]
13688    fn backward_of_mul_emits_two_mul_nodes() {
13689        // c = a * b  ⇒  dc/da = b, dc/db = a (upstream is 1s).
13690        // The backward pass should emit two new Mul nodes (upstream * b,
13691        // upstream * a).
13692        let a = NodeHandle::from_f32(vec![2.0, 3.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13693        let b = a
13694            .const_f32_like(vec![5.0, 7.0], Shape::from_dims(&[2]))
13695            .unwrap();
13696        let c = a.mul(&b);
13697        let nodes_before = c.graph().read().unwrap().len();
13698        let grads = c.backward();
13699        let nodes_after = grads.graph.read().unwrap().len();
13700        // Backward adds: one ones const + two Mul nodes = 3 new nodes.
13701        assert_eq!(nodes_after - nodes_before, 3);
13702        let g_a = grads.get(&a).unwrap();
13703        let g_b = grads.get(&b).unwrap();
13704        // Both gradient nodes should be Mul nodes.
13705        let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13706        let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13707        assert!(matches!(node_a.op, Op::Mul));
13708        assert!(matches!(node_b.op, Op::Mul));
13709    }
13710
13711    #[test]
13712    fn backward_accumulates_when_node_used_twice() {
13713        // c = a * a  ⇒  dc/da = 2a via two separate contributions.
13714        // After backward, the gradient for a should be an Add node
13715        // combining the two Mul contributions (one from each input slot
13716        // of the forward Mul).
13717        let a = NodeHandle::from_f32(vec![3.0, 5.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13718        let c = a.mul(&a);
13719        let grads = c.backward();
13720        let g_a = grads.get(&a).unwrap();
13721        let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13722        // The final gradient for `a` is an Add combining the two
13723        // upstream-times-other-input contributions.
13724        assert!(
13725            matches!(node.op, Op::Add),
13726            "expected accumulated gradient to be an Add node, got {:?}",
13727            node.op,
13728        );
13729    }
13730
13731    #[test]
13732    fn backward_of_matmul_emits_transpose_and_matmul_nodes() {
13733        // Forward: Y = A @ B,  A:[2,3], B:[3,4], Y:[2,4].
13734        // Backward: dA = dY @ B^T (shape [2,3]),  dB = A^T @ dY (shape [3,4]).
13735        let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13736        let b = a
13737            .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13738            .unwrap();
13739        let y = a.matmul(&b);
13740        let grads = y.backward();
13741        let g_a = grads.get(&a).unwrap();
13742        let g_b = grads.get(&b).unwrap();
13743        // Gradient shapes must match the forward shapes.
13744        assert_eq!(g_a.shape().dims(), &[2, 3]);
13745        assert_eq!(g_b.shape().dims(), &[3, 4]);
13746        // Both should be MatMul nodes (the outermost op of each gradient).
13747        let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13748        let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13749        assert!(matches!(node_a.op, Op::MatMul));
13750        assert!(matches!(node_b.op, Op::MatMul));
13751    }
13752
13753    // ----- new builder validation -----
13754
13755    #[test]
13756    fn cast_tags_node_with_target_dtype() {
13757        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13758        let b = a.cast(DType::F64);
13759        assert_eq!(b.dtype(), DType::F64);
13760        assert_eq!(b.shape().dims(), &[2]);
13761        let node = b.graph().read().unwrap().node(b.id()).clone();
13762        assert!(matches!(node.op, Op::Cast(DType::F64)));
13763    }
13764
13765    #[test]
13766    fn broadcast_to_accepts_right_aligned_expansion() {
13767        // [3] broadcasts to [2, 3]: pad with leading 1, expand.
13768        let a =
13769            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13770        let b = a.broadcast_to(Shape::from_dims(&[2, 3]));
13771        assert_eq!(b.shape().dims(), &[2, 3]);
13772    }
13773
13774    #[test]
13775    fn broadcast_to_accepts_size_one_expansion() {
13776        // [3, 1] broadcasts to [3, 4]: size-1 dim expands.
13777        let a = NodeHandle::from_f32(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3, 1]), cpu_dev())
13778            .unwrap();
13779        let b = a.broadcast_to(Shape::from_dims(&[3, 4]));
13780        assert_eq!(b.shape().dims(), &[3, 4]);
13781    }
13782
13783    #[test]
13784    #[should_panic(expected = "incompatible")]
13785    fn broadcast_to_rejects_incompatible_dim() {
13786        // [3] cannot broadcast to [2, 4] — the source dim 3 must match 4.
13787        let a =
13788            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13789        let _ = a.broadcast_to(Shape::from_dims(&[2, 4]));
13790    }
13791
13792    #[test]
13793    fn sum_all_produces_rank_zero_output() {
13794        let a =
13795            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13796        let s = a.sum_all();
13797        assert_eq!(s.shape().dims(), &[] as &[usize]);
13798    }
13799
13800    #[test]
13801    fn sum_dim_removes_reduced_dim_from_shape() {
13802        let a =
13803            NodeHandle::from_f32(vec![1.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13804        // Reducing dim 1 should give shape [2, 4].
13805        let s = a.sum_dim(1);
13806        assert_eq!(s.shape().dims(), &[2, 4]);
13807    }
13808
13809    #[test]
13810    #[should_panic(expected = "out of bounds")]
13811    fn sum_dim_rejects_bad_dim() {
13812        let a =
13813            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13814        let _ = a.sum_dim(5);
13815    }
13816
13817    #[test]
13818    fn softmax_and_layer_norm_preserve_shape() {
13819        let a = NodeHandle::from_f32(
13820            vec![1.0, 2.0, 3.0, 4.0],
13821            Shape::from_dims(&[2, 2]),
13822            cpu_dev(),
13823        )
13824        .unwrap();
13825        assert_eq!(a.softmax_last_dim().shape().dims(), &[2, 2]);
13826        assert_eq!(a.layer_norm_last_dim(1e-5).shape().dims(), &[2, 2]);
13827    }
13828
13829    #[test]
13830    fn neg_sub_div_sqrt_log_sin_cos_tanh_sigmoid_all_build() {
13831        // Smoke test: every new builder produces a node with the expected
13832        // shape and dtype. Numerical correctness is exercised in exec.rs.
13833        let a =
13834            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13835        let b = a
13836            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13837            .unwrap();
13838        for tensor in [
13839            a.neg(),
13840            a.sub(&b),
13841            a.div(&b),
13842            a.sqrt(),
13843            a.log(),
13844            a.sin(),
13845            a.cos(),
13846            a.tanh(),
13847            a.sigmoid(),
13848            a.step(),
13849        ] {
13850            assert_eq!(tensor.shape().dims(), &[3]);
13851            assert_eq!(tensor.dtype(), DType::F32);
13852        }
13853    }
13854
13855    // ----- index tensors and indexing ops -----
13856
13857    #[test]
13858    fn from_u32_tags_node_with_u32_dtype() {
13859        let a = NodeHandle::from_u32(vec![1, 2, 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13860        assert_eq!(a.dtype(), DType::U32);
13861        let node = a.graph().read().unwrap().node(a.id()).clone();
13862        // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13863        assert!(matches!(node.op, Op::Const));
13864        let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13865        assert_eq!(slot.read().unwrap().dtype(), DType::U32);
13866    }
13867
13868    #[test]
13869    fn index_select_produces_shape_with_dim_replaced() {
13870        let data =
13871            NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13872        let idx = data
13873            .const_u32_like(vec![0, 2, 1, 0, 2], Shape::from_dims(&[5]))
13874            .unwrap();
13875        let out = data.index_select(0, &idx);
13876        assert_eq!(out.shape().dims(), &[5, 4]);
13877        assert_eq!(out.dtype(), DType::F32);
13878    }
13879
13880    #[test]
13881    #[should_panic(expected = "must be U32")]
13882    fn index_select_rejects_float_index() {
13883        let data =
13884            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13885        let bad = data
13886            .const_f32_like(vec![0.0, 1.0], Shape::from_dims(&[2]))
13887            .unwrap();
13888        let _ = data.index_select(0, &bad);
13889    }
13890
13891    #[test]
13892    #[should_panic(expected = "must be rank 1")]
13893    fn index_select_rejects_multi_dim_index() {
13894        let data =
13895            NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13896        let idx = data
13897            .const_u32_like(vec![0, 1, 0, 1], Shape::from_dims(&[2, 2]))
13898            .unwrap();
13899        let _ = data.index_select(0, &idx);
13900    }
13901
13902    #[test]
13903    fn gather_output_shape_matches_index_shape() {
13904        let data =
13905            NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13906        // Index shape [2, 5] — same rank as data (rank 2).
13907        let idx = data
13908            .const_u32_like(vec![0; 10], Shape::from_dims(&[2, 5]))
13909            .unwrap();
13910        let out = data.gather(1, &idx);
13911        assert_eq!(out.shape().dims(), &[2, 5]);
13912    }
13913
13914    #[test]
13915    #[should_panic(expected = "same rank")]
13916    fn gather_rejects_rank_mismatch() {
13917        let data =
13918            NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13919        // Rank-1 index for rank-2 data → error.
13920        let idx = data
13921            .const_u32_like(vec![0, 1, 0], Shape::from_dims(&[3]))
13922            .unwrap();
13923        let _ = data.gather(1, &idx);
13924    }
13925
13926    #[test]
13927    fn backward_of_relu_emits_step_node() {
13928        // Before: this used to panic. After adding Step + Relu backward,
13929        // it should successfully emit a backward graph rooted in a Mul
13930        // whose second input is a Step node.
13931        let a =
13932            NodeHandle::from_f32(vec![-1.0, 2.0, -3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13933        let y = a.relu();
13934        let grads = y.backward();
13935        let g_a = grads.get(&a).unwrap();
13936        let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13937        assert!(matches!(node.op, Op::Mul));
13938        // Find a Step node somewhere in the node's inputs.
13939        let any_step = node
13940            .inputs
13941            .iter()
13942            .any(|&id| matches!(g_a.graph().read().unwrap().node(id).op, Op::Step,));
13943        assert!(any_step, "Relu backward must reference a Step node");
13944    }
13945
13946    #[test]
13947    fn recip_and_abs_builders_produce_unary_nodes() {
13948        // Smoke test: NodeHandle::recip()/abs() build single-input nodes
13949        // with the expected op variant and shape passthrough.
13950        let a =
13951            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13952        let r = a.recip();
13953        let b = a.abs();
13954        assert_eq!(r.shape().dims(), &[3]);
13955        assert_eq!(b.shape().dims(), &[3]);
13956        let r_node = r.graph().read().unwrap().node(r.id()).clone();
13957        let b_node = b.graph().read().unwrap().node(b.id()).clone();
13958        assert!(matches!(r_node.op, Op::Recip));
13959        assert!(matches!(b_node.op, Op::Abs));
13960        assert_eq!(r_node.inputs, vec![a.id()]);
13961        assert_eq!(b_node.inputs, vec![a.id()]);
13962    }
13963
13964    #[test]
13965    fn backward_of_recip_is_neg_of_upstream_times_y_squared() {
13966        // y = 1/x ⇒ dy/dx = -y². The backward graph should be a Neg
13967        // wrapping a Mul whose inputs include a Sqr node — and the Sqr
13968        // should reference the forward Recip output, not a fresh recompute.
13969        let a = NodeHandle::from_f32(vec![2.0, 4.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13970        let y = a.recip();
13971        let y_id = y.id();
13972        let grads = y.backward();
13973        let g_a = grads.get(&a).unwrap();
13974        let g = g_a.graph().read().unwrap();
13975        let neg_node = g.node(g_a.id()).clone();
13976        assert!(
13977            matches!(neg_node.op, Op::Neg),
13978            "outermost backward op must be Neg"
13979        );
13980        let mul_id = neg_node.inputs[0];
13981        let mul_node = g.node(mul_id).clone();
13982        assert!(matches!(mul_node.op, Op::Mul));
13983        // One of the Mul's inputs is a Sqr node fed by the forward Recip.
13984        let sqr_id = mul_node
13985            .inputs
13986            .iter()
13987            .copied()
13988            .find(|&id| matches!(g.node(id).op, Op::Sqr))
13989            .expect("backward chain must contain a Sqr node");
13990        let sqr_node = g.node(sqr_id).clone();
13991        assert_eq!(
13992            sqr_node.inputs,
13993            vec![y_id],
13994            "Sqr's input must be the forward Recip output, not a recompute"
13995        );
13996    }
13997
13998    #[test]
13999    fn backward_of_abs_emits_sign_mul() {
14000        // y = |x|, dy/dx = sign(x). After PR B2 landed Op::Sign, the
14001        // backward chain shrinks from 5 nodes (step+neg+step+sub+mul)
14002        // to 2 (sign+mul): grad_x = upstream * sign(x), where Sign is
14003        // a single primitive that returns -1/0/1 directly.
14004        let a = NodeHandle::from_f32(vec![-2.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14005        let y = a.abs();
14006        let grads = y.backward();
14007        let g_a = grads.get(&a).unwrap();
14008        let g = g_a.graph().read().unwrap();
14009        let mul_node = g.node(g_a.id()).clone();
14010        assert!(matches!(mul_node.op, Op::Mul));
14011        // Exactly one input of the Mul is a Sign node (the other is
14012        // the upstream gradient — a Const-rooted ones-tensor here).
14013        let sign_count = mul_node
14014            .inputs
14015            .iter()
14016            .filter(|&&id| matches!(g.node(id).op, Op::Sign))
14017            .count();
14018        assert_eq!(
14019            sign_count, 1,
14020            "Abs backward must reference exactly 1 Sign node, got {sign_count}"
14021        );
14022        // The Sign node should feed off the original input `a`.
14023        let sign_id = mul_node
14024            .inputs
14025            .iter()
14026            .copied()
14027            .find(|&id| matches!(g.node(id).op, Op::Sign))
14028            .unwrap();
14029        assert_eq!(
14030            g.node(sign_id).inputs,
14031            vec![a.id()],
14032            "Sign's input must be the forward input `a`"
14033        );
14034    }
14035
14036    #[test]
14037    fn eq_builder_produces_bool_output_with_input_shape() {
14038        // GAP-168(c): NodeHandle::eq builds a binary node whose dtype is Bool
14039        // regardless of input dtype (CireSnave's ruling — "Fuel uses Bool
14040        // where possible"), with shape == lhs.shape() (and == rhs.shape()).
14041        let a =
14042            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14043        let b = a
14044            .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
14045            .unwrap();
14046        let m = a.eq(&b);
14047        assert_eq!(m.shape().dims(), &[3]);
14048        assert_eq!(m.dtype(), DType::Bool, "eq output must be Bool");
14049        let m_node = m.graph().read().unwrap().node(m.id()).clone();
14050        assert!(matches!(m_node.op, Op::Equal));
14051        assert_eq!(m_node.inputs, vec![a.id(), b.id()]);
14052    }
14053
14054    #[test]
14055    fn all_six_comparisons_produce_bool() {
14056        // GAP-168(c): eq/ne/lt/le/gt/ge every one returns DType::Bool, not the
14057        // legacy U8 mask. Shape is preserved (== lhs == rhs). One assertion per
14058        // operator so a regression names the operator that drifted.
14059        let a =
14060            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14061        let b = a
14062            .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
14063            .unwrap();
14064        for (name, m) in [
14065            ("eq", a.eq(&b)),
14066            ("ne", a.ne(&b)),
14067            ("lt", a.lt(&b)),
14068            ("le", a.le(&b)),
14069            ("gt", a.gt(&b)),
14070            ("ge", a.ge(&b)),
14071        ] {
14072            assert_eq!(m.dtype(), DType::Bool, "{name} output must be Bool");
14073            assert_eq!(m.shape().dims(), &[3], "{name} preserves input shape");
14074        }
14075    }
14076
14077    #[test]
14078    fn try_unsqueeze_returns_err_on_dim_above_rank() {
14079        // try_unsqueeze surfaces bad dim as Err; unsqueeze panics
14080        // on the same input. Both share the validation message.
14081        let a =
14082            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14083        let err = a.try_unsqueeze(5).expect_err("dim above rank must error");
14084        assert!(
14085            format!("{err:?}").contains("out of bounds"),
14086            "error must mention bounds, got: {err:?}"
14087        );
14088        // Happy path still works.
14089        let ok = a.try_unsqueeze(0).expect("dim=0 valid for any rank");
14090        assert_eq!(ok.shape().dims(), &[1, 3]);
14091    }
14092
14093    #[test]
14094    fn try_reshape_returns_err_on_count_mismatch() {
14095        let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
14096            .unwrap();
14097        let err = a
14098            .try_reshape(Shape::from_dims(&[3]))
14099            .expect_err("count mismatch must error");
14100        assert!(
14101            format!("{err:?}").contains("element count mismatch"),
14102            "error must mention count mismatch, got: {err:?}"
14103        );
14104        let ok = a
14105            .try_reshape(Shape::from_dims(&[2, 2]))
14106            .expect("matching count is ok");
14107        assert_eq!(ok.shape().dims(), &[2, 2]);
14108    }
14109
14110    #[test]
14111    fn try_broadcast_to_returns_err_on_incompatible_shape() {
14112        let a =
14113            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14114        let err = a
14115            .try_broadcast_to(Shape::from_dims(&[2, 4]))
14116            .expect_err("source dim 3 cannot broadcast to dim 4");
14117        assert!(
14118            format!("{err:?}").contains("incompatible"),
14119            "error must mention incompatibility, got: {err:?}"
14120        );
14121        let ok = a
14122            .try_broadcast_to(Shape::from_dims(&[2, 3]))
14123            .expect("dim 3 broadcasts to dim 3");
14124        assert_eq!(ok.shape().dims(), &[2, 3]);
14125    }
14126
14127    #[test]
14128    fn try_transpose_returns_err_on_rank_below_2() {
14129        let a =
14130            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14131        let err = a
14132            .try_transpose()
14133            .expect_err("rank-1 input cannot transpose");
14134        assert!(
14135            format!("{err:?}").contains("rank ≥ 2"),
14136            "error must mention rank requirement, got: {err:?}"
14137        );
14138        let m = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14139        let mt = m.try_transpose().expect("rank-2 transposes ok");
14140        assert_eq!(mt.shape().dims(), &[3, 2]);
14141    }
14142
14143    #[test]
14144    fn try_permute_returns_err_on_bad_axes() {
14145        let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14146        // Wrong axes length:
14147        let err = a.try_permute(&[0]).expect_err("axes length mismatch");
14148        assert!(
14149            format!("{err:?}").contains("must equal tensor rank"),
14150            "error must mention length, got: {err:?}"
14151        );
14152        // Out-of-bounds axis:
14153        let err = a.try_permute(&[0, 5]).expect_err("axis 5 out of rank 2");
14154        assert!(format!("{err:?}").contains("out of bounds"));
14155        // Duplicate axis:
14156        let err = a.try_permute(&[0, 0]).expect_err("duplicate axis");
14157        assert!(format!("{err:?}").contains("duplicate"));
14158        // Happy path:
14159        let ok = a.try_permute(&[1, 0]).expect("valid permutation");
14160        assert_eq!(ok.shape().dims(), &[3, 2]);
14161    }
14162
14163    #[test]
14164    fn squeeze_drops_size_one_dim_metadata_only() {
14165        // Build [2, 1, 3] → squeeze(1) → [2, 3]. Op::Squeeze, view-op,
14166        // shape pruned, dtype preserved, single input slot.
14167        let a =
14168            NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
14169        let s = a.squeeze(1).expect("squeeze on size-1 dim");
14170        assert_eq!(s.shape().dims(), &[2, 3]);
14171        assert_eq!(s.dtype(), DType::F32);
14172        let node = s.graph().read().unwrap().node(s.id()).clone();
14173        assert!(matches!(node.op, Op::Squeeze { dim: 1 }));
14174        assert_eq!(node.inputs, vec![a.id()]);
14175        // Squeeze joins the view-op set so the Layout side-table is
14176        // populated automatically.
14177        assert!(
14178            node.op.is_view_op(),
14179            "Op::Squeeze must register as a view op"
14180        );
14181    }
14182
14183    #[test]
14184    fn squeeze_rejects_non_size_one_dim() {
14185        // Result-returning: bad dim surfaces as Err, not panic.
14186        let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14187        let err = a
14188            .squeeze(1)
14189            .expect_err("squeezing a non-size-1 dim must error");
14190        assert!(
14191            format!("{err:?}").contains("expected 1"),
14192            "error message should mention the size-1 expectation, got: {err:?}"
14193        );
14194    }
14195
14196    #[test]
14197    fn squeeze_rejects_dim_above_rank() {
14198        let a =
14199            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14200        let err = a.squeeze(5).expect_err("dim above rank must error");
14201        assert!(
14202            format!("{err:?}").contains("out of bounds"),
14203            "error message should mention bounds, got: {err:?}"
14204        );
14205    }
14206
14207    #[test]
14208    fn backward_through_squeeze_emits_unsqueeze() {
14209        // y = squeeze(x, 1). Backward: re-insert dim 1 via Unsqueeze.
14210        // Gradient shape must equal x.shape exactly.
14211        let a =
14212            NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
14213        let y = a.squeeze(1).expect("squeeze on size-1 dim");
14214        let grads = y.backward();
14215        let g_a = grads.get(&a).expect("gradient for a");
14216        assert_eq!(
14217            g_a.shape().dims(),
14218            &[2, 1, 3],
14219            "Squeeze backward gradient must restore the original shape"
14220        );
14221        // The chain is: ones-seed (post-squeeze, shape [2,3])
14222        //               → Unsqueeze(dim=1) → shape [2, 1, 3].
14223        let g_node = g_a.graph().read().unwrap().node(g_a.id()).clone();
14224        assert!(
14225            matches!(g_node.op, Op::Unsqueeze { dim: 1 }),
14226            "Squeeze backward must be Unsqueeze at the same dim"
14227        );
14228    }
14229
14230    #[test]
14231    fn floor_builder_produces_unary_node_same_dtype() {
14232        // NodeHandle::floor builds a unary node preserving shape + dtype.
14233        let a =
14234            NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14235        let f = a.floor();
14236        assert_eq!(f.shape().dims(), &[3]);
14237        assert_eq!(f.dtype(), DType::F32);
14238        let node = f.graph().read().unwrap().node(f.id()).clone();
14239        assert!(matches!(node.op, Op::Floor));
14240        assert_eq!(node.inputs, vec![a.id()]);
14241    }
14242
14243    #[test]
14244    fn backward_through_floor_drops_gradient_silently() {
14245        // Op::Floor has zero gradient almost everywhere; the inline
14246        // backward arm is a no-op. backward() must succeed and the
14247        // input gets no gradient (the input's upstream is never
14248        // populated through the Floor node).
14249        let a =
14250            NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14251        let y = a.floor();
14252        let grads = y.backward();
14253        // a's gradient is dropped — no entry in the GradMap.
14254        assert!(
14255            grads.get(&a).is_none(),
14256            "Floor must not propagate gradient to its input"
14257        );
14258    }
14259
14260    #[test]
14261    fn where_cond_builder_produces_ternary_with_a_dtype() {
14262        // self is a Bool cond (GAP-168(c)); a/b are F32. Output dtype = F32
14263        // (= a's dtype), shape = self.shape() (= a.shape() = b.shape()).
14264        // Op::Where node carries 3 inputs in order (cond, a, b).
14265        let a =
14266            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14267        let b = a
14268            .const_f32_like(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3]))
14269            .unwrap();
14270        let eq_a_b = a.eq(&b); // Bool mask
14271        let picked = eq_a_b.where_cond(&a, &b);
14272        assert_eq!(picked.shape().dims(), &[3]);
14273        assert_eq!(picked.dtype(), DType::F32, "Where output dtype = a/b dtype");
14274        let node = picked.graph().read().unwrap().node(picked.id()).clone();
14275        assert!(matches!(node.op, Op::Where));
14276        assert_eq!(node.inputs.len(), 3);
14277        assert_eq!(
14278            node.inputs,
14279            vec![eq_a_b.id(), a.id(), b.id()],
14280            "Where input order: (cond, a, b)"
14281        );
14282    }
14283
14284    #[test]
14285    fn backward_reuses_exp_forward_output() {
14286        // Exp's backward rule uses the forward output directly. The
14287        // gradient for x should be a Mul whose inputs include the
14288        // forward Exp node (not a new Exp node).
14289        let a = NodeHandle::from_f32(vec![0.0, 1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14290        let e = a.exp();
14291        let exp_forward_id = e.id();
14292        let grads = e.backward();
14293        let g_a = grads.get(&a).unwrap();
14294        let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
14295        assert!(matches!(node.op, Op::Mul));
14296        // One of the Mul's inputs should be the original forward Exp node.
14297        assert!(
14298            node.inputs.contains(&exp_forward_id),
14299            "Exp backward should reference the forward output ({exp_forward_id:?}), \
14300             got inputs {:?}",
14301            node.inputs,
14302        );
14303    }
14304
14305    // ---- Op::WriteSlice (Phase E.3.2) ---------------------------------------
14306
14307    #[test]
14308    fn write_slice_destructive_input_is_zero() {
14309        let op = Op::WriteSlice {
14310            ranges: vec![(0, 1), (0, 32), (0, 128)],
14311            dyn_offset: None,
14312        };
14313        assert_eq!(op.destructive_input(), Some(0));
14314    }
14315
14316    #[test]
14317    fn write_slice_short_name() {
14318        let op = Op::WriteSlice {
14319            ranges: vec![(0, 1)],
14320            dyn_offset: None,
14321        };
14322        assert_eq!(op.short_name(), "WriteSlice");
14323    }
14324
14325    #[test]
14326    fn write_slice_emits_op_writeslice_node() {
14327        // dest shape [4, 3]; source shape [1, 3]; write at row 2.
14328        let dest =
14329            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14330        let src = dest
14331            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14332            .unwrap();
14333        let out = dest
14334            .write_slice(&src, vec![(2, 3), (0, 3)])
14335            .expect("write_slice should accept matching shapes");
14336        let g = out.graph().read().unwrap();
14337        match &g.node(out.id()).op {
14338            Op::WriteSlice { ranges, dyn_offset } => {
14339                assert_eq!(ranges, &vec![(2, 3), (0, 3)]);
14340                assert_eq!(dyn_offset, &None);
14341            }
14342            other => panic!("expected Op::WriteSlice, got {other:?}"),
14343        }
14344        assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14345        // Output shape == destination shape; bytes are post-write same buffer.
14346        assert_eq!(g.node(out.id()).shape.dims(), &[4, 3]);
14347    }
14348
14349    #[test]
14350    fn write_slice_dyn_records_dynamic_offset() {
14351        use fuel_ir::{DynScalar, SymId};
14352        // dest capacity [8, 3]; source [1, 3]; dynamic start on axis 0.
14353        let dest =
14354            NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[8, 3]), cpu_dev()).unwrap();
14355        let src = dest
14356            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14357            .unwrap();
14358        let sym = SymId(0);
14359        // ranges[0].0 is ignored (start is dynamic); width = 1 - 0 = 1
14360        // matches source dim 0. Axis 1 is static, full width.
14361        let out = dest
14362            .write_slice_dyn(&src, vec![(0, 1), (0, 3)], 0, DynScalar::Sym(sym))
14363            .expect("write_slice_dyn should accept matching widths");
14364        let g = out.graph().read().unwrap();
14365        match &g.node(out.id()).op {
14366            Op::WriteSlice { ranges, dyn_offset } => {
14367                assert_eq!(ranges, &vec![(0, 1), (0, 3)]);
14368                assert_eq!(dyn_offset, &Some((0, DynScalar::Sym(sym))));
14369            }
14370            other => panic!("expected Op::WriteSlice, got {other:?}"),
14371        }
14372        assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14373        assert_eq!(g.node(out.id()).shape.dims(), &[8, 3]);
14374    }
14375
14376    #[test]
14377    fn write_slice_dyn_rejects_slab_wider_than_capacity() {
14378        use fuel_ir::{DynScalar, SymId};
14379        // dest capacity on axis 0 is 2, but the dynamic-axis slab is
14380        // width 4 — can never fit regardless of the runtime offset.
14381        let dest =
14382            NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14383        let src = dest
14384            .const_f32_like(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]))
14385            .unwrap();
14386        let err = dest.write_slice_dyn(&src, vec![(0, 4), (0, 3)], 0, DynScalar::Sym(SymId(0)));
14387        assert!(
14388            err.is_err(),
14389            "dynamic-axis slab wider than capacity must error at build"
14390        );
14391    }
14392
14393    #[test]
14394    fn write_slice_dyn_rejects_axis_out_of_bounds() {
14395        use fuel_ir::{DynScalar, SymId};
14396        let dest =
14397            NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14398        let src = dest
14399            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14400            .unwrap();
14401        let err = dest.write_slice_dyn(&src, vec![(0, 1), (0, 3)], 5, DynScalar::Sym(SymId(0)));
14402        assert!(err.is_err(), "dyn_axis past rank must error");
14403    }
14404
14405    #[test]
14406    fn flash_attn_dyn_records_runtime_k_len() {
14407        use fuel_ir::{DynScalar, SymId};
14408        // q [1, 2, 3, 4]; K/V capacity [1, 1, 8, 4] (GQA Hq=2, Hkv=1).
14409        let q = NodeHandle::from_f32(
14410            vec![0.0_f32; 2 * 3 * 4],
14411            Shape::from_dims(&[1, 2, 3, 4]),
14412            cpu_dev(),
14413        )
14414        .unwrap();
14415        let k = q
14416            .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14417            .unwrap();
14418        let v = q
14419            .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14420            .unwrap();
14421        let sym = SymId(0);
14422        let out = q.flash_attn_dyn(
14423            &k,
14424            &v,
14425            None,
14426            /*scale*/ 0.5,
14427            /*causal*/ true,
14428            None,
14429            None,
14430            None,
14431            DynScalar::Sym(sym),
14432        );
14433        // Output adopts q's shape, not the capacity.
14434        assert_eq!(out.shape().dims(), &[1, 2, 3, 4]);
14435        let g = out.graph().read().unwrap();
14436        match &g.node(out.id()).op {
14437            Op::Fused(fid, crate::registry::FusedOpParams::FlashAttn { causal, k_len, .. })
14438                if *fid == crate::registry::FusedOps::FLASH_ATTN =>
14439            {
14440                assert!(*causal);
14441                assert_eq!(k_len, &Some(DynScalar::Sym(sym)));
14442            }
14443            other => panic!("expected Op::Fused(FLASH_ATTN, FlashAttn), got {other:?}"),
14444        }
14445        assert_eq!(g.node(out.id()).inputs, vec![q.id(), k.id(), v.id()]);
14446    }
14447
14448    #[test]
14449    #[should_panic(expected = "k_len")]
14450    fn flash_attn_dyn_concrete_k_len_exceeding_capacity_panics() {
14451        use fuel_ir::DynScalar;
14452        let q = NodeHandle::from_f32(
14453            vec![0.0_f32; 2 * 4],
14454            Shape::from_dims(&[1, 1, 2, 4]),
14455            cpu_dev(),
14456        )
14457        .unwrap();
14458        let k = q
14459            .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14460            .unwrap();
14461        let v = q
14462            .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14463            .unwrap();
14464        // Concrete k_len=5 > capacity 4 → build-time panic.
14465        let _ = q.flash_attn_dyn(
14466            &k,
14467            &v,
14468            None,
14469            1.0,
14470            true,
14471            None,
14472            None,
14473            None,
14474            DynScalar::Concrete(5),
14475        );
14476    }
14477
14478    #[test]
14479    fn write_slice_rejects_rank_mismatch() {
14480        let dest =
14481            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14482        let src = dest
14483            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
14484            .unwrap();
14485        // ranges has rank 2 (matches dest) but source has rank 1.
14486        let err = dest.write_slice(&src, vec![(0, 1), (0, 3)]);
14487        assert!(err.is_err(), "rank mismatch must error");
14488    }
14489
14490    // ---- cross-graph operands must fail at BUILD time, never hang -----------
14491    //
14492    // Node ids are indices into ONE graph's arena, so an operand built on a
14493    // DIFFERENT graph records an id that indexes an unrelated node (or none),
14494    // producing a malformed dependency graph. The failure surfaces as neither
14495    // a panic nor an error: the executor **HANGS at realize**, waiting on a
14496    // dependency that can never resolve — low CPU, no stack, no message. That
14497    // is strictly worse than a panic, and it violates two rules at once:
14498    // "validate at graph-build time" and never-hang.
14499    //
14500    // `matmul`, `qmatmul`, `conv2d`, `paged_attn`, and everything routed via
14501    // `binary_op` already assert this. These builders did not — a real cost: a
14502    // peer session spent a long bisect localizing exactly this on `write_slice`.
14503    //
14504    // These tests only BUILD, never realize, so before the fix they fail fast
14505    // instead of hanging the suite.
14506
14507    #[test]
14508    fn write_slice_rejects_cross_graph_source() {
14509        let dest =
14510            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14511        // A SECOND `from_*` mints a second graph — the easy mistake to make,
14512        // and currently the un-diagnosable one.
14513        let foreign =
14514            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]), cpu_dev())
14515                .unwrap();
14516        assert_ne!(
14517            dest.graph_id(),
14518            foreign.graph_id(),
14519            "fixture must be cross-graph"
14520        );
14521
14522        let err = dest.write_slice(&foreign, vec![(2, 3), (0, 3)]);
14523        assert!(
14524            err.is_err(),
14525            "cross-graph source must be a build-time Err, not a realize-time hang",
14526        );
14527        let msg = format!("{}", err.unwrap_err());
14528        assert!(
14529            msg.contains("same graph"),
14530            "error should say the operands must share a graph, got: {msg}",
14531        );
14532    }
14533
14534    #[test]
14535    fn masked_fill_rejects_cross_graph_mask() {
14536        let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14537        let foreign_mask =
14538            NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14539        assert_ne!(
14540            x.graph_id(),
14541            foreign_mask.graph_id(),
14542            "fixture must be cross-graph"
14543        );
14544
14545        let err = x.masked_fill(&foreign_mask, Scalar::F32(0.0));
14546        assert!(
14547            err.is_err(),
14548            "cross-graph mask must be a build-time Err, not a realize-time hang",
14549        );
14550        // MUST assert the reason, not just is_err(): this fixture also has a
14551        // dtype mismatch, so a bare `is_err()` passes for the WRONG reason and
14552        // would stay green even with no graph check at all.
14553        let msg = format!("{}", err.unwrap_err());
14554        assert!(
14555            msg.contains("same graph"),
14556            "must fail on GRAPH affinity, not incidentally on dtype, got: {msg}",
14557        );
14558    }
14559
14560    #[test]
14561    fn masked_fill_rejects_scale_dtype_at_build() {
14562        // F8E8M0 is a block-scale dtype: it HAS a scalar value (so the
14563        // value-dtype check passes) but no zero, so the MaskedFill backward
14564        // cannot produce a gradient. Reject at build time — and this must fail
14565        // on the dtype guard specifically: graph / shape / mask-Bool / value-dtype
14566        // are all satisfied, so a bare `is_err()` can only be the guard firing.
14567        let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14568        let scale = x.cast(DType::F8E8M0);
14569        let mask = x.cast(DType::Bool);
14570        let value = Scalar::one(DType::F8E8M0).unwrap();
14571
14572        let err = scale.masked_fill(&mask, value);
14573        assert!(
14574            err.is_err(),
14575            "masked_fill on a scale dtype must be a build-time Err"
14576        );
14577        let msg = format!("{}", err.unwrap_err());
14578        assert!(
14579            msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14580            "must fail on the packed/scale dtype guard, got: {msg}",
14581        );
14582    }
14583
14584    /// GAP-075 fix B: pin the REJECT verdict for every unfillable dtype
14585    /// individually (not a bucket count). The guard is semantic — packed
14586    /// formats (F4/F6*) have no representable fill value; block-scales
14587    /// (F8E8M0/F8E6M2) have no zero for the zero-filling backward — so each must
14588    /// be a build-time Err on the dtype GUARD specifically (its message names
14589    /// the op). Per-dtype pinning protects the classification: a future dtype
14590    /// misfiled into the allow arm can't hide behind a passing tally, and a new
14591    /// dtype with no verdict is caught by the compiler (the match is exhaustive,
14592    /// no wildcard). Paired with the allow test below (opposite assertion), the
14593    /// two are mutually non-vacuous.
14594    #[test]
14595    fn masked_fill_rejects_every_unfillable_dtype() {
14596        for dt in [
14597            DType::F4,
14598            DType::F6E2M3,
14599            DType::F6E3M2,
14600            DType::F8E8M0,
14601            DType::F8E6M2,
14602        ] {
14603            let x =
14604                NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14605            let t = x.cast(dt);
14606            let mask = x.cast(DType::Bool);
14607            // The dtype guard fires before the value-dtype check, so a dummy
14608            // value is fine; the message assertion proves it was the guard.
14609            let err = t.masked_fill(&mask, Scalar::F32(0.0));
14610            assert!(err.is_err(), "masked_fill must reject {dt:?} at build time");
14611            let msg = format!("{}", err.unwrap_err());
14612            assert!(
14613                msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14614                "{dt:?} must fail on the semantic dtype guard, got: {msg}",
14615            );
14616        }
14617    }
14618
14619    /// GAP-075 fix B: the allow arm is a graph-build PERMISSION (masked_fill is
14620    /// semantically well-defined — a fill value + a zero), NOT a claim a backend
14621    /// can allocate/run the dtype. F32 is the live consumer path (attention
14622    /// masking); I32 is an allowed verdict no consumer currently exercises —
14623    /// locking it preserves today's answer without asserting integer masked_fill
14624    /// is known to compute correctly (a backend lacking I32 storage still
14625    /// declines loudly at allocation, downstream of this permission).
14626    #[test]
14627    fn masked_fill_permits_fillable_dtypes_as_permission_not_capability() {
14628        let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14629        let mask = x.cast(DType::Bool);
14630        assert!(
14631            x.masked_fill(&mask, Scalar::F32(0.0)).is_ok(),
14632            "F32 masked_fill must build (the live consumer path)",
14633        );
14634        let xi = x.cast(DType::I32);
14635        assert!(
14636            xi.masked_fill(&mask, Scalar::one(DType::I32).unwrap())
14637                .is_ok(),
14638            "I32 masked_fill must build — permission preserved, not a correctness claim",
14639        );
14640    }
14641
14642    #[test]
14643    #[should_panic(expected = "same graph")]
14644    fn rope_with_tables_panics_on_cross_graph_tables() {
14645        // Returns `NodeHandle`, so it follows the convention of the already-checked
14646        // builders (`matmul`, `paged_attn`) and asserts. A panic names the
14647        // problem at the build site; the status quo hangs later saying nothing.
14648        let x = NodeHandle::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[1, 1, 2, 4]), cpu_dev())
14649            .unwrap();
14650        let cos =
14651            NodeHandle::from_f32(vec![1.0_f32; 8], Shape::from_dims(&[2, 4]), cpu_dev()).unwrap();
14652        let sin = x
14653            .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]))
14654            .unwrap();
14655        let _ = x.rope_with_tables(&cos, &sin);
14656    }
14657
14658    #[test]
14659    fn write_slice_rejects_slab_width_mismatch() {
14660        let dest =
14661            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14662        // Source has 2 elements along axis 0, but slab is width 1.
14663        let src = dest
14664            .const_f32_like(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]))
14665            .unwrap();
14666        let err = dest.write_slice(&src, vec![(2, 3), (0, 3)]);
14667        assert!(err.is_err(), "slab-width mismatch must error");
14668    }
14669
14670    #[test]
14671    fn write_slice_rejects_range_past_dest_extent() {
14672        let dest =
14673            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14674        let src = dest
14675            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14676            .unwrap();
14677        // axis 0: dest extent is 4; range [4, 5) is out of bounds.
14678        let err = dest.write_slice(&src, vec![(4, 5), (0, 3)]);
14679        assert!(err.is_err(), "range past dest extent must error");
14680    }
14681
14682    #[test]
14683    fn write_slice_derives_ordering_after_other_readers() {
14684        // Graph:
14685        //   dest = ...; src = ...
14686        //   ro = dest.relu()                          (non-destructive reader of dest)
14687        //   w  = dest.write_slice(&src, [(0,1),(0,3)])  (destructive on dest)
14688        // Expected ordering: w must run after ro.
14689        let dest =
14690            NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14691        let src = dest
14692            .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14693            .unwrap();
14694        let ro = dest.relu();
14695        let w = dest.write_slice(&src, vec![(0, 1), (0, 3)]).unwrap();
14696        let ord = crate::opt::derive_ordering(&dest.graph().read().unwrap(), &[ro.id(), w.id()]);
14697        let deps = ord.deps_of(w.id());
14698        assert_eq!(
14699            deps.len(),
14700            1,
14701            "write_slice should have one ordering dep (the relu)"
14702        );
14703        assert_eq!(
14704            deps[0],
14705            ro.id(),
14706            "write_slice must run after the non-destructive reader"
14707        );
14708    }
14709
14710    // ---- In-place ops Phase 1 -----------------------------------------------
14711    //
14712    // Smoke tests for the 5 new in-place unary variants
14713    // (`Op::ReluInplace`, `Op::SiluInplace`, `Op::GeluTanhInplace`,
14714    // `Op::TanhInplace`, `Op::SigmoidInplace`) and `FusedOps::INPLACE_AFFINE`.
14715    // Phase 1 only ships the structural plumbing (Op IR + destructive_input +
14716    // short_name + scheduler integration); dispatch + autograd land in Phases
14717    // 3 + 4. See `docs/session-prompts/in-place-ops-infrastructure.md`.
14718
14719    #[test]
14720    fn inplace_unary_destructive_input_is_zero() {
14721        for op in [
14722            Op::ReluInplace,
14723            Op::SiluInplace,
14724            Op::GeluTanhInplace,
14725            Op::TanhInplace,
14726            Op::SigmoidInplace,
14727            Op::NegInplace,
14728            Op::AbsInplace,
14729            Op::SqrInplace,
14730            Op::SqrtInplace,
14731            Op::RsqrtInplace,
14732            Op::RecipInplace,
14733            Op::ExpInplace,
14734            Op::LogInplace,
14735            Op::SinInplace,
14736            Op::CosInplace,
14737            Op::SignInplace,
14738            Op::FloorInplace,
14739            Op::CeilInplace,
14740            Op::RoundInplace,
14741            Op::ErfInplace,
14742            Op::GeluInplace,
14743        ] {
14744            assert_eq!(
14745                op.destructive_input(),
14746                Some(0),
14747                "in-place unary {op:?} must declare input 0 destructive",
14748            );
14749        }
14750    }
14751
14752    #[test]
14753    fn inplace_unary_short_names_round_trip() {
14754        assert_eq!(Op::ReluInplace.short_name(), "ReluInplace");
14755        assert_eq!(Op::SiluInplace.short_name(), "SiluInplace");
14756        assert_eq!(Op::GeluTanhInplace.short_name(), "GeluTanhInplace");
14757        assert_eq!(Op::TanhInplace.short_name(), "TanhInplace");
14758        assert_eq!(Op::SigmoidInplace.short_name(), "SigmoidInplace");
14759        assert_eq!(Op::NegInplace.short_name(), "NegInplace");
14760        assert_eq!(Op::AbsInplace.short_name(), "AbsInplace");
14761        assert_eq!(Op::SqrInplace.short_name(), "SqrInplace");
14762        assert_eq!(Op::SqrtInplace.short_name(), "SqrtInplace");
14763        assert_eq!(Op::RsqrtInplace.short_name(), "RsqrtInplace");
14764        assert_eq!(Op::RecipInplace.short_name(), "RecipInplace");
14765        assert_eq!(Op::ExpInplace.short_name(), "ExpInplace");
14766        assert_eq!(Op::LogInplace.short_name(), "LogInplace");
14767        assert_eq!(Op::SinInplace.short_name(), "SinInplace");
14768        assert_eq!(Op::CosInplace.short_name(), "CosInplace");
14769        assert_eq!(Op::SignInplace.short_name(), "SignInplace");
14770        assert_eq!(Op::FloorInplace.short_name(), "FloorInplace");
14771        assert_eq!(Op::CeilInplace.short_name(), "CeilInplace");
14772        assert_eq!(Op::RoundInplace.short_name(), "RoundInplace");
14773        assert_eq!(Op::ErfInplace.short_name(), "ErfInplace");
14774        assert_eq!(Op::GeluInplace.short_name(), "GeluInplace");
14775        assert_eq!(
14776            Op::ClampInplace { min: 0.0, max: 1.0 }.short_name(),
14777            "ClampInplace"
14778        );
14779        assert_eq!(Op::PowIInplace(3).short_name(), "PowIInplace");
14780    }
14781
14782    #[test]
14783    fn inplace_affine_fused_op_destructive_input_is_zero() {
14784        let op = Op::Fused(
14785            crate::registry::FusedOps::INPLACE_AFFINE,
14786            crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 },
14787        );
14788        assert_eq!(op.destructive_input(), Some(0));
14789    }
14790
14791    #[test]
14792    fn destructive_input_for_fused_is_registry_declared() {
14793        // GAP-076: a fused op's destructiveness is a MANDATORY declared field on
14794        // its registry entry, and `Op::destructive_input` reads that field via
14795        // `default_registry()` rather than a hardcoded id match that could drift
14796        // out of sync. This locks BOTH directions of the declaration plus the
14797        // routing that reads it. Regression lock, not a born-red: no op was
14798        // misclassified before the fix — its value is that a future wrong
14799        // declaration (or a reverted routing) reddens HERE instead of surfacing
14800        // as an intermittent scheduler data race that points nowhere near this
14801        // code. The exhaustive match in `Op::destructive_input` and the
14802        // mandatory struct field are the compile-time seams; this is the belt.
14803        use crate::registry::{FusedOps, default_registry};
14804        let reg = default_registry();
14805        assert_eq!(
14806            reg.entry(FusedOps::INPLACE_AFFINE)
14807                .expect("INPLACE_AFFINE is registered")
14808                .destructive_input,
14809            Some(0),
14810            "InplaceAffine must declare itself destructive on input 0",
14811        );
14812        assert_eq!(
14813            reg.entry(FusedOps::SOFTMAX_LAST_DIM)
14814                .expect("SOFTMAX_LAST_DIM is registered")
14815                .destructive_input,
14816            None,
14817            "a functional fused op must declare itself non-destructive",
14818        );
14819        // Routing reads the declared field (not a hardcoded id match).
14820        let op = Op::Fused(
14821            FusedOps::INPLACE_AFFINE,
14822            crate::registry::FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 },
14823        );
14824        assert_eq!(op.destructive_input(), Some(0));
14825    }
14826
14827    #[test]
14828    fn inplace_affine_params_key_dedupe_on_same_mul_add() {
14829        // Two `InplaceAffine` params with identical (mul, add) hash to the
14830        // same key; differing values produce distinct keys. Lets CSE / the
14831        // existing op_key infrastructure collapse identical in-place affines
14832        // (when callers wire them through the equivalent graph machinery).
14833        let a = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14834        let b = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14835        let c = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 0.5 };
14836        assert_eq!(a.key(), b.key(), "identical mul/add must dedupe");
14837        assert_ne!(a.key(), c.key(), "different add must produce distinct key");
14838    }
14839
14840    // ---- Phase 4 — autograd through in-place ops ----
14841    //
14842    // The view-aware `derive_ordering` (Phase 4a) ensures backward
14843    // grad nodes that read forward inputs run BEFORE any in-place
14844    // mutation of those inputs. The backward arms in
14845    // `NodeHandle::backward` (Phase 4b) emit the same gradient graph as
14846    // the non-inplace cousins. These tests prove that calling
14847    // `.backward()` through an in-place node:
14848    //   (1) does NOT panic (was previously guarded by the Phase 1
14849    //       defensive panic);
14850    //   (2) emits the same gradient-node structure as the non-inplace
14851    //       cousin (matching node counts + op types as a structural
14852    //       proxy for numerical equivalence — the actual numerics are
14853    //       exercised by the live oracle tests in fuel-storage).
14854
14855    #[test]
14856    fn backward_through_relu_inplace_does_not_panic() {
14857        // y = x.relu_inplace(); loss = y.sum_all(); loss.backward()
14858        // Phase 1's defensive panic is removed; backward emits
14859        // Op::Step(x) + Op::Mul(upstream, step) — same as Op::Relu.
14860        let x =
14861            NodeHandle::from_f32(vec![1.0, -2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14862        let y = x.relu_inplace();
14863        let loss = y.sum_all();
14864        let grads = loss.backward();
14865        let g_x = grads.get(&x).expect("gradient for x should be present");
14866        // Same structural form as Op::Relu's backward: gradient node
14867        // is an Op::Mul (upstream × step(x)).
14868        let g_node = g_x.graph().read().unwrap().node(g_x.id()).clone();
14869        assert!(
14870            matches!(g_node.op, Op::Mul),
14871            "relu backward grad is Mul; got {:?}",
14872            g_node.op
14873        );
14874    }
14875
14876    #[test]
14877    fn backward_through_sigmoid_inplace_does_not_panic() {
14878        let x = NodeHandle::from_f32(vec![0.5, -0.5], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14879        let y = x.sigmoid_inplace();
14880        let loss = y.sum_all();
14881        let grads = loss.backward();
14882        let g_x = grads.get(&x);
14883        assert!(g_x.is_some());
14884    }
14885
14886    #[test]
14887    fn backward_through_tanh_inplace_does_not_panic() {
14888        let x =
14889            NodeHandle::from_f32(vec![0.1, 0.2, 0.3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14890        let y = x.tanh_inplace();
14891        let loss = y.sum_all();
14892        let grads = loss.backward();
14893        let g_x = grads.get(&x);
14894        assert!(g_x.is_some());
14895    }
14896
14897    #[test]
14898    fn backward_through_silu_inplace_does_not_panic() {
14899        let x = NodeHandle::from_f32(vec![0.1, 0.2], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14900        let y = x.silu_inplace();
14901        let loss = y.sum_all();
14902        let grads = loss.backward();
14903        let g_x = grads.get(&x);
14904        assert!(g_x.is_some());
14905    }
14906
14907    /// The reverse walk has hand-written arms for some fused ids and lowers the
14908    /// rest through their total `decompose` first; WHICH ids take the second path
14909    /// is whatever the registry declares as `BackwardKind::Decompose`. Pin that
14910    /// set so adding or flipping one is a deliberate change that also adds its
14911    /// finite-difference test (SSM recipes: `fuel-tensor` scan tests;
14912    /// FusedSoftmaxCrossEntropy: `fuel-training`; NF4/AWQ matmul and causal
14913    /// conv1d: `fuel-tensor` `*_gradient_matches_finite_difference`).
14914    #[test]
14915    fn decompose_declared_fused_ops_are_exactly_the_tested_set() {
14916        use crate::registry::{BackwardKind, FusedOps, default_registry};
14917        let declared: Vec<_> = default_registry()
14918            .entries_iter()
14919            .filter(|e| e.backward == BackwardKind::Decompose)
14920            .map(|e| e.id)
14921            .collect();
14922        let expected = [
14923            FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
14924            FusedOps::SELECTIVE_SCAN,
14925            FusedOps::SSD_CHUNK_SCAN,
14926            FusedOps::NF4_MATMUL,
14927            FusedOps::AWQ_MATMUL,
14928            FusedOps::CAUSAL_CONV1D,
14929        ];
14930        assert_eq!(declared.len(), expected.len(), "declared: {declared:?}");
14931        for id in expected {
14932            assert!(declared.contains(&id), "{id:?} lost its Decompose backward");
14933            assert!(
14934                lowers_for_backward(id),
14935                "{id:?} not lowered by the pre-pass"
14936            );
14937        }
14938        // Control: a hand-armed op is not lowered.
14939        assert!(!lowers_for_backward(FusedOps::SOFTMAX_LAST_DIM));
14940    }
14941
14942    #[test]
14943    fn backward_through_gelu_tanh_inplace_does_not_panic() {
14944        // Numerics are checked against finite differences in fuel-tensor
14945        // (`gelu_tanh_inplace_backward_matches_finite_difference`).
14946        let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14947        let y = x.gelu_tanh_inplace();
14948        let loss = y.sum_all();
14949        let grads = loss.backward();
14950        assert!(grads.get(&x).is_some());
14951    }
14952
14953    #[test]
14954    fn backward_through_gelu_tanh_does_not_panic() {
14955        let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14956        let loss = x.gelu_tanh().sum_all();
14957        let grads = loss.backward();
14958        assert!(grads.get(&x).is_some());
14959    }
14960
14961    #[test]
14962    fn backward_through_relu_inplace_emits_same_graph_shape_as_functional() {
14963        // Structural parity: relu_inplace backward emits the same node
14964        // count + same op variants as relu backward, since the
14965        // gradient formula is identical.
14966        let x_inp =
14967            NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14968        let y_inp = x_inp.relu_inplace();
14969        let loss_inp = y_inp.sum_all();
14970        let nodes_before_inp = loss_inp.graph().read().unwrap().len();
14971        let _ = loss_inp.backward();
14972        let added_inp = loss_inp.graph().read().unwrap().len() - nodes_before_inp;
14973
14974        let x_fn =
14975            NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14976        let y_fn = x_fn.relu();
14977        let loss_fn = y_fn.sum_all();
14978        let nodes_before_fn = loss_fn.graph().read().unwrap().len();
14979        let _ = loss_fn.backward();
14980        let added_fn = loss_fn.graph().read().unwrap().len() - nodes_before_fn;
14981
14982        assert_eq!(
14983            added_inp, added_fn,
14984            "ReluInplace backward should add the same number of nodes as Relu backward ({added_fn}), got {added_inp}",
14985        );
14986    }
14987
14988    #[test]
14989    fn relu_inplace_builder_emits_op_reluinplace() {
14990        let x = NodeHandle::from_f32(
14991            vec![1.0_f32, -1.0, 2.0, -2.0],
14992            Shape::from_dims(&[4]),
14993            cpu_dev(),
14994        )
14995        .unwrap();
14996        let y = x.relu_inplace();
14997        let g = y.graph().read().unwrap();
14998        let node = g.node(y.id());
14999        assert!(matches!(node.op, Op::ReluInplace));
15000        assert_eq!(node.inputs, vec![x.id()]);
15001        assert_eq!(node.shape.dims(), &[4]);
15002        assert_eq!(node.dtype, DType::F32);
15003    }
15004
15005    #[test]
15006    fn affine_inplace_builder_emits_fused_inplace_affine() {
15007        let x = NodeHandle::from_f32(
15008            vec![1.0_f32, 2.0, 3.0, 4.0],
15009            Shape::from_dims(&[4]),
15010            cpu_dev(),
15011        )
15012        .unwrap();
15013        let y = x.affine_inplace(2.0, 0.5);
15014        let g = y.graph().read().unwrap();
15015        let node = g.node(y.id());
15016        match &node.op {
15017            Op::Fused(id, crate::registry::FusedOpParams::InplaceAffine { mul, add }) => {
15018                assert_eq!(*id, crate::registry::FusedOps::INPLACE_AFFINE);
15019                assert_eq!(*mul, 2.0);
15020                assert_eq!(*add, 0.5);
15021            }
15022            other => panic!("expected Op::Fused(INPLACE_AFFINE, InplaceAffine), got {other:?}"),
15023        }
15024        assert_eq!(node.inputs, vec![x.id()]);
15025        assert_eq!(node.shape.dims(), &[4]);
15026    }
15027
15028    #[test]
15029    fn all_inplace_unary_builders_round_trip_through_op_variants() {
15030        // One smoke per variant — each builder emits exactly the
15031        // matching `Op::*Inplace` variant, single input, shape +
15032        // dtype unchanged.
15033        let x = NodeHandle::from_f32(vec![0.5_f32; 8], Shape::from_dims(&[8]), cpu_dev()).unwrap();
15034        fn check(y: NodeHandle, x_id: NodeId, expect: fn(&Op) -> bool) {
15035            let g = y.graph().read().unwrap();
15036            let node = g.node(y.id());
15037            assert!(expect(&node.op), "wrong Op variant: {:?}", node.op);
15038            assert_eq!(node.inputs, vec![x_id]);
15039            assert_eq!(node.shape.dims(), &[8]);
15040            assert_eq!(node.dtype, DType::F32);
15041        }
15042        check(x.relu_inplace(), x.id(), |o| matches!(o, Op::ReluInplace));
15043        check(x.silu_inplace(), x.id(), |o| matches!(o, Op::SiluInplace));
15044        check(x.gelu_tanh_inplace(), x.id(), |o| {
15045            matches!(o, Op::GeluTanhInplace)
15046        });
15047        check(x.tanh_inplace(), x.id(), |o| matches!(o, Op::TanhInplace));
15048        check(x.sigmoid_inplace(), x.id(), |o| {
15049            matches!(o, Op::SigmoidInplace)
15050        });
15051        check(x.neg_inplace(), x.id(), |o| matches!(o, Op::NegInplace));
15052        check(x.abs_inplace(), x.id(), |o| matches!(o, Op::AbsInplace));
15053        check(x.sqr_inplace(), x.id(), |o| matches!(o, Op::SqrInplace));
15054        check(x.sqrt_inplace(), x.id(), |o| matches!(o, Op::SqrtInplace));
15055        check(x.rsqrt_inplace(), x.id(), |o| matches!(o, Op::RsqrtInplace));
15056        check(x.recip_inplace(), x.id(), |o| matches!(o, Op::RecipInplace));
15057        check(x.exp_inplace(), x.id(), |o| matches!(o, Op::ExpInplace));
15058        check(x.log_inplace(), x.id(), |o| matches!(o, Op::LogInplace));
15059        check(x.sin_inplace(), x.id(), |o| matches!(o, Op::SinInplace));
15060        check(x.cos_inplace(), x.id(), |o| matches!(o, Op::CosInplace));
15061        check(x.sign_inplace(), x.id(), |o| matches!(o, Op::SignInplace));
15062        check(x.floor_inplace(), x.id(), |o| matches!(o, Op::FloorInplace));
15063        check(x.ceil_inplace(), x.id(), |o| matches!(o, Op::CeilInplace));
15064        check(x.round_inplace(), x.id(), |o| matches!(o, Op::RoundInplace));
15065        check(x.erf_inplace(), x.id(), |o| matches!(o, Op::ErfInplace));
15066        check(x.gelu_inplace(), x.id(), |o| matches!(o, Op::GeluInplace));
15067        check(x.clamp_inplace(-1.0, 1.0), x.id(), |o| {
15068            matches!(o, Op::ClampInplace { .. })
15069        });
15070        check(x.powi_inplace(3), x.id(), |o| {
15071            matches!(o, Op::PowIInplace(3))
15072        });
15073    }
15074
15075    /// Backward smoke for the expanded in-place op family — each variant
15076    /// (except zero-grad ones) must produce a gradient node for x without
15077    /// panicking. Zero-grad variants (Sign/Floor/Ceil/Round) drop the
15078    /// gradient entirely (no entry in the GradMap), mirroring their
15079    /// non-inplace cousins.
15080    #[test]
15081    fn backward_through_expanded_inplace_unary_emits_grad() {
15082        fn check_emits_grad(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
15083            let x =
15084                NodeHandle::from_f32(vec![0.5_f32, 1.5, 2.5], Shape::from_dims(&[3]), cpu_dev())
15085                    .unwrap();
15086            let y = make(&x);
15087            let loss = y.sum_all();
15088            let grads = loss.backward();
15089            assert!(grads.get(&x).is_some(), "backward must emit gradient for x");
15090        }
15091        check_emits_grad(|x| x.neg_inplace());
15092        check_emits_grad(|x| x.abs_inplace());
15093        check_emits_grad(|x| x.sqr_inplace());
15094        check_emits_grad(|x| x.sqrt_inplace());
15095        check_emits_grad(|x| x.rsqrt_inplace());
15096        check_emits_grad(|x| x.recip_inplace());
15097        check_emits_grad(|x| x.exp_inplace());
15098        check_emits_grad(|x| x.log_inplace());
15099        check_emits_grad(|x| x.sin_inplace());
15100        check_emits_grad(|x| x.cos_inplace());
15101        check_emits_grad(|x| x.erf_inplace());
15102        check_emits_grad(|x| x.gelu_inplace());
15103        check_emits_grad(|x| x.clamp_inplace(-1.0, 2.0));
15104        check_emits_grad(|x| x.powi_inplace(3));
15105    }
15106
15107    #[test]
15108    fn backward_through_zero_grad_inplace_drops_gradient() {
15109        fn check_drops(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
15110            let x =
15111                NodeHandle::from_f32(vec![1.5_f32, 2.5, -3.5], Shape::from_dims(&[3]), cpu_dev())
15112                    .unwrap();
15113            let y = make(&x);
15114            let loss = y.sum_all();
15115            let grads = loss.backward();
15116            assert!(
15117                grads.get(&x).is_none(),
15118                "zero-grad in-place op must not emit gradient"
15119            );
15120        }
15121        check_drops(|x| x.sign_inplace());
15122        check_drops(|x| x.floor_inplace());
15123        check_drops(|x| x.ceil_inplace());
15124        check_drops(|x| x.round_inplace());
15125    }
15126
15127    #[test]
15128    fn inplace_unary_derives_ordering_after_non_destructive_readers() {
15129        // Graph:
15130        //   x   = const f32 [4]
15131        //   y_a = x.relu()                  (non-destructive reader of x)
15132        //   y_b = manually-pushed Op::ReluInplace on x  (destructive)
15133        // Expected: y_b must run after y_a.
15134        let x = NodeHandle::from_f32(
15135            vec![1.0_f32, -1.0, 2.0, -2.0],
15136            Shape::from_dims(&[4]),
15137            cpu_dev(),
15138        )
15139        .unwrap();
15140        let y_a = x.relu();
15141        let y_b_id = x.graph().write().unwrap().push(Node {
15142            op: Op::ReluInplace,
15143            inputs: vec![x.id()],
15144            shape: Shape::from_dims(&[4]),
15145            dtype: DType::F32,
15146        });
15147        let ord = crate::opt::derive_ordering(&x.graph().read().unwrap(), &[y_a.id(), y_b_id]);
15148        let deps = ord.deps_of(y_b_id);
15149        assert_eq!(deps.len(), 1, "in-place unary should have one ordering dep");
15150        assert_eq!(
15151            deps[0],
15152            y_a.id(),
15153            "in-place unary must run after the non-destructive reader"
15154        );
15155    }
15156
15157    // ------------------------------------------------------------------
15158    // Multi-output nodes (Option C, Session 1)
15159    // ------------------------------------------------------------------
15160
15161    use fuel_backend_contract::storage::Storage as CoreStorage;
15162    use fuel_ir::storage::OutputView;
15163
15164    /// Build a real CPU `Storage` of `n` F32 zeros so `Storage`-level
15165    /// tests can attach + read bundle metadata against a live backend
15166    /// allocator. The dtype is fixed at F32 because every existing
15167    /// `OutputView` test below uses F32 for slot 0; bundle dtype is
15168    /// validated at `with_bundle` time against this primary dtype.
15169    fn cpu_f32_storage(n: usize) -> CoreStorage {
15170        let dev = cpu_dev();
15171        let buf = fuel_ir::HostBuffer::F32(vec![0.0_f32; n]);
15172        let inner = dev
15173            .storage_from_host_buffer_owned_dyn(buf)
15174            .expect("test fixture: F32 storage_from_host_buffer_owned_dyn failed");
15175        CoreStorage::from_dyn(inner)
15176    }
15177
15178    /// Build a 2-slot bundle: slot 0 `[2, 3]` F32 `y`-shape, slot 1
15179    /// `[2, 4]` F32 `last_state`-shape. Returns the views and the
15180    /// total element count (used to size the backing CPU buffer so
15181    /// slot 1's byte range stays inside the bundle's bytes).
15182    fn two_slot_views() -> (Vec<OutputView>, usize) {
15183        let s0 = Shape::from_dims(&[2, 3]);
15184        let s1 = Shape::from_dims(&[2, 4]);
15185        let v0 = OutputView {
15186            byte_offset: 0,
15187            len_elements: s0.elem_count(),
15188            dtype: DType::F32,
15189            shape: s0.clone(),
15190            layout: Layout::contiguous(s0),
15191            name: Some("y"),
15192        };
15193        let v1 = OutputView {
15194            byte_offset: v0.len_bytes(),
15195            len_elements: s1.elem_count(),
15196            dtype: DType::F32,
15197            shape: s1.clone(),
15198            layout: Layout::contiguous(s1),
15199            name: Some("last_state"),
15200        };
15201        let total = v0.len_elements + v1.len_elements;
15202        (vec![v0, v1], total)
15203    }
15204
15205    /// `Storage::is_bundled` is false by default; `slot_count` is 1;
15206    /// `bundle` / `bundle_arc` / `slot_view` / `slot_dtype` all return
15207    /// `None` for the non-multi-output case.
15208    #[test]
15209    fn storage_single_output_defaults() {
15210        let s = cpu_f32_storage(8);
15211        assert!(!s.is_bundled());
15212        assert_eq!(s.slot_count(), 1);
15213        assert!(s.bundle().is_none());
15214        assert!(s.bundle_arc().is_none());
15215        assert!(s.slot_view(0).is_none());
15216        assert_eq!(s.slot_dtype(0), None);
15217        assert_eq!(s.primary_dtype(), DType::F32);
15218        assert_eq!(s.dtype(), DType::F32);
15219    }
15220
15221    /// `Storage::with_bundle` attaches the side-table and per-slot
15222    /// lookups report the declared shape/dtype.
15223    #[test]
15224    fn storage_with_bundle_attaches_views() {
15225        let (views, total) = two_slot_views();
15226        let s = cpu_f32_storage(total)
15227            .with_bundle(views.clone().into())
15228            .expect("with_bundle should accept matching slot-0 dtype");
15229        assert!(s.is_bundled());
15230        assert_eq!(s.slot_count(), 2);
15231        let slot0 = s.slot_view(0).unwrap();
15232        assert_eq!(slot0.shape, Shape::from_dims(&[2, 3]));
15233        assert_eq!(slot0.dtype, DType::F32);
15234        assert_eq!(slot0.byte_offset, 0);
15235        assert_eq!(slot0.name, Some("y"));
15236        let slot1 = s.slot_view(1).unwrap();
15237        assert_eq!(slot1.shape, Shape::from_dims(&[2, 4]));
15238        assert_eq!(slot1.byte_offset, 24); // 6 F32s = 24 bytes
15239        assert_eq!(slot1.name, Some("last_state"));
15240        // Out-of-range slot reads `None`, doesn't panic.
15241        assert!(s.slot_view(2).is_none());
15242        assert_eq!(s.slot_dtype(2), None);
15243    }
15244
15245    /// `Storage::with_bundle` rejects an empty bundle slice (a
15246    /// zero-slot bundle is a contract bug — use a single-output
15247    /// Storage if there's nothing to project).
15248    #[test]
15249    fn storage_with_bundle_rejects_empty() {
15250        let s = cpu_f32_storage(1);
15251        let empty: Arc<[OutputView]> = Arc::from(Vec::<OutputView>::new().into_boxed_slice());
15252        let err = s
15253            .with_bundle(empty)
15254            .expect_err("empty bundle slice must error");
15255        let msg = format!("{err}");
15256        assert!(msg.contains("non-empty"), "error message: {msg}");
15257    }
15258
15259    /// `Storage::with_bundle` rejects slot 0 dtype that disagrees with
15260    /// the inner backend dtype — the bundle invariant "slot 0 dtype ==
15261    /// primary_dtype()" must hold.
15262    #[test]
15263    fn storage_with_bundle_rejects_dtype_mismatch() {
15264        let s = cpu_f32_storage(8);
15265        let bad = OutputView {
15266            byte_offset: 0,
15267            len_elements: 4,
15268            dtype: DType::F64,
15269            shape: Shape::from_dims(&[2, 2]),
15270            layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15271            name: None,
15272        };
15273        let err = s
15274            .with_bundle(Arc::from(vec![bad].into_boxed_slice()))
15275            .expect_err("slot 0 dtype mismatch must error");
15276        let msg = format!("{err}");
15277        assert!(msg.contains("dtype"), "error message: {msg}");
15278    }
15279
15280    /// `Graph::output_views` is `None` for ordinary single-output
15281    /// nodes; `multi_output_count` is 0.
15282    #[test]
15283    fn graph_output_views_defaults() {
15284        let mut g = Graph::new();
15285        let id = g.push(Node {
15286            op: Op::Const,
15287            inputs: vec![],
15288            shape: Shape::from_dims(&[2, 3]),
15289            dtype: DType::F32,
15290        });
15291        assert!(g.output_views(id).is_none());
15292        assert!(!g.is_multi_output(id));
15293        assert_eq!(g.multi_output_count(), 0);
15294    }
15295
15296    /// `Graph::set_output_views` round-trips: read returns what was
15297    /// written; `is_multi_output` flips.
15298    #[test]
15299    fn graph_set_output_views_roundtrip() {
15300        let mut g = Graph::new();
15301        let id = g.push(Node {
15302            op: Op::Const,
15303            inputs: vec![],
15304            shape: Shape::from_dims(&[2, 3]),
15305            dtype: DType::F32,
15306        });
15307        let (views, _) = two_slot_views();
15308        g.set_output_views(id, views.clone().into())
15309            .expect("valid 2-slot specs");
15310        assert!(g.is_multi_output(id));
15311        assert_eq!(g.multi_output_count(), 1);
15312        let read = g.output_views(id).expect("entry present");
15313        assert_eq!(read.len(), 2);
15314        assert_eq!(read[1].shape, Shape::from_dims(&[2, 4]));
15315    }
15316
15317    /// `Graph::set_output_views` rejects slot 0 dtype/shape that
15318    /// disagree with the producer node's primary shape/dtype.
15319    #[test]
15320    fn graph_set_output_views_validates_primary() {
15321        let mut g = Graph::new();
15322        let id = g.push(Node {
15323            op: Op::Const,
15324            inputs: vec![],
15325            shape: Shape::from_dims(&[2, 3]),
15326            dtype: DType::F32,
15327        });
15328        // dtype mismatch on slot 0
15329        let bad_dtype = OutputView {
15330            byte_offset: 0,
15331            len_elements: 6,
15332            dtype: DType::F64,
15333            shape: Shape::from_dims(&[2, 3]),
15334            layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15335            name: None,
15336        };
15337        let err = g
15338            .set_output_views(id, vec![bad_dtype].into())
15339            .expect_err("primary dtype mismatch must error");
15340        let msg = format!("{err}");
15341        assert!(msg.contains("dtype"), "error message: {msg}");
15342        // shape mismatch on slot 0
15343        let bad_shape = OutputView {
15344            byte_offset: 0,
15345            len_elements: 4,
15346            dtype: DType::F32,
15347            shape: Shape::from_dims(&[2, 2]),
15348            layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15349            name: None,
15350        };
15351        let err = g
15352            .set_output_views(id, vec![bad_shape].into())
15353            .expect_err("primary shape mismatch must error");
15354        let msg = format!("{err}");
15355        assert!(msg.contains("shape"), "error message: {msg}");
15356    }
15357
15358    /// `NodeHandle::view(slot)` against a producer that hasn't been
15359    /// declared multi-output returns Err — fails fast at build time.
15360    #[test]
15361    fn tensor_view_on_non_multi_output_errors() {
15362        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15363        let id = graph.write().unwrap().push(Node {
15364            op: Op::Const,
15365            inputs: vec![],
15366            shape: Shape::from_dims(&[2, 3]),
15367            dtype: DType::F32,
15368        });
15369        let producer = NodeHandle::from_existing(Arc::clone(&graph), id);
15370        let err = producer
15371            .view(0)
15372            .expect_err("view on non-multi-output producer must error");
15373        let msg = format!("{err}");
15374        assert!(msg.contains("multi-output"), "error message: {msg}");
15375    }
15376
15377    /// `NodeHandle::view(slot)` with slot OOB returns Err.
15378    #[test]
15379    fn tensor_view_oob_slot_errors() {
15380        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15381        let producer_id = {
15382            let mut g = graph.write().unwrap();
15383            let id = g.push(Node {
15384                op: Op::Const,
15385                inputs: vec![],
15386                shape: Shape::from_dims(&[2, 3]),
15387                dtype: DType::F32,
15388            });
15389            let (views, _) = two_slot_views();
15390            g.set_output_views(id, views.into())
15391                .expect("valid 2-slot specs");
15392            id
15393        };
15394        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15395        let err = producer
15396            .view(2)
15397            .expect_err("slot 2 of a 2-slot producer must error");
15398        let msg = format!("{err}");
15399        assert!(msg.contains("out of range"), "error message: {msg}");
15400    }
15401
15402    /// `NodeHandle::view(slot)` produces a tensor whose shape/dtype match
15403    /// the slot spec; producer's primary shape stays as slot 0's. The
15404    /// View node holds the producer in `inputs[0]`.
15405    #[test]
15406    fn tensor_view_shape_dtype_from_slot() {
15407        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15408        let producer_id = {
15409            let mut g = graph.write().unwrap();
15410            let id = g.push(Node {
15411                op: Op::Const,
15412                inputs: vec![],
15413                shape: Shape::from_dims(&[2, 3]),
15414                dtype: DType::F32,
15415            });
15416            let (views, _) = two_slot_views();
15417            g.set_output_views(id, views.into())
15418                .expect("valid 2-slot specs");
15419            id
15420        };
15421        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15422        let v0 = producer.view(0).expect("slot 0 view");
15423        assert_eq!(v0.shape(), Shape::from_dims(&[2, 3]));
15424        assert_eq!(v0.dtype(), DType::F32);
15425        let v1 = producer.view(1).expect("slot 1 view");
15426        assert_eq!(v1.shape(), Shape::from_dims(&[2, 4]));
15427        assert_eq!(v1.dtype(), DType::F32);
15428        // View node carries the producer in inputs[0] and the slot
15429        // index in the Op variant — verify the Graph state directly.
15430        let g = graph.read().unwrap();
15431        let v1_node = g.node(v1.id());
15432        assert_eq!(v1_node.inputs, vec![producer_id]);
15433        assert!(matches!(v1_node.op, Op::View { slot: 1 }));
15434        // Slot 0 starts at byte_offset 0 + contiguous → layout
15435        // matches Layout::contiguous(slot0.shape) → no side-table
15436        // entry (the contiguous fallback covers it).
15437        assert!(!g.has_explicit_layout(v0.id()));
15438        // Slot 1 starts at byte_offset 24 (= 6 F32 elements past
15439        // slot 0). Session 4 bakes that into the layout's
15440        // start_offset so a downstream kernel reading the producer's
15441        // bytes as F32 elements lands on slot 1's first byte. Side-
15442        // table entry is mandatory.
15443        assert!(g.has_explicit_layout(v1.id()));
15444        let l1 = g.layout(v1.id());
15445        assert_eq!(
15446            l1.start_offset(),
15447            6,
15448            "slot 1 byte_offset 24 / 4 = 6 F32 elements"
15449        );
15450        assert_eq!(l1.shape(), &Shape::from_dims(&[2, 4]));
15451    }
15452
15453    /// `NodeHandle::view(slot)` over a slot whose layout is non-contiguous
15454    /// (strided) populates the Graph's layout side-table with the
15455    /// slot's layout — so downstream consumers see the strided view.
15456    #[test]
15457    fn tensor_view_propagates_non_contiguous_slot_layout() {
15458        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15459        let strided_shape = Shape::from_dims(&[2, 3]);
15460        let strided_layout = Layout::contiguous(strided_shape.clone())
15461            .transpose(0, 1)
15462            .expect("transpose [2,3] -> [3,2]");
15463        // Slot 0 = primary (contiguous, matches producer's Node shape).
15464        let s0 = OutputView {
15465            byte_offset: 0,
15466            len_elements: strided_shape.elem_count(),
15467            dtype: DType::F32,
15468            shape: strided_shape.clone(),
15469            layout: Layout::contiguous(strided_shape.clone()),
15470            name: Some("primary"),
15471        };
15472        // Slot 1 = strided projection. Same byte range as slot 0; the
15473        // shape after transpose is [3, 2]; layout's start offset stays
15474        // within the slot.
15475        let s1 = OutputView {
15476            byte_offset: 0,
15477            len_elements: strided_shape.elem_count(),
15478            dtype: DType::F32,
15479            shape: Shape::from_dims(&[3, 2]),
15480            layout: strided_layout.clone(),
15481            name: Some("strided_view"),
15482        };
15483        let producer_id = {
15484            let mut g = graph.write().unwrap();
15485            let id = g.push(Node {
15486                op: Op::Const,
15487                inputs: vec![],
15488                shape: strided_shape.clone(),
15489                dtype: DType::F32,
15490            });
15491            g.set_output_views(id, vec![s0, s1].into())
15492                .expect("valid 2-slot strided spec");
15493            id
15494        };
15495        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15496        let v1 = producer.view(1).expect("strided slot view");
15497        let g = graph.read().unwrap();
15498        assert!(
15499            g.has_explicit_layout(v1.id()),
15500            "strided slot must populate Graph::layouts side-table",
15501        );
15502        let read_layout = g.layout(v1.id());
15503        assert_eq!(read_layout.shape(), strided_layout.shape());
15504        assert_eq!(read_layout.stride(), strided_layout.stride());
15505    }
15506
15507    /// `NodeHandle::view_owned(slot)` produces the same shape/dtype as
15508    /// `NodeHandle::view(slot)` but its output layout is ALWAYS contiguous
15509    /// — the forward memcpy produces a fresh standalone buffer, so
15510    /// the slot's (possibly strided) layout is not propagated.
15511    #[test]
15512    fn tensor_view_owned_layout_is_contiguous() {
15513        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15514        let strided_shape = Shape::from_dims(&[2, 3]);
15515        let strided_layout = Layout::contiguous(strided_shape.clone())
15516            .transpose(0, 1)
15517            .expect("transpose [2,3] -> [3,2]");
15518        let s0 = OutputView {
15519            byte_offset: 0,
15520            len_elements: strided_shape.elem_count(),
15521            dtype: DType::F32,
15522            shape: strided_shape.clone(),
15523            layout: Layout::contiguous(strided_shape.clone()),
15524            name: None,
15525        };
15526        let s1 = OutputView {
15527            byte_offset: 0,
15528            len_elements: strided_shape.elem_count(),
15529            dtype: DType::F32,
15530            shape: Shape::from_dims(&[3, 2]),
15531            layout: strided_layout,
15532            name: None,
15533        };
15534        let producer_id = {
15535            let mut g = graph.write().unwrap();
15536            let id = g.push(Node {
15537                op: Op::Const,
15538                inputs: vec![],
15539                shape: strided_shape,
15540                dtype: DType::F32,
15541            });
15542            g.set_output_views(id, vec![s0, s1].into())
15543                .expect("valid 2-slot specs");
15544            id
15545        };
15546        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15547        let v1 = producer.view_owned(1).expect("ViewOwned slot 1");
15548        assert_eq!(v1.shape(), Shape::from_dims(&[3, 2]));
15549        assert_eq!(v1.dtype(), DType::F32);
15550        let g = graph.read().unwrap();
15551        // ViewOwned is a fresh allocation — no explicit layout entry,
15552        // contiguous layout falls through.
15553        assert!(!g.has_explicit_layout(v1.id()));
15554        let owned_node = g.node(v1.id());
15555        assert!(matches!(owned_node.op, Op::ViewOwned { slot: 1 }));
15556    }
15557
15558    // ------------------------------------------------------------------
15559    // Session 2: bundled allocator + FusedOpEntry::output_views +
15560    // View-vs-ViewOwned planner pass. The tests use the bundled
15561    // storage allocator and a synthetic 2-output FusedOp entry — no
15562    // real fused-op author migrates in Session 2; the
15563    // selective-scan-ssd-chunk-multi-output-followup session lights
15564    // up the first real consumer.
15565    // ------------------------------------------------------------------
15566
15567    use fuel_backend_contract::storage::allocate_bundled_storage;
15568    use fuel_ir::storage::OutputViewSpec;
15569
15570    /// `allocate_bundled_storage` allocates one Storage on the device,
15571    /// attaches the bundle, and slot lookups report the spec-derived
15572    /// byte_offsets.
15573    #[test]
15574    fn allocate_bundled_storage_two_slot_roundtrip() {
15575        let dev = cpu_dev();
15576        let specs = vec![
15577            OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15578            OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15579        ];
15580        let s =
15581            allocate_bundled_storage(dev.as_ref(), &specs).expect("two-slot F32 alloc succeeds");
15582        assert!(s.is_bundled());
15583        assert_eq!(s.slot_count(), 2);
15584        assert_eq!(s.primary_dtype(), DType::F32);
15585        let v0 = s.slot_view(0).unwrap();
15586        let v1 = s.slot_view(1).unwrap();
15587        assert_eq!(v0.byte_offset, 0);
15588        assert_eq!(v0.shape, Shape::from_dims(&[2, 3]));
15589        assert_eq!(v1.byte_offset, 24);
15590        assert_eq!(v1.shape, Shape::from_dims(&[2, 4]));
15591    }
15592
15593    /// `allocate_bundled_storage` handles mixed F32 + F64 slots — slot
15594    /// 0 is primary (F32), slot 1's bytes are aligned to its F64
15595    /// boundary, and the underlying allocation has enough flat F32
15596    /// elements to cover the total bundle bytes.
15597    #[test]
15598    fn allocate_bundled_storage_mixed_dtype() {
15599        let dev = cpu_dev();
15600        let specs = vec![
15601            OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[6])),
15602            OutputViewSpec::contiguous(DType::F64, Shape::from_dims(&[3])),
15603        ];
15604        let s = allocate_bundled_storage(dev.as_ref(), &specs).expect("mixed-dtype alloc succeeds");
15605        assert_eq!(s.primary_dtype(), DType::F32);
15606        let v0 = s.slot_view(0).unwrap();
15607        let v1 = s.slot_view(1).unwrap();
15608        assert_eq!(v0.dtype, DType::F32);
15609        assert_eq!(v1.dtype, DType::F64);
15610        assert_eq!(v0.byte_offset, 0);
15611        // F32[6] = 24 bytes; 24 is already multiple of 8, so v1
15612        // starts at 24 without further padding.
15613        assert_eq!(v1.byte_offset, 24);
15614    }
15615
15616    /// `allocate_bundled_storage` propagates compose_bundle errors —
15617    /// an empty spec list errors out before touching the device.
15618    #[test]
15619    fn allocate_bundled_storage_rejects_empty() {
15620        let dev = cpu_dev();
15621        let err = allocate_bundled_storage(dev.as_ref(), &[]).expect_err("empty specs error");
15622        assert!(format!("{err}").contains("non-empty"));
15623    }
15624
15625    /// The two SelectiveScan / SsdChunkScan migrations from item 3
15626    /// (2026-06-01) are the first `default_registry` entries to
15627    /// declare `output_views`. Any new multi-output op author should
15628    /// extend the expected set here.
15629    #[test]
15630    fn default_registry_multi_output_entries() {
15631        let reg = crate::registry::default_registry();
15632        let mut multi_out_names: Vec<&'static str> = reg
15633            .entries_iter()
15634            .filter(|e| e.output_views.is_some())
15635            .map(|e| e.name)
15636            .collect();
15637        multi_out_names.sort();
15638        assert_eq!(
15639            multi_out_names,
15640            vec!["MatMulTopK", "SelectiveScan", "SsdChunkScan", "TopKLastDim"],
15641            "the multi-output registry set should match the item-3 \
15642             migrations (SelectiveScan + SsdChunkScan); add new \
15643             multi-output ops to this list as they migrate",
15644        );
15645    }
15646
15647    /// Authoring-contract invariant: for every multi-output entry in
15648    /// the process-wide registry, `shape_rule(inputs)` MUST equal
15649    /// `output_views(inputs)[0].shape` and `dtype_rule(inputs)` MUST
15650    /// equal `output_views(inputs)[0].dtype`. Slot 0 is the primary
15651    /// and the bundled-allocation contract assumes the producer's
15652    /// `Node.shape`/`Node.dtype` reflect it.
15653    #[test]
15654    fn multi_output_entries_slot_0_matches_primary_rules() {
15655        use crate::registry::FusedOpParams;
15656        let reg = crate::registry::default_registry();
15657
15658        // Each multi-output entry needs a representative input batch
15659        // (shapes + dtypes + params) that satisfies its
15660        // shape_rule/dtype_rule preconditions. The check below runs
15661        // once per entry using these fixtures.
15662        struct Fixture {
15663            shapes: Vec<Shape>,
15664            dtypes: Vec<DType>,
15665            params: FusedOpParams,
15666        }
15667        fn selective_scan_fixture() -> Fixture {
15668            Fixture {
15669                shapes: vec![
15670                    Shape::from_dims(&[2, 4, 8]),  // u: [batch, seqlen, dim]
15671                    Shape::from_dims(&[2, 4, 8]),  // delta: same
15672                    Shape::from_dims(&[8, 16]),    // a: [dim, dstate]
15673                    Shape::from_dims(&[2, 4, 16]), // b: [batch, seqlen, dstate]
15674                    Shape::from_dims(&[2, 4, 16]), // c: same
15675                ],
15676                dtypes: vec![DType::F32; 5],
15677                params: FusedOpParams::SelectiveScan {
15678                    delta_softplus: false,
15679                },
15680            }
15681        }
15682        fn ssd_chunk_scan_fixture() -> Fixture {
15683            Fixture {
15684                shapes: vec![
15685                    Shape::from_dims(&[2, 4, 3, 8]), // x: [batch, seqlen, heads, head_dim]
15686                    Shape::from_dims(&[2, 4, 3]),    // dt: [batch, seqlen, heads]
15687                    Shape::from_dims(&[3]),          // a: [heads]
15688                    Shape::from_dims(&[2, 4, 3, 16]), // b: [batch, seqlen, heads, state_dim]
15689                    Shape::from_dims(&[2, 4, 3, 16]), // c: same
15690                ],
15691                dtypes: vec![DType::F32; 5],
15692                params: FusedOpParams::SsdChunkScan { chunk_size: 4 },
15693            }
15694        }
15695
15696        fn top_k_fixture() -> Fixture {
15697            Fixture {
15698                shapes: vec![Shape::from_dims(&[2, 5, 8])],
15699                dtypes: vec![DType::F32],
15700                params: FusedOpParams::TopKLastDim { k: 3 },
15701            }
15702        }
15703
15704        fn matmul_top_k_fixture() -> Fixture {
15705            Fixture {
15706                shapes: vec![Shape::from_dims(&[2, 4, 8]), Shape::from_dims(&[2, 8, 16])],
15707                dtypes: vec![DType::F32; 2],
15708                params: FusedOpParams::MatMulTopK { k: 3 },
15709            }
15710        }
15711
15712        for entry in reg.entries_iter().filter(|e| e.output_views.is_some()) {
15713            let fx = match entry.name {
15714                "MatMulTopK" => matmul_top_k_fixture(),
15715                "TopKLastDim" => top_k_fixture(),
15716                "SelectiveScan" => selective_scan_fixture(),
15717                "SsdChunkScan" => ssd_chunk_scan_fixture(),
15718                other => panic!(
15719                    "multi_output_entries_slot_0_matches_primary_rules: \
15720                     no fixture for new multi-output entry {other:?}. \
15721                     Add one to this test as you register a new op.",
15722                ),
15723            };
15724            let primary_shape = (entry.shape_rule)(&fx.shapes, &fx.params);
15725            let primary_dtype = (entry.dtype_rule)(&fx.dtypes, &fx.params);
15726            let specs = entry.output_views.unwrap()(&fx.shapes, &fx.dtypes, &fx.params);
15727            assert!(
15728                !specs.is_empty(),
15729                "{}: output_views returned empty Vec (multi-output ops \
15730                 must have ≥ 1 slot)",
15731                entry.name,
15732            );
15733            assert_eq!(
15734                specs[0].shape, primary_shape,
15735                "{}: output_views[0].shape {:?} must equal shape_rule \
15736                 {:?} (slot 0 is the primary; Node::shape reflects it)",
15737                entry.name, specs[0].shape, primary_shape,
15738            );
15739            assert_eq!(
15740                specs[0].dtype, primary_dtype,
15741                "{}: output_views[0].dtype {:?} must equal dtype_rule \
15742                 {:?} (slot 0 is the primary; Node::dtype reflects it)",
15743                entry.name, specs[0].dtype, primary_dtype,
15744            );
15745            // Layout-shape coherence: each slot's layout shape must
15746            // equal its declared shape (the same invariant
15747            // set_output_views enforces at graph-build time).
15748            for (i, spec) in specs.iter().enumerate() {
15749                assert_eq!(
15750                    spec.layout.shape(),
15751                    &spec.shape,
15752                    "{}: slot {i} layout.shape() {:?} disagrees with \
15753                     declared spec.shape {:?}",
15754                    entry.name,
15755                    spec.layout.shape(),
15756                    spec.shape,
15757                );
15758            }
15759        }
15760    }
15761
15762    /// Build a synthetic multi-output `FusedOpEntry` to exercise the
15763    /// authoring contract end-to-end without polluting the production
15764    /// registry. The output_views fn returns a 2-slot spec list whose
15765    /// slot 0 matches shape_rule / dtype_rule (the primary).
15766    fn synthetic_two_output_entry() -> crate::registry::FusedOpEntry {
15767        fn shape(_: &[Shape], _: &crate::registry::FusedOpParams) -> Shape {
15768            Shape::from_dims(&[2, 3])
15769        }
15770        fn dtype(_: &[DType], _: &crate::registry::FusedOpParams) -> DType {
15771            DType::F32
15772        }
15773        fn ovs(
15774            _: &[Shape],
15775            _: &[DType],
15776            _: &crate::registry::FusedOpParams,
15777        ) -> Vec<OutputViewSpec> {
15778            vec![
15779                OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15780                OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15781            ]
15782        }
15783        crate::registry::FusedOpEntry {
15784            destructive_input: None,
15785            id: crate::registry::FusedOps::SOFTMAX_LAST_DIM, // any id; not registered
15786            name: "<synthetic-2-output>",
15787            family: crate::registry::FusedOpFamily::Forward,
15788            pattern: crate::registry::SubgraphPattern::Callable(|_g, _id| None),
15789            decompose: |_g, id, _p| id,
15790            backward: crate::registry::BackwardKind::NotDifferentiable,
15791            shape_rule: shape,
15792            dtype_rule: dtype,
15793            output_views: Some(ovs),
15794        }
15795    }
15796
15797    /// The synthetic entry's `output_views` matches the
15798    /// `shape_rule`/`dtype_rule` contract on slot 0.
15799    #[test]
15800    fn synthetic_entry_output_views_matches_primary_contract() {
15801        let entry = synthetic_two_output_entry();
15802        let ovs_fn = entry.output_views.expect("synthetic entry is multi-output");
15803        let specs = ovs_fn(&[], &[], &crate::registry::FusedOpParams::SoftmaxLastDim);
15804        assert_eq!(specs.len(), 2);
15805        assert_eq!(
15806            specs[0].dtype,
15807            (entry.dtype_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15808        );
15809        assert_eq!(
15810            specs[0].shape,
15811            (entry.shape_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15812        );
15813    }
15814
15815    /// Build a producer Const node and declare it multi-output via
15816    /// `Graph::set_output_views`. Returns the producer's NodeId and a
15817    /// SharedGraph handle.
15818    fn multi_output_producer(slots: Vec<OutputView>) -> (SharedGraph, NodeId) {
15819        let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15820        let id = {
15821            let mut g = graph.write().unwrap();
15822            let id = g.push(Node {
15823                op: Op::Const,
15824                inputs: vec![],
15825                shape: slots[0].shape.clone(),
15826                dtype: slots[0].dtype,
15827            });
15828            g.set_output_views(id, slots.into())
15829                .expect("valid synthetic specs");
15830            id
15831        };
15832        (graph, id)
15833    }
15834
15835    /// Two slots, both consumed at the same topo depth → planner does
15836    /// nothing (symmetric lifetimes, bundle drops naturally).
15837    #[test]
15838    fn promote_views_symmetric_lifetimes_is_noop() {
15839        let slot_specs = vec![
15840            OutputView {
15841                byte_offset: 0,
15842                len_elements: 6,
15843                dtype: DType::F32,
15844                shape: Shape::from_dims(&[2, 3]),
15845                layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15846                name: Some("y"),
15847            },
15848            OutputView {
15849                byte_offset: 24,
15850                len_elements: 8,
15851                dtype: DType::F32,
15852                shape: Shape::from_dims(&[2, 4]),
15853                layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15854                name: Some("state"),
15855            },
15856        ];
15857        let (graph, producer_id) = multi_output_producer(slot_specs);
15858        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15859        // Each slot has exactly one View, consumed at the same depth
15860        // (a no-op Relu downstream of each).
15861        let v0 = producer.view(0).expect("slot 0 view");
15862        let v1 = producer.view(1).expect("slot 1 view");
15863        let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15864        let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15865        let roots = {
15866            let mut g = graph.write().unwrap();
15867            let r0 = g.push(Node {
15868                op: Op::Relu,
15869                inputs: vec![v0_id],
15870                shape: v0_shape,
15871                dtype: v0_dtype,
15872            });
15873            let r1 = g.push(Node {
15874                op: Op::Relu,
15875                inputs: vec![v1_id],
15876                shape: v1_shape,
15877                dtype: v1_dtype,
15878            });
15879            vec![r0, r1]
15880        };
15881        let promotions = {
15882            let mut g = graph.write().unwrap();
15883            crate::opt::promote_views_for_liveness(&mut g, &roots)
15884        };
15885        assert_eq!(
15886            promotions, 0,
15887            "symmetric lifetimes shouldn't promote anything"
15888        );
15889    }
15890
15891    /// Asymmetric lifetimes: slot 0 consumed early, slot 1 consumed
15892    /// late → planner promotes slot 1's View to ViewOwned.
15893    #[test]
15894    fn promote_views_asymmetric_promotes_long_lived_slot() {
15895        let slot_specs = vec![
15896            OutputView {
15897                byte_offset: 0,
15898                len_elements: 6,
15899                dtype: DType::F32,
15900                shape: Shape::from_dims(&[2, 3]),
15901                layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15902                name: Some("y"),
15903            },
15904            OutputView {
15905                byte_offset: 24,
15906                len_elements: 6,
15907                dtype: DType::F32,
15908                shape: Shape::from_dims(&[2, 3]),
15909                layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15910                name: Some("state"),
15911            },
15912        ];
15913        let (graph, producer_id) = multi_output_producer(slot_specs);
15914        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15915        let v_y = producer.view(0).expect("slot 0 view");
15916        let v_state = producer.view(1).expect("slot 1 view");
15917        // Slot 0 ("y") consumed at depth 1 (single Relu).
15918        // Slot 1 ("state") consumed at a much deeper chain — Relu →
15919        // Relu → Relu. Topo positions push state's last-use later
15920        // than y's, triggering promotion of state's View.
15921        let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15922        let (v_state_id, v_state_shape, v_state_dtype) =
15923            (v_state.id(), v_state.shape(), v_state.dtype());
15924        let roots = {
15925            let mut g = graph.write().unwrap();
15926            let y_relu = g.push(Node {
15927                op: Op::Relu,
15928                inputs: vec![v_y_id],
15929                shape: v_y_shape,
15930                dtype: v_y_dtype,
15931            });
15932            let s1 = g.push(Node {
15933                op: Op::Relu,
15934                inputs: vec![v_state_id],
15935                shape: v_state_shape.clone(),
15936                dtype: v_state_dtype,
15937            });
15938            let s2 = g.push(Node {
15939                op: Op::Relu,
15940                inputs: vec![s1],
15941                shape: v_state_shape.clone(),
15942                dtype: v_state_dtype,
15943            });
15944            let s3 = g.push(Node {
15945                op: Op::Relu,
15946                inputs: vec![s2],
15947                shape: v_state_shape,
15948                dtype: v_state_dtype,
15949            });
15950            vec![y_relu, s3]
15951        };
15952        let promotions = {
15953            let mut g = graph.write().unwrap();
15954            crate::opt::promote_views_for_liveness(&mut g, &roots)
15955        };
15956        assert_eq!(
15957            promotions, 1,
15958            "exactly the long-lived slot 1 View should promote"
15959        );
15960        // Slot 1's consumer (the first Relu in the long chain) now
15961        // reads a fresh Op::ViewOwned node, not the old Op::View.
15962        let g = graph.read().unwrap();
15963        // Find the new ViewOwned node — it was pushed AFTER the
15964        // existing nodes, so it's the last node in the arena. Its op
15965        // must be Op::ViewOwned { slot: 1 } and its input must be the
15966        // producer.
15967        let last_id = NodeId(g.len() - 1);
15968        let last_node = g.node(last_id);
15969        assert!(matches!(last_node.op, Op::ViewOwned { slot: 1 }));
15970        assert_eq!(last_node.inputs, vec![producer_id]);
15971        // The slot 0 View is untouched — still Op::View.
15972        let v_y_node = g.node(v_y_id);
15973        assert!(matches!(v_y_node.op, Op::View { slot: 0 }));
15974        // The old slot 1 View stays in the arena (orphaned). No
15975        // consumer points at it anymore.
15976        let v_state_node = g.node(v_state_id);
15977        assert!(matches!(v_state_node.op, Op::View { slot: 1 }));
15978    }
15979
15980    /// Running the pass twice on the same graph promotes nothing on
15981    /// the second call — `Op::ViewOwned` is a fixpoint (skipped by
15982    /// the planner because `is_owned` is true).
15983    #[test]
15984    fn promote_views_idempotent() {
15985        let slot_specs = vec![
15986            OutputView {
15987                byte_offset: 0,
15988                len_elements: 4,
15989                dtype: DType::F32,
15990                shape: Shape::from_dims(&[2, 2]),
15991                layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15992                name: None,
15993            },
15994            OutputView {
15995                byte_offset: 16,
15996                len_elements: 4,
15997                dtype: DType::F32,
15998                shape: Shape::from_dims(&[2, 2]),
15999                layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
16000                name: None,
16001            },
16002        ];
16003        let (graph, producer_id) = multi_output_producer(slot_specs);
16004        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16005        let v_y = producer.view(0).expect("slot 0 view");
16006        let v_state = producer.view(1).expect("slot 1 view");
16007        let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
16008        let (v_state_id, v_state_shape, v_state_dtype) =
16009            (v_state.id(), v_state.shape(), v_state.dtype());
16010        let roots = {
16011            let mut g = graph.write().unwrap();
16012            let y_r = g.push(Node {
16013                op: Op::Relu,
16014                inputs: vec![v_y_id],
16015                shape: v_y_shape,
16016                dtype: v_y_dtype,
16017            });
16018            let s1 = g.push(Node {
16019                op: Op::Relu,
16020                inputs: vec![v_state_id],
16021                shape: v_state_shape.clone(),
16022                dtype: v_state_dtype,
16023            });
16024            let s2 = g.push(Node {
16025                op: Op::Relu,
16026                inputs: vec![s1],
16027                shape: v_state_shape,
16028                dtype: v_state_dtype,
16029            });
16030            vec![y_r, s2]
16031        };
16032        let first = {
16033            let mut g = graph.write().unwrap();
16034            crate::opt::promote_views_for_liveness(&mut g, &roots)
16035        };
16036        let second = {
16037            let mut g = graph.write().unwrap();
16038            crate::opt::promote_views_for_liveness(&mut g, &roots)
16039        };
16040        assert_eq!(first, 1, "first call promotes the long-lived slot");
16041        assert_eq!(
16042            second, 0,
16043            "second call is idempotent — no further promotions"
16044        );
16045    }
16046
16047    /// Graph with no multi-output producers: pass returns 0 and
16048    /// touches nothing.
16049    #[test]
16050    fn promote_views_noop_on_graph_without_multi_output() {
16051        let mut g = Graph::new();
16052        let a = g.push(Node {
16053            op: Op::Const,
16054            inputs: vec![],
16055            shape: Shape::from_dims(&[2, 3]),
16056            dtype: DType::F32,
16057        });
16058        let r = g.push(Node {
16059            op: Op::Relu,
16060            inputs: vec![a],
16061            shape: Shape::from_dims(&[2, 3]),
16062            dtype: DType::F32,
16063        });
16064        let n_before = g.len();
16065        let promotions = crate::opt::promote_views_for_liveness(&mut g, &[r]);
16066        assert_eq!(promotions, 0);
16067        assert_eq!(g.len(), n_before, "no node should have been added");
16068    }
16069
16070    // ------------------------------------------------------------------
16071    // Session 3: scheduler / destructive-cleanup integration —
16072    // bundle-aware liveness. A destructive op on a multi-output
16073    // producer (or any of its Views) must run after every reader of
16074    // every other View, because all Views share the bundle's storage
16075    // Arc. Op::ViewOwned is excluded — it forks a fresh standalone
16076    // Storage at execute time.
16077    // ------------------------------------------------------------------
16078
16079    /// Helper: build two contiguous slot specs for a producer of
16080    /// `Node::shape = [2, 3] F32`. Slot 0 is the primary (matches the
16081    /// producer's Node::shape/dtype, required by set_output_views);
16082    /// slot 1 carries a sibling shape that doesn't collide with the
16083    /// primary.
16084    fn two_slot_views_2x3_and_2x4() -> Vec<OutputView> {
16085        vec![
16086            OutputView {
16087                byte_offset: 0,
16088                len_elements: 6,
16089                dtype: DType::F32,
16090                shape: Shape::from_dims(&[2, 3]),
16091                layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
16092                name: Some("y"),
16093            },
16094            OutputView {
16095                byte_offset: 24,
16096                len_elements: 8,
16097                dtype: DType::F32,
16098                shape: Shape::from_dims(&[2, 4]),
16099                layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
16100                name: Some("state"),
16101            },
16102        ]
16103    }
16104
16105    /// Op::Release targeting a multi-output producer pins after every
16106    /// consumer of any View of that producer. Without bundle-aware
16107    /// aliasing the Views' downstream Relu nodes would be missed and
16108    /// could race the Release.
16109    #[test]
16110    fn derive_ordering_release_of_bundled_producer_pins_after_view_consumers() {
16111        let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
16112        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16113        let v0 = producer.view(0).expect("slot 0 view");
16114        let v1 = producer.view(1).expect("slot 1 view");
16115        let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
16116        let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
16117        let (r0, r1, release_id) = {
16118            let mut g = graph.write().unwrap();
16119            let r0 = g.push(Node {
16120                op: Op::Relu,
16121                inputs: vec![v0_id],
16122                shape: v0_shape,
16123                dtype: v0_dtype,
16124            });
16125            let r1 = g.push(Node {
16126                op: Op::Relu,
16127                inputs: vec![v1_id],
16128                shape: v1_shape,
16129                dtype: v1_dtype,
16130            });
16131            let release = g.push(Node {
16132                op: Op::Release,
16133                inputs: vec![producer_id],
16134                shape: Shape::from_dims(&[0]),
16135                dtype: DType::F32,
16136            });
16137            (r0, r1, release)
16138        };
16139        let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r0, r1, release_id]);
16140        let deps = ord.deps_of(release_id);
16141        let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16142        assert!(
16143            dep_set.contains(&r0),
16144            "Release must run after the slot-0 View's consumer (r0)",
16145        );
16146        assert!(
16147            dep_set.contains(&r1),
16148            "Release must run after the slot-1 View's consumer (r1) — \
16149             both Views share the bundle Arc",
16150        );
16151    }
16152
16153    /// Destructive op targeting one of a bundle's Op::View nodes
16154    /// pins after every sibling View's consumers too — every View
16155    /// of the producer shares the bundle's Arc, so writing through
16156    /// one of them clobbers the bytes the others read.
16157    #[test]
16158    fn derive_ordering_destructive_on_view_pins_sibling_view_consumers() {
16159        let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
16160        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16161        let v0 = producer.view(0).expect("slot 0 view");
16162        let v1 = producer.view(1).expect("slot 1 view");
16163        let (v0_id, _v0_shape, _v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
16164        let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
16165        // Destructive op (Release) targets v0 directly — its
16166        // alias set must reach v1's consumer via the producer-sibling
16167        // hop in collect_alias_set.
16168        let (r1, release_id) = {
16169            let mut g = graph.write().unwrap();
16170            let r1 = g.push(Node {
16171                op: Op::Relu,
16172                inputs: vec![v1_id],
16173                shape: v1_shape,
16174                dtype: v1_dtype,
16175            });
16176            let release = g.push(Node {
16177                op: Op::Release,
16178                inputs: vec![v0_id],
16179                shape: Shape::from_dims(&[0]),
16180                dtype: DType::F32,
16181            });
16182            (r1, release)
16183        };
16184        let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r1, release_id]);
16185        let deps = ord.deps_of(release_id);
16186        let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16187        assert!(
16188            dep_set.contains(&r1),
16189            "Release targeting slot-0 View must pin after sibling slot-1 \
16190             View's consumer (r1) — both share the bundle's storage Arc",
16191        );
16192    }
16193
16194    /// Op::ViewOwned does NOT extend the alias set: its forward
16195    /// memcpy produces an independent Storage. derive_ordering must
16196    /// still pin Release after the ViewOwned itself (via the standard
16197    /// data-dependency: ViewOwned consumes the producer), but
16198    /// downstream consumers of the ViewOwned are NOT in the alias
16199    /// set's reader sweep — they read independent bytes and may run
16200    /// freely after the Release.
16201    #[test]
16202    fn derive_ordering_view_owned_is_not_alias_extending() {
16203        let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
16204        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16205        // Slot 0 → View (shared Arc); slot 1 → ViewOwned (independent).
16206        let v_view = producer.view(0).expect("slot 0 view");
16207        let v_owned = producer.view_owned(1).expect("slot 1 viewowned");
16208        let (v_view_id, _, _) = (v_view.id(), v_view.shape(), v_view.dtype());
16209        let (v_owned_id, v_owned_shape, v_owned_dtype) =
16210            (v_owned.id(), v_owned.shape(), v_owned.dtype());
16211        let (consumer_of_owned, release_id) = {
16212            let mut g = graph.write().unwrap();
16213            let consumer = g.push(Node {
16214                op: Op::Relu,
16215                inputs: vec![v_owned_id],
16216                shape: v_owned_shape,
16217                dtype: v_owned_dtype,
16218            });
16219            let release = g.push(Node {
16220                op: Op::Release,
16221                inputs: vec![producer_id],
16222                shape: Shape::from_dims(&[0]),
16223                dtype: DType::F32,
16224            });
16225            (consumer, release)
16226        };
16227        let ord =
16228            crate::opt::derive_ordering(&graph.read().unwrap(), &[consumer_of_owned, release_id]);
16229        let deps = ord.deps_of(release_id);
16230        let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16231        // Release MUST wait for ViewOwned to run (ViewOwned reads
16232        // the producer's bytes during its memcpy).
16233        assert!(
16234            dep_set.contains(&v_owned_id),
16235            "Release must pin after ViewOwned — ViewOwned reads the \
16236             producer's bundle during its memcpy phase",
16237        );
16238        // Release must NOT depend on the ViewOwned's downstream
16239        // consumer — that consumer reads ViewOwned's independent
16240        // bytes, not the producer's bundle.
16241        assert!(
16242            !dep_set.contains(&consumer_of_owned),
16243            "Release must NOT pin after consumers of ViewOwned — \
16244             ViewOwned forks a fresh Storage; its consumers don't \
16245             read the producer's bundle",
16246        );
16247        // Op::View's consumers stay reached via the alias chain; here
16248        // there are none (v_view has no consumer), so v_view itself
16249        // is the only alias-set entry beyond the producer.
16250        let _ = v_view_id;
16251    }
16252
16253    /// Long-tail bundle-aware schedule: a producer with three Views,
16254    /// each consumed by a chain of different depth, and a destructive
16255    /// Release on the producer. The Release must end up after every
16256    /// terminal consumer of every chain — bundle-as-single-eviction-
16257    /// unit semantics fall out of derive_ordering's alias-set walk
16258    /// reaching each chain's leaf via the producer-then-View hop.
16259    #[test]
16260    fn derive_ordering_bundle_release_pins_after_all_chains() {
16261        // Build a 3-slot bundle. Slot 0 primary [2,3] F32 satisfies
16262        // the producer's Node::shape/dtype constraint; slots 1 + 2
16263        // add sibling shapes.
16264        let slot_specs = vec![
16265            OutputView {
16266                byte_offset: 0,
16267                len_elements: 6,
16268                dtype: DType::F32,
16269                shape: Shape::from_dims(&[2, 3]),
16270                layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
16271                name: Some("a"),
16272            },
16273            OutputView {
16274                byte_offset: 24,
16275                len_elements: 4,
16276                dtype: DType::F32,
16277                shape: Shape::from_dims(&[2, 2]),
16278                layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
16279                name: Some("b"),
16280            },
16281            OutputView {
16282                byte_offset: 40,
16283                len_elements: 8,
16284                dtype: DType::F32,
16285                shape: Shape::from_dims(&[2, 4]),
16286                layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
16287                name: Some("c"),
16288            },
16289        ];
16290        let (graph, producer_id) = multi_output_producer(slot_specs);
16291        let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16292        let v0 = producer.view(0).unwrap();
16293        let v1 = producer.view(1).unwrap();
16294        let v2 = producer.view(2).unwrap();
16295        let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
16296        let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
16297        let (v2_id, v2_shape, v2_dtype) = (v2.id(), v2.shape(), v2.dtype());
16298        let (leaf_a, leaf_b, leaf_c, release_id) = {
16299            let mut g = graph.write().unwrap();
16300            let leaf_a = g.push(Node {
16301                op: Op::Relu,
16302                inputs: vec![v0_id],
16303                shape: v0_shape,
16304                dtype: v0_dtype,
16305            });
16306            let b1 = g.push(Node {
16307                op: Op::Relu,
16308                inputs: vec![v1_id],
16309                shape: v1_shape.clone(),
16310                dtype: v1_dtype,
16311            });
16312            let leaf_b = g.push(Node {
16313                op: Op::Relu,
16314                inputs: vec![b1],
16315                shape: v1_shape,
16316                dtype: v1_dtype,
16317            });
16318            let c1 = g.push(Node {
16319                op: Op::Relu,
16320                inputs: vec![v2_id],
16321                shape: v2_shape.clone(),
16322                dtype: v2_dtype,
16323            });
16324            let c2 = g.push(Node {
16325                op: Op::Relu,
16326                inputs: vec![c1],
16327                shape: v2_shape.clone(),
16328                dtype: v2_dtype,
16329            });
16330            let leaf_c = g.push(Node {
16331                op: Op::Relu,
16332                inputs: vec![c2],
16333                shape: v2_shape,
16334                dtype: v2_dtype,
16335            });
16336            let release = g.push(Node {
16337                op: Op::Release,
16338                inputs: vec![producer_id],
16339                shape: Shape::from_dims(&[0]),
16340                dtype: DType::F32,
16341            });
16342            (leaf_a, leaf_b, leaf_c, release)
16343        };
16344        let ord = crate::opt::derive_ordering(
16345            &graph.read().unwrap(),
16346            &[leaf_a, leaf_b, leaf_c, release_id],
16347        );
16348        let deps = ord.deps_of(release_id);
16349        let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16350        // The direct readers of any View are the FIRST relu in each
16351        // chain — those are the nodes that read the bundle's bytes.
16352        // Every consumer further down reads its predecessor's
16353        // standalone output Storage, so they aren't in the alias-set
16354        // reader sweep. Verify the Release pins on the direct
16355        // readers — sufficient for bundle-single-eviction safety
16356        // because the chains are themselves data-dep ordered after
16357        // their direct readers.
16358        assert!(
16359            dep_set.contains(&leaf_a),
16360            "single-Relu chain a: leaf is the direct reader",
16361        );
16362        // For the b/c chains, the direct readers are the first Relus
16363        // (b1 / c1), not the leaves. The Release must include those.
16364        // Find them by walking inputs from leaves.
16365        let g = graph.read().unwrap();
16366        let b1 = g.node(leaf_b).inputs[0];
16367        let (c2, c1) = {
16368            let c2 = g.node(leaf_c).inputs[0];
16369            let c1 = g.node(c2).inputs[0];
16370            (c2, c1)
16371        };
16372        let _ = c2;
16373        assert!(
16374            dep_set.contains(&b1),
16375            "two-Relu chain b: first Relu is the direct bundle reader",
16376        );
16377        assert!(
16378            dep_set.contains(&c1),
16379            "three-Relu chain c: first Relu is the direct bundle reader",
16380        );
16381    }
16382
16383    // ------------------------------------------------------------------
16384    // Item 4 — Op::View / Op::ViewOwned autograd emits Op::ScatterIntoSlot
16385    // ------------------------------------------------------------------
16386
16387    /// The View's backward arm pushes an `Op::ScatterIntoSlot { slot }`
16388    /// node into the gradient graph as the producer's input gradient.
16389    /// Synthetic test: build a 2-slot producer + Op::View(slot 1) +
16390    /// a Relu downstream + invoke NodeHandle::backward + walk the produced
16391    /// gradient graph and assert a ScatterIntoSlot was emitted.
16392    #[test]
16393    fn op_view_backward_emits_scatter_into_slot() {
16394        let producer_t =
16395            NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
16396        let graph: SharedGraph = Arc::clone(producer_t.graph());
16397        let producer_id = producer_t.id();
16398        let view_id = {
16399            let mut g = graph.write().unwrap();
16400            let specs = two_slot_views_2x3_and_2x4();
16401            g.set_output_views(producer_id, specs.into())
16402                .expect("output_views");
16403            drop(g);
16404            let v1 = producer_t.view(1).expect("slot 1 view");
16405            v1.id()
16406        };
16407        // Build a tiny tape-tracked loss = sum(relu(v1)).
16408        let v1_tensor = NodeHandle::from_existing(Arc::clone(&graph), view_id);
16409        let relu_t = v1_tensor.relu();
16410        let loss_t = relu_t.sum_all();
16411
16412        // Take backward — exercises the View's backward arm.
16413        let grads = loss_t.backward();
16414
16415        // The producer's input gradient should be reachable via a
16416        // chain that includes an Op::ScatterIntoSlot { slot: 1 } node.
16417        let producer_tensor = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16418        let grad_for_producer = grads
16419            .get(&producer_tensor)
16420            .expect("producer has an accumulated gradient");
16421        let grad_id = grad_for_producer.id();
16422        let g = graph.read().unwrap();
16423        let scatter_present = matches!(g.node(grad_id).op, Op::ScatterIntoSlot { slot: 1 }) || {
16424            // Walk one hop back through `Op::Add` accumulations
16425            // if any.
16426            let n = g.node(grad_id);
16427            n.inputs
16428                .iter()
16429                .any(|inp| matches!(g.node(*inp).op, Op::ScatterIntoSlot { slot: 1 }))
16430        };
16431        assert!(
16432            scatter_present,
16433            "View(slot=1) backward must emit an Op::ScatterIntoSlot {{ slot: 1 }} \
16434             into the gradient graph; got grad node op = {:?}",
16435            g.node(grad_id).op,
16436        );
16437    }
16438
16439    // ----- Op::Branch inert scaffold (Phase A PR-A0 of the
16440    // "plan IS the graph" rebuild) -----
16441
16442    /// Back-compat by construction: a graph with ZERO `Op::Branch`
16443    /// nodes builds with exactly the arena it had before the variant
16444    /// existed. The locked design guarantees "a graph with zero
16445    /// Op::Branch nodes is exactly today's single-route graph" — this
16446    /// test pins that: the same builder calls produce the same node
16447    /// count, the same topo order, and not a single `Op::Branch` node.
16448    /// GAP-003 STEP 1: the panic IS reachable from the public API today.
16449    ///
16450    /// `NodeHandle::from_f32` returns `Self`, so a length/shape mismatch has
16451    /// nowhere to go but `assert_eq!` inside `from_host_buffer_on`. This test
16452    /// PASSES today and is deleted by the fix -- it exists to prove the defect
16453    /// is live from a caller's seat, not merely present in the source.
16454    /// GAP-003: a length/shape mismatch DECLINES instead of panicking.
16455    ///
16456    /// ⚠️ This started life as a `#[should_panic]` probe proving the defect was
16457    /// reachable from the public API. The bulk `.unwrap()` pass then appended
16458    /// `.unwrap()` to it, and it KEPT PASSING -- for the wrong reason: unwrapping
16459    /// an `Err` panics, and the `Err` message contains the expected substring, so
16460    /// the assertion could no longer tell "the API panics" from "I unwrapped a
16461    /// Result". A vacuous green produced by the very edit that fixed the defect.
16462    ///
16463    /// It now asserts the `Err` DIRECTLY, with no `unwrap`, and matches on the
16464    /// LENGTH-MISMATCH message specifically -- not merely on `is_err()`. That
16465    /// distinction is load-bearing: `from_host_buffer_on` has a second failure
16466    /// path (`storage_from_host_buffer_owned_dyn`), so a bare `is_err()` could
16467    /// not tell this decline from that one.
16468    #[test]
16469    fn gap003_from_f32_declines_a_length_mismatch() {
16470        // 2 elements declared as a 3-element shape.
16471        let err = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[3]), cpu_dev())
16472            .expect_err("a length/shape mismatch must DECLINE, not construct");
16473        let msg = err.to_string();
16474        assert!(
16475            msg.contains("does not match shape element count"),
16476            "the decline must name the LENGTH MISMATCH specifically, got: {msg}"
16477        );
16478        assert!(
16479            msg.contains('2') && msg.contains('3'),
16480            "and both operands: {msg}"
16481        );
16482
16483        // CONTROL: a MATCHING length still constructs, so the guard is not
16484        // "this constructor always fails".
16485        assert!(
16486            NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).is_ok()
16487        );
16488    }
16489
16490    #[test]
16491    fn zero_branch_graph_builds_unchanged() {
16492        // Build: c = (a + b) * a — the same DAG the topo-order tests
16493        // use, exercised here purely to prove the arena is untouched by
16494        // the new variant.
16495        let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
16496        let b = a
16497            .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
16498            .unwrap();
16499        let sum = a.add(&b);
16500        let c = sum.mul(&a);
16501
16502        let g = c.graph();
16503        let guard = g.read().unwrap();
16504
16505        // Exactly four nodes (a, b, sum, c) — no implicit Branch
16506        // anywhere.
16507        assert_eq!(
16508            guard.len(),
16509            4,
16510            "zero-Branch graph must have the same node count as before"
16511        );
16512
16513        // Topo order is unchanged and contains zero Branch nodes.
16514        let order = topo_order(&guard, c.id());
16515        assert_eq!(order.len(), 4);
16516        let branch_count = order
16517            .iter()
16518            .filter(|&&id| matches!(guard.node(id).op, Op::Branch { .. }))
16519            .count();
16520        assert_eq!(branch_count, 0, "no builder constructs Op::Branch in PR-A0");
16521
16522        // The ops are exactly the ones the builders emitted (no
16523        // structural rewrite slipped in a merge node).
16524        assert!(matches!(guard.node(a.id()).op, Op::Const));
16525        assert!(matches!(guard.node(b.id()).op, Op::Const));
16526        assert!(matches!(guard.node(sum.id()).op, Op::Add));
16527        assert!(matches!(guard.node(c.id()).op, Op::Mul));
16528    }
16529
16530    /// The variant exists and its infallible accessor behaves: a
16531    /// hand-constructed `Op::Branch` reports `short_name() == "Branch"`,
16532    /// and the multi-path encoding (arms = `inputs`, explicit
16533    /// `reconverge_at`) round-trips through the arena. This is the only
16534    /// place in PR-A0 that constructs the variant — the production
16535    /// builders land in PR-A1.
16536    #[test]
16537    fn branch_variant_exists_and_short_name_works() {
16538        // short_name / the Op::short_name() facade both return the
16539        // stable "Branch" constant.
16540        let reconverge = NodeId(7);
16541        let branch_op = Op::Branch {
16542            reconverge_at: reconverge,
16543        };
16544        assert_eq!(branch_op.short_name(), "Branch");
16545        assert_eq!(op_short_name(&branch_op), "Branch");
16546
16547        // Structural nodes carry no destructive input (matches the
16548        // other structural ops: Const / View / ScatterIntoSlot).
16549        assert_eq!(branch_op.destructive_input(), None);
16550
16551        // Encode a 2-arm merge directly on the arena: two route exits
16552        // as `inputs`, the reconvergence node named explicitly. Prove
16553        // the encoding survives a push + read-back unchanged.
16554        let mut g = Graph::new();
16555        let arm0 = g.push(Node {
16556            op: Op::Const,
16557            inputs: vec![],
16558            shape: Shape::from_dims(&[2]),
16559            dtype: DType::F32,
16560        });
16561        let arm1 = g.push(Node {
16562            op: Op::Const,
16563            inputs: vec![],
16564            shape: Shape::from_dims(&[2]),
16565            dtype: DType::F32,
16566        });
16567        let merged = g.push(Node {
16568            op: Op::Const,
16569            inputs: vec![],
16570            shape: Shape::from_dims(&[2]),
16571            dtype: DType::F32,
16572        });
16573        let branch = g.push(Node {
16574            op: Op::Branch {
16575                reconverge_at: merged,
16576            },
16577            inputs: vec![arm0, arm1],
16578            shape: Shape::from_dims(&[2]),
16579            dtype: DType::F32,
16580        });
16581
16582        let node = g.node(branch);
16583        assert_eq!(node.op.short_name(), "Branch");
16584        // Arms are the node's inputs (each input = one route's exit).
16585        assert_eq!(node.inputs, vec![arm0, arm1]);
16586        // The explicit reconvergence node is carried on the op.
16587        match node.op {
16588            Op::Branch { reconverge_at } => assert_eq!(reconverge_at, merged),
16589            ref other => panic!("expected Op::Branch, got {other:?}"),
16590        }
16591    }
16592
16593    // ----- Op::Branch builders + build-time validation
16594    // (Phase A PR-A1 of the "plan IS the graph" rebuild) -----
16595
16596    /// Hand-build a 2-arm diamond directly on the arena and return the
16597    /// pieces the branch builders will stitch together:
16598    /// `diverge` → {`arm0`, `arm1`} → `reconverge`. The reconverge node
16599    /// already reads arm0 as input 0, which is exactly the runnability
16600    /// invariant the builders must preserve (a finalized-but-unpicked
16601    /// branch still realizes on arm 0). Every node is `[2] f32` so the
16602    /// cast-to-uniform check has agreeing shape/dtype across arms.
16603    fn diamond_2arm() -> (Graph, NodeId, NodeId, NodeId, NodeId) {
16604        let mut g = Graph::new();
16605        let diverge = g.push(Node {
16606            op: Op::Const,
16607            inputs: vec![],
16608            shape: Shape::from_dims(&[2]),
16609            dtype: DType::F32,
16610        });
16611        // arm0 = relu(diverge), arm1 = silu(diverge): two interior nodes,
16612        // each reachable only through its own arm from the diverge point.
16613        let arm0 = g.push(Node {
16614            op: Op::Relu,
16615            inputs: vec![diverge],
16616            shape: Shape::from_dims(&[2]),
16617            dtype: DType::F32,
16618        });
16619        let arm1 = g.push(Node {
16620            op: Op::Silu,
16621            inputs: vec![diverge],
16622            shape: Shape::from_dims(&[2]),
16623            dtype: DType::F32,
16624        });
16625        // reconverge reads arm0 (runnability: arm 0 is always input 0).
16626        let reconverge = g.push(Node {
16627            op: Op::Relu,
16628            inputs: vec![arm0],
16629            shape: Shape::from_dims(&[2]),
16630            dtype: DType::F32,
16631        });
16632        (g, diverge, arm0, arm1, reconverge)
16633    }
16634
16635    /// (a) A 2-arm diamond round-trips through
16636    /// `open_branch`/`add_arm`/`finalize_branches`: it produces exactly
16637    /// one valid `Op::Branch` node whose `inputs` are the arm exits in
16638    /// order and whose `reconverge_at` is the named merge node.
16639    #[test]
16640    fn two_arm_diamond_round_trips_to_branch_node() {
16641        let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16642        let before = g.len();
16643
16644        let mut b = g.open_branch(diverge);
16645        b.add_arm(arm0);
16646        b.add_arm(arm1);
16647        let branch = b
16648            .finalize_branches(&mut g, reconverge)
16649            .expect("well-formed 2-arm branch must finalize")
16650            .expect("2 arms survive — not collapsed to a single arm");
16651
16652        // Exactly one node was appended (the Branch); no orphan debris.
16653        assert_eq!(g.len(), before + 1);
16654
16655        let node = g.node(branch);
16656        assert!(matches!(node.op, Op::Branch { .. }));
16657        // Arms are the node's inputs, in add order: arm0 first.
16658        assert_eq!(node.inputs, vec![arm0, arm1]);
16659        match node.op {
16660            Op::Branch { reconverge_at } => assert_eq!(reconverge_at, reconverge),
16661            ref other => panic!("expected Op::Branch, got {other:?}"),
16662        }
16663        // The merge node still carries arm0's shape/dtype (cast-to-uniform
16664        // validated, not rewritten).
16665        assert_eq!(node.shape, g.node(arm0).shape);
16666        assert_eq!(node.dtype, g.node(arm0).dtype);
16667    }
16668
16669    /// (b) A `reconverge_at` that is NOT a descendant of the diverge
16670    /// point returns `Error::InvalidBranch` — never a panic.
16671    #[test]
16672    fn reconverge_not_descendant_of_diverge_is_typed_err() {
16673        let (mut g, diverge, arm0, arm1, _reconverge) = diamond_2arm();
16674        // A sibling node that does NOT descend from `diverge`.
16675        let unrelated = g.push(Node {
16676            op: Op::Const,
16677            inputs: vec![],
16678            shape: Shape::from_dims(&[2]),
16679            dtype: DType::F32,
16680        });
16681
16682        let mut b = g.open_branch(diverge);
16683        b.add_arm(arm0);
16684        b.add_arm(arm1);
16685        let err = b
16686            .finalize_branches(&mut g, unrelated)
16687            .expect_err("reconverge that doesn't descend from diverge must be rejected");
16688        assert!(
16689            matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16690            "expected InvalidBranch, got {err:?}",
16691        );
16692    }
16693
16694    /// (c) A non-disjoint arm — an arm interior node reachable from
16695    /// outside that arm (shared with the rest of the graph) — returns
16696    /// `Error::InvalidBranch`.
16697    #[test]
16698    fn non_disjoint_arm_is_typed_err() {
16699        let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16700        // Add a reader OUTSIDE the branch that consumes arm0's interior.
16701        // arm0 is now reachable from a node that isn't part of the merge,
16702        // so the arm is not internally disjoint.
16703        let _external_reader = g.push(Node {
16704            op: Op::Relu,
16705            inputs: vec![arm0],
16706            shape: Shape::from_dims(&[2]),
16707            dtype: DType::F32,
16708        });
16709
16710        let mut b = g.open_branch(diverge);
16711        b.add_arm(arm0);
16712        b.add_arm(arm1);
16713        let err = b
16714            .finalize_branches(&mut g, reconverge)
16715            .expect_err("an arm interior read from outside the branch must be rejected");
16716        assert!(
16717            matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16718            "expected InvalidBranch, got {err:?}",
16719        );
16720    }
16721
16722    /// (c') Arms that disagree on shape/dtype at their exits violate
16723    /// cast-to-uniform and return `Error::InvalidBranch` (validate-and-Err
16724    /// — no implicit Cast insertion in PR-A1).
16725    #[test]
16726    fn arms_disagreeing_on_dtype_is_typed_err() {
16727        let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16728        // A second arm with a DIFFERENT dtype than arm0.
16729        let arm1_f16 = g.push(Node {
16730            op: Op::Silu,
16731            inputs: vec![diverge],
16732            shape: Shape::from_dims(&[2]),
16733            dtype: DType::F16,
16734        });
16735
16736        let mut b = g.open_branch(diverge);
16737        b.add_arm(arm0);
16738        b.add_arm(arm1_f16);
16739        let err = b
16740            .finalize_branches(&mut g, reconverge)
16741            .expect_err("arms with mismatched dtype must be rejected (cast-to-uniform)");
16742        assert!(
16743            matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16744            "expected InvalidBranch, got {err:?}",
16745        );
16746    }
16747
16748    /// (d) `finalize_branches` drops a single-arm branch: with only one
16749    /// surviving arm there is no real decision point, so no `Op::Branch`
16750    /// node is emitted (`Ok(None)`), the arena is left untouched, and the
16751    /// graph collapses back to that arm.
16752    #[test]
16753    fn single_arm_branch_is_dropped() {
16754        let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16755        let before = g.len();
16756
16757        let mut b = g.open_branch(diverge);
16758        b.add_arm(arm0);
16759        let result = b
16760            .finalize_branches(&mut g, reconverge)
16761            .expect("a single-arm branch is valid — it just collapses");
16762        assert!(
16763            result.is_none(),
16764            "single-arm branch must NOT emit an Op::Branch"
16765        );
16766        // No node appended: the lone arm is the graph, unchanged.
16767        assert_eq!(
16768            g.len(),
16769            before,
16770            "dropping a single-arm branch leaves the arena untouched"
16771        );
16772        let branch_count = (0..g.len())
16773            .filter(|&i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }))
16774            .count();
16775        assert_eq!(branch_count, 0);
16776    }
16777
16778    /// (e) The runnability invariant: the emitted `Op::Branch`'s inputs
16779    /// always include arm-0's exit as input 0, so a finalized-but-not-yet-
16780    /// route-picked graph still realizes on arm 0 (a graph with a
16781    /// finalized branch must still be executable). The named reconverge
16782    /// node reads arm-0's exit, so realizing on arm 0 alone produces a
16783    /// defined value at the merge.
16784    #[test]
16785    fn finalized_branch_preserves_arm0_runnability() {
16786        let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16787
16788        let mut b = g.open_branch(diverge);
16789        b.add_arm(arm0);
16790        b.add_arm(arm1);
16791        let branch = b
16792            .finalize_branches(&mut g, reconverge)
16793            .expect("well-formed branch finalizes")
16794            .expect("2 arms survive");
16795
16796        // arm 0 is input 0 of the Branch — the always-realizable route.
16797        assert_eq!(g.node(branch).inputs.first().copied(), Some(arm0));
16798        // And the named reconverge node reads arm0, so realizing on
16799        // arm 0 alone produces a defined value at the merge.
16800        assert!(
16801            g.node(reconverge).inputs.contains(&arm0),
16802            "reconverge must read arm-0's exit so the unpicked graph runs on arm 0",
16803        );
16804    }
16805
16806    // ===================================================================
16807    // PR-B4: required compaction of the append-only arena.
16808    // ===================================================================
16809
16810    use crate::run::{extract_runs, lower_runs_arm0};
16811
16812    /// Build the same 2-arm diamond the run.rs tests use, finalized into a
16813    /// real `Op::Branch`. Returns `(g, diverge, arm0, arm1, reconverge,
16814    /// branch, post)`. `post` reads `reconverge`, so the post-merge region
16815    /// is a non-empty run and `post` is a stable root.
16816    fn diamond_with_branch_b4() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
16817        let mk = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
16818            g.push(Node {
16819                op,
16820                inputs,
16821                shape: Shape::from_dims(&[2]),
16822                dtype: DType::F32,
16823            })
16824        };
16825        let mut g = Graph::new();
16826        let pre = mk(&mut g, Op::Const, vec![]);
16827        let diverge = mk(&mut g, Op::Relu, vec![pre]);
16828        let arm0 = mk(&mut g, Op::Silu, vec![diverge]);
16829        let arm1 = mk(&mut g, Op::GeluTanh, vec![diverge]);
16830        let reconverge = mk(&mut g, Op::Relu, vec![arm0]);
16831        let mut b = g.open_branch(diverge);
16832        b.add_arm(arm0);
16833        b.add_arm(arm1);
16834        let branch = b
16835            .finalize_branches(&mut g, reconverge)
16836            .expect("well-formed 2-arm branch finalizes")
16837            .expect("2 arms survive");
16838        let post = mk(&mut g, Op::Tanh, vec![reconverge]);
16839        (g, diverge, arm0, arm1, reconverge, branch, post)
16840    }
16841
16842    /// PR-D1 storage-class substrate: the op-inferred class is correct
16843    /// (`Op::Const` → Shared, `Op::WriteSlice` → SessionState, other →
16844    /// Transient), an explicit override beats the inferred default (a
16845    /// KV-cache placeholder `Op::Const` marked SessionState), and `compact`
16846    /// carries the override to the node's new id while inferred defaults
16847    /// still hold. Born-red: fails if classification, override precedence,
16848    /// or the compaction remap is wrong.
16849    #[test]
16850    fn storage_class_inference_override_and_compaction() {
16851        let mut g = Graph::new();
16852        // A shared weight Const, a session-state KV placeholder Const, a
16853        // transient activation, and an in-place cache-write target.
16854        let weight = g.push(Node {
16855            op: Op::Const,
16856            inputs: vec![],
16857            shape: Shape::from_dims(&[2]),
16858            dtype: DType::F32,
16859        });
16860        let kv = g.push(Node {
16861            op: Op::Const,
16862            inputs: vec![],
16863            shape: Shape::from_dims(&[2]),
16864            dtype: DType::F32,
16865        });
16866        let act = g.push(Node {
16867            op: Op::Relu,
16868            inputs: vec![weight],
16869            shape: Shape::from_dims(&[2]),
16870            dtype: DType::F32,
16871        });
16872        let write = g.push(Node {
16873            op: Op::WriteSlice {
16874                ranges: vec![(0, 2)],
16875                dyn_offset: None,
16876            },
16877            inputs: vec![kv, act],
16878            shape: Shape::from_dims(&[2]),
16879            dtype: DType::F32,
16880        });
16881
16882        // Op-inferred defaults.
16883        assert_eq!(
16884            g.storage_class(weight),
16885            StorageClass::Shared,
16886            "Const → Shared"
16887        );
16888        assert_eq!(
16889            g.storage_class(act),
16890            StorageClass::Transient,
16891            "activation → Transient"
16892        );
16893        assert_eq!(
16894            g.storage_class(write),
16895            StorageClass::SessionState,
16896            "WriteSlice → SessionState"
16897        );
16898        // No overrides set yet.
16899        assert_eq!(
16900            g.storage_class(kv),
16901            StorageClass::Shared,
16902            "KV placeholder Const infers Shared before override"
16903        );
16904        assert!(!g.has_storage_class_override(kv));
16905        assert_eq!(g.storage_class_override_count(), 0);
16906
16907        // Explicit override: the KV placeholder is session state, not a
16908        // shared weight.
16909        g.set_storage_class(kv, StorageClass::SessionState);
16910        assert_eq!(
16911            g.storage_class(kv),
16912            StorageClass::SessionState,
16913            "override beats inferred default"
16914        );
16915        assert!(g.has_storage_class_override(kv));
16916        assert_eq!(g.storage_class_override_count(), 1);
16917
16918        // Compaction carries the override to the new id; inferred defaults
16919        // (no side-table entry) still resolve from the op.
16920        let remap = compact(&mut g, &[write]);
16921        let n_kv = remap.get(kv).expect("kv survives (input of write)");
16922        let n_weight = remap
16923            .get(weight)
16924            .expect("weight survives (transitively under act)");
16925        let n_write = remap.get(write).expect("write is the root");
16926        assert_eq!(
16927            g.storage_class(n_kv),
16928            StorageClass::SessionState,
16929            "override remapped by compact"
16930        );
16931        assert!(g.has_storage_class_override(n_kv));
16932        assert_eq!(
16933            g.storage_class_override_count(),
16934            1,
16935            "exactly the one override survives"
16936        );
16937        assert_eq!(
16938            g.storage_class(n_weight),
16939            StorageClass::Shared,
16940            "inferred Shared still holds post-compact"
16941        );
16942        assert_eq!(
16943            g.storage_class(n_write),
16944            StorageClass::SessionState,
16945            "inferred SessionState still holds post-compact"
16946        );
16947        assert!(g.verify_no_dangling().is_ok());
16948    }
16949
16950    /// (a) A deliberately-orphaned node (pushed, referenced by nothing) is
16951    /// dropped by `compact`; the node count shrinks by exactly the orphan
16952    /// count, and every still-reachable node survives.
16953    #[test]
16954    fn compact_drops_orphan_debris() {
16955        let mut g = Graph::new();
16956        let a = g.push(Node {
16957            op: Op::Const,
16958            inputs: vec![],
16959            shape: Shape::from_dims(&[2]),
16960            dtype: DType::F32,
16961        });
16962        let b = g.push(Node {
16963            op: Op::Relu,
16964            inputs: vec![a],
16965            shape: Shape::from_dims(&[2]),
16966            dtype: DType::F32,
16967        });
16968        let c = g.push(Node {
16969            op: Op::Silu,
16970            inputs: vec![b],
16971            shape: Shape::from_dims(&[2]),
16972            dtype: DType::F32,
16973        });
16974        // Two pieces of exploration debris: reachable from nothing in the
16975        // live structure (no root, no side-effect, no branch references them).
16976        let _orphan0 = g.push(Node {
16977            op: Op::Const,
16978            inputs: vec![],
16979            shape: Shape::from_dims(&[2]),
16980            dtype: DType::F32,
16981        });
16982        let _orphan1 = g.push(Node {
16983            op: Op::Tanh,
16984            inputs: vec![_orphan0],
16985            shape: Shape::from_dims(&[2]),
16986            dtype: DType::F32,
16987        });
16988
16989        let before = g.len();
16990        let remap = compact(&mut g, &[c]);
16991
16992        assert_eq!(
16993            g.len(),
16994            before - 2,
16995            "compaction drops exactly the two orphan-debris nodes",
16996        );
16997        // The three reachable nodes all survived (have new ids).
16998        assert!(remap.get(a).is_some());
16999        assert!(remap.get(b).is_some());
17000        assert!(remap.get(c).is_some());
17001        // The orphans are gone.
17002        assert!(remap.get(_orphan0).is_none());
17003        assert!(remap.get(_orphan1).is_none());
17004        // The surviving chain still resolves: c' reads b' reads a'.
17005        let (na, nb, nc) = (
17006            remap.get(a).unwrap(),
17007            remap.get(b).unwrap(),
17008            remap.get(c).unwrap(),
17009        );
17010        assert_eq!(g.node(nc).inputs, vec![nb]);
17011        assert_eq!(g.node(nb).inputs, vec![na]);
17012        assert_eq!(g.node(na).inputs, Vec::<NodeId>::new());
17013        assert_no_dangling(&g);
17014    }
17015
17016    /// (b) Branches preserved: a graph with a finalized `Op::Branch` keeps
17017    /// every arm + `reconverge_at` after compaction (remapped), and the
17018    /// arm-0 lowering yields the same logical route.
17019    #[test]
17020    fn compact_preserves_branch_arms_and_reconverge() {
17021        let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch_b4();
17022
17023        // Inject orphan debris so compaction has something to drop and the
17024        // surviving-branch claim is non-trivial.
17025        let _debris = g.push(Node {
17026            op: Op::Const,
17027            inputs: vec![],
17028            shape: Shape::from_dims(&[2]),
17029            dtype: DType::F32,
17030        });
17031
17032        // Baseline arm-0 route over old ids, mapped to the op sequence.
17033        let before_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
17034            .iter()
17035            .map(|&id| g.node(id).op.short_name())
17036            .collect();
17037
17038        let remap = compact(&mut g, &[post]);
17039
17040        // Every branch participant survived.
17041        let narm0 = remap.get(arm0).expect("arm0 survives");
17042        let narm1 = remap
17043            .get(arm1)
17044            .expect("arm1 (the non-fallback arm) survives");
17045        let nrecon = remap.get(reconverge).expect("reconverge survives");
17046        let nbranch = remap.get(branch).expect("the Branch node itself survives");
17047        let npost = remap.get(post).expect("post survives");
17048
17049        // The Branch's inputs are the remapped arm exits (arm0 first), and
17050        // its reconverge_at is the remapped reconverge — it still resolves.
17051        let bn = g.node(nbranch);
17052        assert!(matches!(bn.op, Op::Branch { .. }));
17053        assert_eq!(
17054            bn.inputs,
17055            vec![narm0, narm1],
17056            "arm exits remapped, arm0 first"
17057        );
17058        match bn.op {
17059            Op::Branch { reconverge_at } => assert_eq!(reconverge_at, nrecon),
17060            ref other => panic!("expected Op::Branch, got {other:?}"),
17061        }
17062        // reconverge still reads arm0 (runnability preserved through remap).
17063        assert!(g.node(nrecon).inputs.contains(&narm0));
17064        // The arm-0 route is logically identical (same op sequence).
17065        let after_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
17066            .iter()
17067            .map(|&id| g.node(id).op.short_name())
17068            .collect();
17069        assert_eq!(before_ops, after_ops, "arm-0 route is logically unchanged");
17070        assert_no_dangling(&g);
17071    }
17072
17073    /// (c) Base map preserved: a branchless, fully-reachable graph compacts
17074    /// to itself — no node dropped; ids may renumber but the structure is
17075    /// identical.
17076    #[test]
17077    fn compact_branchless_reachable_is_identity_in_structure() {
17078        let mut g = Graph::new();
17079        let a = g.push(Node {
17080            op: Op::Const,
17081            inputs: vec![],
17082            shape: Shape::from_dims(&[2]),
17083            dtype: DType::F32,
17084        });
17085        let b = g.push(Node {
17086            op: Op::Relu,
17087            inputs: vec![a],
17088            shape: Shape::from_dims(&[2]),
17089            dtype: DType::F32,
17090        });
17091        let c = g.push(Node {
17092            op: Op::Silu,
17093            inputs: vec![b],
17094            shape: Shape::from_dims(&[2]),
17095            dtype: DType::F32,
17096        });
17097        let d = g.push(Node {
17098            op: Op::Tanh,
17099            inputs: vec![c],
17100            shape: Shape::from_dims(&[2]),
17101            dtype: DType::F32,
17102        });
17103
17104        let before_ops: Vec<&'static str> = extract_runs(&g, d)
17105            .iter()
17106            .flat_map(|r| {
17107                r.members
17108                    .iter()
17109                    .map(|&id| g.node(id).op.short_name())
17110                    .collect::<Vec<_>>()
17111            })
17112            .collect();
17113        let before_len = g.len();
17114
17115        let remap = compact(&mut g, &[d]);
17116
17117        assert_eq!(g.len(), before_len, "a fully-reachable graph drops nothing");
17118        for n in [a, b, c, d] {
17119            assert!(remap.get(n).is_some(), "every node survives");
17120        }
17121        // Structure identical: same op sequence over the compacted graph.
17122        let nd = remap.get(d).unwrap();
17123        let after_ops: Vec<&'static str> = extract_runs(&g, nd)
17124            .iter()
17125            .flat_map(|r| {
17126                r.members
17127                    .iter()
17128                    .map(|&id| g.node(id).op.short_name())
17129                    .collect::<Vec<_>>()
17130            })
17131            .collect();
17132        assert_eq!(before_ops, after_ops);
17133        assert_no_dangling(&g);
17134    }
17135
17136    /// (d) No dangling + round-trip: after `compact`, NO NodeId reference
17137    /// (node inputs, op-carried `reconverge_at`, or any side-table) points
17138    /// outside the new arena, AND `extract_runs` / arm-0 lowering on the
17139    /// compacted graph yields the identical logical result, including for
17140    /// graphs carrying every side-table (placements, target_backends,
17141    /// layouts, storage_map, node_output_views, side_effect_roots).
17142    #[test]
17143    fn compact_no_dangling_and_round_trip_with_side_tables() {
17144        let (mut g, diverge, arm0, _arm1, reconverge, _branch, post) = diamond_with_branch_b4();
17145
17146        // Populate side-tables on surviving nodes so the remap must carry
17147        // them. (target_backend on a couple nodes; placement on one.)
17148        g.set_target_backend(arm0, BackendId::Cpu);
17149        g.set_target_backend(reconverge, BackendId::Cpu);
17150        g.set_placement(diverge, DeviceLocation::Cpu);
17151        // A side-effect root that is itself orphan-from-roots: a Release-like
17152        // op the executor must keep even though no output reads it.
17153        let se = g.push(Node {
17154            op: Op::Const,
17155            inputs: vec![post],
17156            shape: Shape::from_dims(&[2]),
17157            dtype: DType::F32,
17158        });
17159        g.add_side_effect_root(se);
17160
17161        // Orphan debris (referenced by nothing live) to force a real drop.
17162        let _debris = g.push(Node {
17163            op: Op::Const,
17164            inputs: vec![],
17165            shape: Shape::from_dims(&[2]),
17166            dtype: DType::F32,
17167        });
17168
17169        let before_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
17170            .iter()
17171            .map(|&id| g.node(id).op.short_name())
17172            .collect();
17173
17174        let remap = compact(&mut g, &[post]);
17175
17176        // No dangling references anywhere.
17177        assert_no_dangling(&g);
17178
17179        // The side-effect root survived (a side-effect-only node is a
17180        // reachability seed) and its side-table entry was remapped.
17181        let nse = remap.get(se).expect("side-effect root survives compaction");
17182        assert!(
17183            g.side_effect_roots().contains(&nse),
17184            "the remapped side-effect root is registered post-compaction",
17185        );
17186        // The surviving target_backend side-table is keyed by the new ids.
17187        assert_eq!(
17188            g.target_backend(remap.get(arm0).unwrap()),
17189            Some(BackendId::Cpu)
17190        );
17191        assert_eq!(
17192            g.target_backend(remap.get(reconverge).unwrap()),
17193            Some(BackendId::Cpu)
17194        );
17195        assert_eq!(
17196            g.placement(remap.get(diverge).unwrap()),
17197            Some(DeviceLocation::Cpu)
17198        );
17199
17200        // Round-trip: the arm-0 route is logically identical.
17201        let npost = remap.get(post).unwrap();
17202        let after_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
17203            .iter()
17204            .map(|&id| g.node(id).op.short_name())
17205            .collect();
17206        assert_eq!(
17207            before_run_ops, after_run_ops,
17208            "compaction preserves the realized arm-0 route exactly",
17209        );
17210    }
17211
17212    /// Helper: assert NO NodeId reference in the graph points outside the
17213    /// arena. Covers node `inputs`, the op-carried `Op::Branch.reconverge_at`,
17214    /// every NodeId-keyed side-table, and the `side_effect_roots` vec — the
17215    /// exhaustive no-dangling safety net for a missed remap.
17216    fn assert_no_dangling(g: &Graph) {
17217        let n = g.len();
17218        let ok = |id: NodeId| id.0 < n;
17219        for i in 0..n {
17220            let node = g.node(NodeId(i));
17221            for &inp in &node.inputs {
17222                assert!(ok(inp), "Node#{i} input {:?} dangles (len={n})", inp);
17223            }
17224            if let Op::Branch { reconverge_at } = node.op {
17225                assert!(
17226                    ok(reconverge_at),
17227                    "Node#{i} Branch.reconverge_at {:?} dangles (len={n})",
17228                    reconverge_at
17229                );
17230            }
17231        }
17232        for &r in g.side_effect_roots() {
17233            assert!(ok(r), "side_effect_root {:?} dangles (len={n})", r);
17234        }
17235        // Use the graph's own verification entry point as the load-bearing
17236        // assert (it covers every side-table by reading the private fields).
17237        assert!(
17238            g.verify_no_dangling().is_ok(),
17239            "Graph::verify_no_dangling found a dangling reference: {:?}",
17240            g.verify_no_dangling().err(),
17241        );
17242    }
17243
17244    #[test]
17245    fn scan_variants_construct_and_name() {
17246        use crate::{Graph, Node, Op, ScanEmit, ScanPredicate, ScanRole};
17247        use fuel_ir::{DType, Shape};
17248        let mut g = Graph::new();
17249        let s = Shape::from_dims(&[1, 1, 1]);
17250        let carry = g.push(Node {
17251            op: Op::Const,
17252            inputs: vec![],
17253            shape: s.clone(),
17254            dtype: DType::F32,
17255        });
17256        // A ScanPlaceholder leaf (the per-step carry hole).
17257        let hole = g.push(Node {
17258            op: Op::ScanPlaceholder {
17259                role: ScanRole::Carry,
17260                index: 0,
17261            },
17262            inputs: vec![],
17263            shape: s.clone(),
17264            dtype: DType::F32,
17265        });
17266        // A trivial body: new_carry = hole (identity); body_y = hole.
17267        // Op::Scan node: inputs = [init_carry, <no xs>, <no consts>, body_new_carry, body_y].
17268        let scan = g.push(Node {
17269            op: Op::Scan {
17270                n_carries: 1,
17271                n_xs: 0,
17272                bound: 1,
17273                emit: ScanEmit::All,
17274                early_exit: None,
17275            },
17276            inputs: vec![carry, hole, hole],
17277            shape: s.clone(),
17278            dtype: DType::F32,
17279        });
17280        assert_eq!(g.node(scan).op.short_name(), "Scan");
17281        assert_eq!(g.node(hole).op.short_name(), "ScanPlaceholder");
17282        // early_exit is constructible (guarded elsewhere) but never Some on a live path.
17283        let _guarded = Op::Scan {
17284            n_carries: 1,
17285            n_xs: 0,
17286            bound: 1,
17287            emit: ScanEmit::Final,
17288            early_exit: Some(ScanPredicate),
17289        };
17290        // derive_view_output_layout: Scan is NOT a view op -> Err (handled by the catch-all).
17291        let lay = fuel_ir::Layout::contiguous(s.clone());
17292        let derived = crate::derive_view_output_layout(
17293            &Op::Scan {
17294                n_carries: 1,
17295                n_xs: 0,
17296                bound: 1,
17297                emit: ScanEmit::All,
17298                early_exit: None,
17299            },
17300            &lay,
17301        );
17302        assert!(
17303            derived.is_err(),
17304            "Op::Scan must not be treated as a view op"
17305        );
17306        let _ = scan;
17307    }
17308
17309    #[test]
17310    fn scan_builder_all_and_final_shapes() {
17311        use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17312        use fuel_ir::{DType, Shape};
17313        use std::sync::{Arc, RwLock};
17314        let graph = Arc::new(RwLock::new(Graph::new()));
17315        let cs = Shape::from_dims(&[2]); // carry shape
17316        let ys = Shape::from_dims(&[2]); // per-step y shape
17317        let (carry, hole, new_carry, body_y) = {
17318            let mut g = graph.write().unwrap();
17319            let carry = g.push(Node {
17320                op: Op::Const,
17321                inputs: vec![],
17322                shape: cs.clone(),
17323                dtype: DType::F32,
17324            });
17325            let hole = g.push(Node {
17326                op: Op::ScanPlaceholder {
17327                    role: ScanRole::Carry,
17328                    index: 0,
17329                },
17330                inputs: vec![],
17331                shape: cs.clone(),
17332                dtype: DType::F32,
17333            });
17334            let new_carry = g.push(Node {
17335                op: Op::MulScalar(2.0),
17336                inputs: vec![hole],
17337                shape: cs.clone(),
17338                dtype: DType::F32,
17339            });
17340            let body_y = g.push(Node {
17341                op: Op::AddScalar(1.0),
17342                inputs: vec![new_carry],
17343                shape: ys.clone(),
17344                dtype: DType::F32,
17345            });
17346            (carry, hole, new_carry, body_y)
17347        };
17348        let t = |id| NodeHandle {
17349            graph: graph.clone(),
17350            id,
17351        }; // same-crate access to private fields
17352        let init = t(carry);
17353        let (nc, by) = (t(new_carry), t(body_y));
17354        let bound = 4usize;
17355
17356        let all = init
17357            .scan(&[], &[], &nc, &by, bound, ScanEmit::All)
17358            .expect("scan All");
17359        assert_eq!(
17360            all.shape().dims(),
17361            &[bound, 2],
17362            "emit=All -> [bound] ++ body_y"
17363        );
17364
17365        // Structural guard (Task-2 review finding): the Op::Scan node's
17366        // inputs MUST end with [.., body_new_carry, body_y] in that
17367        // order — base_map_hash recurses into the last two inputs to
17368        // hash the body, so a reordering would silently hash the wrong
17369        // subgraph. `all` is a View(0) over the producer; its own
17370        // single input is the producer NodeId.
17371        {
17372            let g = graph.read().unwrap();
17373            let producer_id = g.node(all.id()).inputs[0];
17374            let producer_inputs = &g.node(producer_id).inputs;
17375            assert_eq!(
17376                producer_inputs[producer_inputs.len() - 2],
17377                nc.id(),
17378                "Op::Scan inputs[len-2] must be body_new_carry",
17379            );
17380            assert_eq!(
17381                producer_inputs[producer_inputs.len() - 1],
17382                by.id(),
17383                "Op::Scan inputs[len-1] must be body_y",
17384            );
17385        }
17386
17387        let fin = init
17388            .scan(&[], &[], &nc, &by, bound, ScanEmit::Final)
17389            .expect("scan Final");
17390        assert_eq!(fin.shape().dims(), &[2], "emit=Final -> carry shape");
17391        let _ = hole;
17392    }
17393
17394    #[test]
17395    fn scan_builder_rejects_zero_bound() {
17396        use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17397        use fuel_ir::{DType, Shape};
17398        use std::sync::{Arc, RwLock};
17399        let graph = Arc::new(RwLock::new(Graph::new()));
17400        let cs = Shape::from_dims(&[1]);
17401        let (carry, new_carry, body_y) = {
17402            let mut g = graph.write().unwrap();
17403            let carry = g.push(Node {
17404                op: Op::Const,
17405                inputs: vec![],
17406                shape: cs.clone(),
17407                dtype: DType::F32,
17408            });
17409            let hole = g.push(Node {
17410                op: Op::ScanPlaceholder {
17411                    role: ScanRole::Carry,
17412                    index: 0,
17413                },
17414                inputs: vec![],
17415                shape: cs.clone(),
17416                dtype: DType::F32,
17417            });
17418            let nc = g.push(Node {
17419                op: Op::MulScalar(2.0),
17420                inputs: vec![hole],
17421                shape: cs.clone(),
17422                dtype: DType::F32,
17423            });
17424            (carry, nc, nc)
17425        };
17426        let t = |id| NodeHandle {
17427            graph: graph.clone(),
17428            id,
17429        };
17430        let r = t(carry).scan(&[], &[], &t(new_carry), &t(body_y), 0, ScanEmit::All);
17431        assert!(r.is_err(), "bound == 0 must be a typed Err, not a panic");
17432    }
17433
17434    /// Task 5 (C6): every "opt-in" classifier/dispatch site over `Op` must
17435    /// treat the new `Op::Scan` / `Op::ScanPlaceholder` variants via its
17436    /// existing safe-conservative wildcard/allow-list — no site should need
17437    /// a bespoke Scan arm in Phase 1. This is a regression LOCK, not a
17438    /// born-red test: every assertion here is expected to pass immediately
17439    /// because the wildcards already exist; a red assertion means that site
17440    /// silently mishandles Scan and needs a conservative arm added.
17441    ///
17442    /// Also confirms reachability: `Op::Scan`'s body lives in its own
17443    /// `inputs` (like `Op::Branch`'s arms), so the ordinary input-closure
17444    /// walk (`topo_order_multi`) sees body nodes for free — no
17445    /// `effective_roots` / `live_set` edit is needed.
17446    #[test]
17447    fn scan_opt_in_sites_are_safe_defaults() {
17448        use crate::{Graph, Node, Op, ScanEmit, ScanRole};
17449        use fuel_ir::{DType, Shape};
17450        let scan = Op::Scan {
17451            n_carries: 1,
17452            n_xs: 0,
17453            bound: 2,
17454            emit: ScanEmit::All,
17455            early_exit: None,
17456        };
17457        let hole = Op::ScanPlaceholder {
17458            role: ScanRole::Carry,
17459            index: 0,
17460        };
17461        // Classifier defaults.
17462        assert_eq!(scan.destructive_input(), None);
17463        assert_eq!(hole.destructive_input(), None);
17464        assert!(!scan.is_view_op());
17465        assert!(!hole.is_view_op());
17466        assert_eq!(
17467            crate::infer_storage_class(&scan),
17468            crate::StorageClass::Transient
17469        );
17470        assert_eq!(crate::jit::op_to_tag(&scan), None);
17471        // Reachability: build a graph with an Op::Scan whose body references a hole;
17472        // the hole (a body node) is reachable from the Scan via inputs, no seeding.
17473        let mut g = Graph::new();
17474        let s = Shape::from_dims(&[1]);
17475        let carry = g.push(Node {
17476            op: Op::Const,
17477            inputs: vec![],
17478            shape: s.clone(),
17479            dtype: DType::F32,
17480        });
17481        let h = g.push(Node {
17482            op: hole.clone(),
17483            inputs: vec![],
17484            shape: s.clone(),
17485            dtype: DType::F32,
17486        });
17487        let nc = g.push(Node {
17488            op: Op::MulScalar(2.0),
17489            inputs: vec![h],
17490            shape: s.clone(),
17491            dtype: DType::F32,
17492        });
17493        let sc = g.push(Node {
17494            op: scan.clone(),
17495            inputs: vec![carry, nc, nc],
17496            shape: Shape::from_dims(&[2, 1]),
17497            dtype: DType::F32,
17498        });
17499        let reachable = crate::topo_order_multi(&g, &[sc]);
17500        assert!(
17501            reachable.contains(&nc) && reachable.contains(&h),
17502            "body nodes must be reachable from Op::Scan via inputs (no effective_roots edit needed)"
17503        );
17504    }
17505}