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}
166
167impl QuantType {
168 /// Bytes per quantization block. Mirrors `std::mem::size_of::<BlockQ*>()`.
169 pub fn bytes_per_block(self) -> usize {
170 match self {
171 QuantType::Q4_0 => 18,
172 QuantType::Q4_1 => 20,
173 QuantType::Q5_0 => 22,
174 QuantType::Q5_1 => 24,
175 QuantType::Q8_0 => 34,
176 QuantType::Q8_1 => 36,
177 QuantType::Q2K => 84,
178 QuantType::Q3K => 110,
179 QuantType::Q4_K_M => 144,
180 QuantType::Q5K => 176,
181 QuantType::Q6K => 210,
182 }
183 }
184 /// Elements per quantization block.
185 pub fn elements_per_block(self) -> usize {
186 match self {
187 QuantType::Q4_0
188 | QuantType::Q4_1
189 | QuantType::Q5_0
190 | QuantType::Q5_1
191 | QuantType::Q8_0
192 | QuantType::Q8_1 => 32,
193 QuantType::Q2K
194 | QuantType::Q3K
195 | QuantType::Q4_K_M
196 | QuantType::Q5K
197 | QuantType::Q6K => 256,
198 }
199 }
200}
201
202/// Fill mode for [`Op::Pad`]. Only [`PadMode::Constant`] is
203/// implemented in the v1 cut; the other variants are accepted at
204/// the IR level so the enum is forward-stable, but the executor
205/// returns a clean error until they ship.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub enum PadMode {
208 /// Fill padded slots with the constant `value` parameter on
209 /// the [`Op::Pad`] variant.
210 Constant,
211 /// Reflect input around the padded edges (without repeating the
212 /// edge value). Not yet implemented.
213 Reflect,
214 /// Repeat the edge value into the padded region. Not yet
215 /// implemented.
216 Replicate,
217}
218
219/// The closed enum of operations a graph node can represent.
220///
221/// This is the API contract between the graph layer and every backend.
222/// Adding a new op means (1) adding a variant here, (2) teaching every
223/// backend how to execute it, and (3) teaching the reference backend how
224/// to compute its textbook answer.
225// EXHAUSTIVE-BY-DESIGN: `Op` is the CLOSED graph vocabulary; `OpKind`
226// (fuel-ir/src/dispatch.rs) is the deliberately-`#[non_exhaustive]` EXTENSIBLE
227// dispatch key. This marker makes that split — currently stated only in the doc
228// above — explicit and machine-checkable. The forcing functions are in-crate and
229// exhaustive: `op_short_name` (below) and the autograd `backward` match; adding a
230// variant fails to compile until both get an arm, which is the intended
231// enforcement (a new op with no gradient rule must not compile silently). Because
232// those live in fuel-graph, `-p fuel-graph` DOES catch a variant-add here (unlike
233// Scalar/DType, whose exhaustive consumers are cross-crate) — but do NOT add
234// `#[non_exhaustive]`: it would falsely advertise Op as open to external
235// consumers, contradicting the "teach every backend" contract. Downstream
236// dispatch/cost/telemetry consumers legitimately PARTIAL-match Op with sound
237// defaults (`None`/`Err`/skip); execution is gated by `op_to_op_kind` returning
238// `None`, so a new op is never silently mis-executed — that is why a plain
239// wildcard is correct THERE and forbidden in the two forcing functions above.
240// A THIRD in-crate forcing function joined the two above (GAP-076):
241// `destructive_input` (this file) is now exhaustive as well — a new primitive
242// must classify itself there (destructive → `Some(idx)`, otherwise `None`), and
243// a new *fused* op declares destructiveness as a mandatory `FusedOpEntry` field
244// that `Op::destructive_input` reads via `default_registry()`. The old
245// `_ => None` there silently read a new destructive op as non-destructive and
246// dropped its scheduler ordering edges (a data race); it is gone. See GAP-049
247// and GAP-076.
248#[derive(Debug, Clone, PartialEq)]
249pub enum Op {
250 // --- leaves ---
251 /// A concrete constant tensor — a leaf with no input nodes. The
252 /// realized bytes live in the graph's `storage_map` slot for this
253 /// node, populated at construction time. The executor's slot-first
254 /// dispatch returns the slot's `Arc<RwLock<Storage>>` directly.
255 /// (Phase 7.5 work item G2 retired the host-side `ConstData`
256 /// payload — the slot is the sole source of bytes.)
257 Const,
258
259 /// Position-index generator — a leaf (no inputs) producing the 1-D
260 /// `F32` sequence `[0.0, 1.0, …, (len-1) as f32]` of shape `[len]`.
261 /// The integer-valued positions are exact in `f32` for any realistic
262 /// sequence length (`< 2^24`). Reshaped + broadcast, it builds the
263 /// row/column indices that express causal / sliding-window masks and
264 /// alibi position biases (e.g. in FlashAttn's decomposition), so those
265 /// ops can lower to primitives instead of being opaque. Non-differentiable
266 /// (a constant generator; backward drops gradient like `Op::Const`).
267 Iota { len: usize },
268
269 // --- element-wise binary ---
270 /// Element-wise addition.
271 Add,
272 /// Element-wise subtraction (`a - b`).
273 Sub,
274 /// Element-wise multiplication.
275 Mul,
276 /// Element-wise division (`a / b`).
277 Div,
278
279 // --- element-wise unary ---
280 /// Element-wise negation (`-x`).
281 Neg,
282 /// Element-wise square (`x * x`).
283 Sqr,
284 /// Element-wise square root.
285 Sqrt,
286 /// Element-wise exponential (`e^x`).
287 Exp,
288 /// Element-wise natural logarithm.
289 Log,
290 /// Element-wise sine.
291 Sin,
292 /// Element-wise cosine.
293 Cos,
294 /// Element-wise hyperbolic tangent.
295 Tanh,
296 /// Element-wise logistic sigmoid.
297 Sigmoid,
298 /// SiLU activation (x · sigmoid(x)), also called Swish.
299 Silu,
300 /// GELU activation (tanh approximation).
301 GeluTanh,
302 /// Rectified linear unit (`max(0, x)`), element-wise.
303 Relu,
304 /// Heaviside step function: `1` where `x > 0`, `0` otherwise. Serves
305 /// as the derivative of `Relu` and as a building block for other
306 /// comparison-based gradients.
307 Step,
308 /// Element-wise reciprocal (`1 / x`). On `x = 0` the IEEE-754 result
309 /// is `±inf`; the kernel matches the obvious `1.0 / x` expression
310 /// rather than treating the input as an error.
311 Recip,
312 /// Element-wise absolute value (`|x|`).
313 Abs,
314
315 // --- in-place elementwise unary (Phase 1 of the in-place ops
316 // infrastructure landed 2026-05-30; see
317 // `docs/session-prompts/in-place-ops-infrastructure.md`) ---
318 //
319 // Each variant mutates input 0 in place; output aliases input 0.
320 // Pinned to run after every non-destructive reader of input 0 by
321 // `opt::derive_ordering` via the `destructive_input() -> Some(0)`
322 // contract. Backward integration deferred to Phase 4 (the
323 // mutation-safety pass auto-clones tape-tracked inputs).
324 /// In-place Relu: `x = max(0, x)`. Same semantics as `Op::Relu`,
325 /// mutates input 0. Not yet wired through autograd.
326 ReluInplace,
327 /// In-place Silu: `x = x * sigmoid(x)`. Same semantics as
328 /// `Op::Silu`, mutates input 0. Not yet wired through autograd.
329 SiluInplace,
330 /// In-place GeluTanh (tanh approximation): mutates input 0 with the
331 /// same formula as `Op::GeluTanh`. Not yet wired through autograd.
332 GeluTanhInplace,
333 /// In-place Tanh: mutates input 0. Same semantics as `Op::Tanh`.
334 /// Not yet wired through autograd.
335 TanhInplace,
336 /// In-place Sigmoid: mutates input 0. Same semantics as
337 /// `Op::Sigmoid`. Not yet wired through autograd.
338 SigmoidInplace,
339
340 // --- in-place elementwise unary, dtype expansion + op family
341 // expansion shipped 2026-05-30. Same `destructive_input() ->
342 // Some(0)` contract as the 5 above; backward emitters mirror
343 // the non-inplace cousin (chain-rule formulas relying on
344 // Phase 4a view-aware ordering for pre-mutation reads of x).
345 /// In-place Neg: `x = -x`. Same semantics as `Op::Neg`.
346 NegInplace,
347 /// In-place Abs: `x = |x|`. Same semantics as `Op::Abs`.
348 AbsInplace,
349 /// In-place Sqr: `x = x²`. Same semantics as `Op::Sqr`.
350 SqrInplace,
351 /// In-place Sqrt: `x = √x`. Same semantics as `Op::Sqrt`.
352 SqrtInplace,
353 /// In-place Rsqrt: `x = 1/√x`. Same semantics as `Op::Rsqrt`.
354 RsqrtInplace,
355 /// In-place Recip: `x = 1/x`. Same semantics as `Op::Recip`.
356 RecipInplace,
357 /// In-place Exp: `x = exp(x)`. Same semantics as `Op::Exp`.
358 ExpInplace,
359 /// In-place Log: `x = ln(x)`. Same semantics as `Op::Log`.
360 LogInplace,
361 /// In-place Sin: `x = sin(x)`. Same semantics as `Op::Sin`.
362 SinInplace,
363 /// In-place Cos: `x = cos(x)`. Same semantics as `Op::Cos`.
364 CosInplace,
365 /// In-place Sign: `x = sign(x)`. Same semantics as `Op::Sign`.
366 /// Backward drops gradient (mirrors `Op::Sign`).
367 SignInplace,
368 /// In-place Floor: `x = ⌊x⌋`. Same semantics as `Op::Floor`.
369 /// Backward drops gradient (mirrors `Op::Floor`).
370 FloorInplace,
371 /// In-place Ceil: `x = ⌈x⌉`. Same semantics as `Op::Ceil`.
372 /// Backward drops gradient (mirrors `Op::Ceil`).
373 CeilInplace,
374 /// In-place Round: `x = round(x)`. Same semantics as `Op::Round`.
375 /// Backward drops gradient (mirrors `Op::Round`).
376 RoundInplace,
377 /// In-place Erf: `x = erf(x)`. Same semantics as `Op::Erf`.
378 ErfInplace,
379 /// In-place exact-GeLU: `x = 0.5 · x · (1 + erf(x/√2))`. Same
380 /// semantics as `Op::Gelu`.
381 GeluInplace,
382 /// In-place clamp: `x = clamp(x, min, max)`. Same semantics as
383 /// `Op::Clamp`. Backward gates the upstream by `(x ≥ min) ∧
384 /// (x ≤ max)` (mirrors Op::Clamp).
385 ClampInplace { min: f64, max: f64 },
386 /// In-place integer-power: `x = x.powi(exp)`. Same semantics as
387 /// `Op::PowI`. Backward emits `exp · upstream · x.powi(exp-1)`
388 /// (mirrors Op::PowI).
389 PowIInplace(i32),
390
391 // --- element-wise comparison (output is Bool mask) ---
392 /// Element-wise equality (`a == b`) producing a `Bool` mask: `1`
393 /// where the inputs are equal, `0` otherwise. Both operands must
394 /// share dtype and shape. NaN follows IEEE-754 (`NaN == NaN` is
395 /// false). Output dtype is always `Bool`, regardless of input dtype
396 /// — the binding-table key is `[T, T, Bool]`.
397 ///
398 /// Non-differentiable: backward returns `None` for both inputs
399 /// (registered via [`crate::grad::NoGradientBinaryRule`]).
400 Equal,
401 /// Element-wise inequality (`a != b`) producing a `Bool` mask: `1`
402 /// where unequal, `0` otherwise. Same shape/dtype contract as
403 /// [`Op::Equal`]. NaN follows IEEE-754 (`NaN != NaN` is true →
404 /// `1`). Non-differentiable.
405 Ne,
406 /// Element-wise strictly-less (`a < b`) producing a `Bool` mask: `1`
407 /// where lhs is strictly less than rhs, `0` otherwise. Same
408 /// shape/dtype contract as [`Op::Equal`]. NaN-on-either-side is
409 /// always `0` (IEEE-754 unordered comparison). Non-differentiable.
410 Lt,
411 /// Element-wise less-or-equal (`a <= b`) producing a `Bool` mask.
412 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
413 /// is always `0`. Non-differentiable.
414 Le,
415 /// Element-wise strictly-greater (`a > b`) producing a `Bool` mask.
416 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
417 /// is always `0`. Non-differentiable.
418 Gt,
419 /// Element-wise greater-or-equal (`a >= b`) producing a `Bool` mask.
420 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
421 /// is always `0`. Non-differentiable. Final variant of the
422 /// comparison family (`Equal`, `Ne`, `Lt`, `Le`, `Gt`, `Ge`).
423 Ge,
424
425 // --- rounding family (non-differentiable) ---
426 /// Element-wise floor (`⌊x⌋`). Same dtype as input. Backward is
427 /// the zero distribution almost everywhere; gradient is dropped
428 /// silently (treated like `Op::Step`'s no-grad backward).
429 Floor,
430 /// Element-wise ceiling (`⌈x⌉`). Same dtype as input. Backward
431 /// drops gradient (mirrors [`Op::Floor`]).
432 Ceil,
433 /// Element-wise round-to-nearest with **banker's rounding**
434 /// (round-half-to-even, IEEE 754 roundeven). 0.5 → 0, 1.5 → 2,
435 /// 2.5 → 2 (NOT 3), 3.5 → 4. Matches NumPy/PyTorch defaults and
436 /// differs from C99 `round()` (half-away-from-zero) at exact ties.
437 /// Backward drops gradient (mirrors [`Op::Floor`]).
438 Round,
439 /// Element-wise sign (`-1` / `0` / `1`). `sign(0) = 0` by
440 /// subgradient convention (same convention `Op::Abs`'s backward
441 /// uses). Same dtype as input. Backward drops gradient (zero
442 /// almost everywhere).
443 Sign,
444 /// Element-wise Gauss error function (`erf(x)`). Same dtype as
445 /// input. Differentiable: `d/dx erf(x) = (2/√π) * exp(-x²)`.
446 /// Backward emitted via existing primitives (Sqr → Neg → Exp →
447 /// MulScalar(2/√π) → Mul(upstream, .)).
448 Erf,
449 /// Element-wise GELU activation, **exact erf formulation**:
450 /// `0.5 * x * (1 + erf(x/√2))`. Distinct from [`Op::GeluTanh`]
451 /// (tanh approximation, faster but slightly less accurate).
452 /// Differentiable; backward decomposes into the standard-normal
453 /// CDF + `x * φ(x)` (PDF) chain via primitives.
454 Gelu,
455 /// Element-wise binary power: `out = pow(a, b)` with real `b`.
456 /// Both inputs share dtype `T` and shape. Distinct from
457 /// [`Op::PowI`] (scalar `i32` exponent). Backward:
458 /// d/da pow(a,b) = b * pow(a, b-1)
459 /// d/db pow(a,b) = pow(a,b) * ln(a)
460 /// NaN follows IEEE-754 (`pow(-2, 0.5) = NaN`); ln of negative `a`
461 /// in the d/db term yields NaN at those positions.
462 Pow,
463 /// Element-wise reciprocal square root: `out = 1 / sqrt(x)`.
464 /// Same dtype as input. Distinct from `Sqrt` followed by `Recip`
465 /// (one op instead of two — saves a kernel launch and matches the
466 /// RMSNorm shape `x * rsqrt(mean(x²)+eps)`). Backward:
467 /// d/dx (x^(-1/2)) = -0.5 * x^(-3/2) = -0.5 * y³
468 /// where `y = 1/sqrt(x)` is the forward output (so the chain
469 /// reuses the forward node and never touches `x` directly —
470 /// safe near x=0).
471 Rsqrt,
472 /// Element-wise remainder, **PyTorch convention**:
473 /// `out = a - floor(a / b) * b`. The result has the sign of the
474 /// divisor (matches `torch.remainder`). Distinct from C99 fmod
475 /// (sign of dividend) and `f32::rem_euclid` (always non-negative).
476 /// Backward:
477 /// d/da = 1
478 /// d/db = -floor(a/b)
479 Rem,
480 /// Reverse the order of elements along `dim`. Materializing op
481 /// (not a view) — `Layout`'s strides are `usize` so the
482 /// negative-stride view path isn't representable. Backward is
483 /// `Flip { dim }` itself (involutive).
484 Flip { dim: usize },
485 /// Cyclic shift along `dim` by `shift` positions (positive
486 /// shifts move elements to higher indices, wrapping around).
487 /// Materializing op. Backward is `Roll { dim, -shift }`.
488 Roll { dim: usize, shift: i64 },
489 /// Running cumulative sum along `dim`. Same shape as input.
490 /// Backward: reverse cumsum, expressed as `Flip → CumSum → Flip`
491 /// on the same dim using existing primitives.
492 CumSum { dim: usize },
493 /// Upper triangular: keep `x[..., i, j]` when `j >= i + diagonal`,
494 /// zero otherwise. Operates on the last two dims; leading dims
495 /// are batched. `diagonal` selects which diagonal is the cutoff
496 /// (0 = main diagonal, positive = above, negative = below).
497 /// Same shape as input. Backward is `Triu { diagonal }` itself
498 /// (linear mask; gradient passes through kept positions).
499 Triu { diagonal: i64 },
500 /// Lower triangular: keep `x[..., i, j]` when `j <= i + diagonal`,
501 /// zero otherwise. Operates on the last two dims; leading dims
502 /// are batched. `diagonal` selects which diagonal is the cutoff
503 /// (0 = main diagonal, positive = above, negative = below). The
504 /// canonical causal-attention mask is `tril(diagonal = 0)`.
505 /// Same shape as input. Backward is `Tril { diagonal }` itself.
506 Tril { diagonal: i64 },
507 /// Numerically-stable log-softmax along the last dimension:
508 /// `y_i = x_i - max_j(x_j) - log(sum_j exp(x_j - max_j(x_j)))`.
509 /// Same shape as input. Used in NLL / cross-entropy loss where
510 /// the explicit `log(softmax(x))` decomposition risks
511 /// over/underflow. Backward: see [`Op::LogSoftmaxLastDimBackward`].
512 LogSoftmaxLastDim,
513 /// MaskedFill: `out = where(mask != 0, value, x)`. Inputs:
514 /// `(x, mask)` where `mask` is U8 (any nonzero counts as "fill").
515 /// `value` is a scalar of the same dtype as `x`, stored on the
516 /// op. Output shape == x shape (mask must broadcast to x but the
517 /// simple-shape case requires identical shapes today). Backward
518 /// passes the upstream gradient through `x` at positions where
519 /// `mask == 0`, and contributes zero to `mask` (U8 anyway).
520 MaskedFill { value: Scalar },
521 /// Backward helper for [`Op::Pad`]. Single input is the upstream
522 /// gradient (shape == padded forward output shape); output is the
523 /// gradient with respect to the original input (shape ==
524 /// `in_shape`). Mode determines accumulation behavior:
525 /// - Constant: gradient at padded slots is dropped; the unpadded
526 /// region is the input gradient.
527 /// - Reflect / Replicate: gradient accumulates from output
528 /// positions that map back to each input position via the
529 /// forward index function.
530 ///
531 /// Carries `in_shape` so the kernel can size the output tensor
532 /// (Op output shape isn't enough — Op::Pad's output shape
533 /// derivation needs reversing).
534 PadBackward {
535 in_shape: Shape,
536 padding: Vec<(usize, usize)>,
537 mode: PadMode,
538 },
539
540 /// Multi-dim Pad: per-axis `(before, after)` extends each
541 /// dimension. Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
542 /// `mode` selects the fill behavior; `value` is the fill
543 /// constant for [`PadMode::Constant`] (ignored otherwise — see
544 /// the variant docs for those modes).
545 ///
546 /// Multi-dim shape is the form PyTorch's `F.pad` exposes — a
547 /// single call covers e.g. "pad an image by 1 px on every side"
548 /// (`padding = [(0,0), (0,0), (1,1), (1,1)]` for `[N,C,H,W]`).
549 /// Single-dim is just the special case `padding[i] = (0,0)`
550 /// everywhere except one axis.
551 ///
552 /// Only Constant mode is fully implemented in v1. Reflect /
553 /// Replicate are accepted at the IR level but the executor
554 /// returns a clean "not yet implemented" error.
555 ///
556 /// Backward (Constant): slice along each padded axis to drop
557 /// the padded regions, restoring the input shape.
558 Pad {
559 padding: Vec<(usize, usize)>,
560 mode: PadMode,
561 value: f64,
562 },
563
564 // --- ternary select ---
565 /// Ternary select: `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
566 /// Inputs `(cond, a, b)`: `cond` is `U8` (typically the output of
567 /// a comparison op), `a` and `b` share dtype `T` and shape with
568 /// `cond`. Output dtype = `T`, shape = `cond.shape()`.
569 ///
570 /// Differentiable through `a` and `b` (gradient flows only to
571 /// the picked positions); `cond` is non-differentiable. Backward
572 /// rule expressed via `Op::Cast` + scalar arithmetic on existing
573 /// primitives, registered in [`crate::grad::WhereRule`].
574 Where,
575
576 // --- linear algebra and shape ---
577 /// Rank-2 matrix multiply.
578 MatMul,
579 /// Rank-2 transpose.
580 Transpose,
581 /// N-dimensional permutation. The parameter is the new axis order:
582 /// `out.shape[i] = in.shape[axes[i]]`. For a rank-3 input `[a, b, c]`
583 /// with `axes = [2, 0, 1]`, output shape is `[c, a, b]`. The axes
584 /// vector must be a permutation of `0..rank`.
585 Permute(Vec<usize>),
586
587 // --- dtype, shape, and broadcasting ---
588 /// Convert a tensor to a different dtype. The target dtype is carried
589 /// on the op itself; the source dtype is whatever the input node's
590 /// dtype is.
591 Cast(DType),
592 /// Broadcast a tensor to a larger shape. The input shape must be
593 /// broadcast-compatible with the target (NumPy rules). Used directly
594 /// by user code and as the backward rule for `SumAll`, `MeanAll`,
595 /// and axis reductions.
596 BroadcastTo(Shape),
597 /// Reshape a tensor to a new shape with the same element count. Data
598 /// is unchanged; only the shape metadata is replaced. Serves as the
599 /// general building block for arbitrary shape changes;
600 /// see [`Op::Unsqueeze`] for the metadata-only-view variant that
601 /// inserts a size-1 dim without ever materializing.
602 Reshape(Shape),
603 /// Materialize a contiguous copy of the input. Output shape and
604 /// dtype match the input; only the layout changes (strides become
605 /// row-major, start_offset becomes 0). Zero-cost when the input
606 /// is already contiguous + zero-offset — the executor adopts the
607 /// input's Storage Arc unchanged in that case.
608 ///
609 /// First-class IR concern so the optimizer (Phase 2.2) can insert
610 /// layout-fixups before kernels that don't advertise
611 /// `crate::KernelCaps::strided_input` without overloading
612 /// [`Op::Reshape`]'s "change shape" semantics. The executor
613 /// compiles this to the same `WorkItemKind::ContiguizeOf` arm
614 /// `Op::Reshape` uses; the only difference is that
615 /// `Op::Contiguize`'s output shape equals its input shape, so
616 /// the executor's element-count sanity check is trivial.
617 Contiguize,
618 /// Insert a size-1 dimension at position `dim` (range `0..=rank`,
619 /// where `dim == rank` appends to the end). Strictly more efficient
620 /// than [`Op::Reshape`] for the size-1-insertion case: this is a
621 /// metadata-only view op that shares bytes with its input via the
622 /// Layout side-table, so it preserves any upstream
623 /// strided/transposed/broadcast layout instead of triggering an
624 /// auto-Contiguize.
625 Unsqueeze { dim: usize },
626 /// Drop a size-1 dimension at position `dim` (range `0..rank`).
627 /// Inverse of [`Op::Unsqueeze`]; metadata-only view that shares
628 /// bytes with its input via the Layout side-table. Panics at build
629 /// time if the dim's size isn't 1 (mirrors Unsqueeze's bounds
630 /// check — graph-builder validation, not runtime).
631 Squeeze { dim: usize },
632 /// Sum-reduce a tensor to a smaller shape by summing along any dims
633 /// where the source was broadcast against the target. This is the
634 /// backward rule for `BroadcastTo` and is symmetric with it: both ops
635 /// are each other's gradient. For a source shape `[2, 3, 4]` being
636 /// reduced to `[3, 4]`, the sum is along dim 0; for `[2, 3, 4]` to
637 /// `[2, 1, 4]`, the sum is along dim 1 while keeping the dim.
638 ReduceSumTo(Shape),
639 /// Max-reduce a tensor to a smaller shape, the maximum-symmetric
640 /// counterpart of [`Op::ReduceSumTo`]. The target shape must be
641 /// broadcast-compatible into the source: along any axis where the
642 /// padded target is 1 (or absent), the input is reduced via max;
643 /// other axes carry through. Used by lowering rules (notably
644 /// SoftmaxLastDim's max-subtract step) and as the keepdim form of
645 /// per-axis max reductions.
646 ///
647 /// Backward through max-selection routes the upstream gradient
648 /// only to the argmax position, which requires holding onto the
649 /// original input and recomputing the argmax. PR 3.5 ships this
650 /// op without a backward rule (panics cleanly on `.backward()`,
651 /// matching `Op::ArgMaxDim`'s precedent); add the backward when a
652 /// real consumer needs it.
653 ReduceMaxTo(Shape),
654
655 // --- reductions to a scalar ---
656 /// Sum of every element, producing a rank-0 tensor.
657 SumAll,
658 /// Maximum of every element, producing a rank-0 tensor.
659 MaxAll,
660 /// Minimum of every element, producing a rank-0 tensor.
661 MinAll,
662 /// Arithmetic mean of every element, producing a rank-0 tensor.
663 MeanAll,
664
665 // --- reductions along one dimension ---
666 /// Sum along the given dim; the reduced dim is removed from the output.
667 SumDim(usize),
668 /// Max along the given dim; the reduced dim is removed from the output.
669 MaxDim(usize),
670 /// Min along the given dim; the reduced dim is removed from the output.
671 MinDim(usize),
672 /// Mean along the given dim; the reduced dim is removed from the output.
673 MeanDim(usize),
674
675 // --- compositions ---
676 //
677 // Phase 7.6 step 5 (2026-05-11): the per-fused-op primitive variants
678 // (SoftmaxLastDim, LayerNormLastDim { eps }, RmsNormLastDim { eps },
679 // Rope, Conv2D { … }, FusedLinear) plus the four backward-helper
680 // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
681 // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
682 // The closed primitive set no longer carries fused-op concepts;
683 // every fused op flows through `Op::Fused(FusedOpId, FusedOpParams)`.
684 // See `docs/fused-op-registry.md` for the migration record.
685
686 // Phase 7.6 step 5 (continued, 2026-05-11): `QMatMul {
687 // quant_type, k, n }` dropped — flows through
688 // `Op::Fused(QMATMUL, FusedOpParams::QMatMul { … })`.
689
690 // --- backward helpers ---
691 //
692 // Phase 7.6 step 5 (2026-05-11): the four migrated backward-helper
693 // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
694 // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
695 // They flow through `Op::Fused(FusedOpId, FusedOpParams)` per the
696 // registry split. LogSoftmaxLastDimBackward is the only remaining
697 // backward-helper primitive variant — its forward primitive
698 // (`Op::LogSoftmaxLastDim`, not in scope for step 5) hasn't migrated
699 // to the registry yet, so the backward stays primitive too.
700 //
701 /// LogSoftmax-last-dim backward. Inputs: `(forward_log_softmax_output,
702 /// upstream)`. Output: the gradient of the input to log-softmax.
703 /// Formula: `g - exp(y) * sum(g, last_dim, keepdim=true)` where
704 /// `y` is the forward log-softmax output and `g` is the upstream
705 /// gradient. Independent of `Op::SoftmaxLastDimBackward` because
706 /// the closed-form rule uses `exp(y) = softmax(x)` directly, not
707 /// the upstream-times-softmax composition.
708 LogSoftmaxLastDimBackward,
709
710 // --- integer-producing reductions ---
711 //
712 // These reduce a float tensor along one dim and emit a U32 tensor of
713 // indices. Non-differentiable — they exist for classification
714 // prediction and similar discrete workloads, not as part of any
715 // training graph. Backward panics cleanly if a user builds these
716 // inside a graph they then differentiate.
717 /// Index of the maximum along `dim`. Output: U32 with the reduced
718 /// dim removed.
719 ArgMaxDim(usize),
720 /// Index of the minimum along `dim`. Output: U32 with the reduced
721 /// dim removed.
722 ArgMinDim(usize),
723
724 // --- shape manipulation ---
725 /// Concatenate two tensors along `dim`. Both must have the same rank,
726 /// same dtype, and equal sizes in every dim except `dim`.
727 Concat { dim: usize },
728 /// Slice (narrow) a tensor along `dim`: take elements `[start, start+len)`.
729 /// Output shape: same as input but with `dim` shrunk to `len`.
730 Slice {
731 dim: usize,
732 start: usize,
733 len: usize,
734 },
735
736 // --- scalar-by-tensor ops ---
737 //
738 // These exist to avoid building a full-shape const just to add or
739 // multiply by a constant. Stored as f64 on the op and converted to
740 // the target dtype at realize time.
741 /// Add a scalar to every element.
742 AddScalar(f64),
743 /// Multiply every element by a scalar.
744 MulScalar(f64),
745 /// Raise every element to an integer power via repeated multiplication.
746 /// Works without an extra `log`/`exp` pair so it's numerically clean
747 /// for small integer exponents like squaring or cubing.
748 PowI(i32),
749 /// Clamp every element to the inclusive range `[min, max]`.
750 Clamp { min: f64, max: f64 },
751
752 // --- element-wise max/min between two tensors ---
753 /// Element-wise maximum of two tensors with matching shape.
754 Maximum,
755 /// Element-wise minimum of two tensors with matching shape.
756 Minimum,
757
758 // --- indexing ops ---
759 //
760 // These take a "data" tensor (floats) as their first input and an
761 // "index" tensor (integer) as their second input. The executor
762 // reads both operands from the cache, dispatches on the data
763 // tensor's dtype for the output, and uses the index tensor as-is.
764 /// Index-select along a single dimension with a 1-D index vector.
765 /// Output shape: same as input, but with `dim` replaced by
766 /// `indices.elem_count()`.
767 IndexSelect { dim: usize },
768 /// N-dimensional gather along `dim`. Output shape matches the index
769 /// tensor's shape. `out[..., k, ...] = data[..., indices[..., k, ...], ...]`
770 /// with `dim` being the position where the index value substitutes
771 /// for the output coordinate.
772 Gather { dim: usize },
773 /// Index-add: the backward of `IndexSelect`. Takes a base tensor,
774 /// a 1-D `U32` index vector, and a src tensor, and adds src to base
775 /// at the indexed positions along `dim`. `out[..., indices[i], ...] +=
776 /// src[..., i, ...]`. Non-indexed positions of base are copied
777 /// through unchanged. Works functionally (returns a new tensor).
778 IndexAdd { dim: usize },
779 /// Scatter-add: the backward of `Gather`. Takes a base tensor, an
780 /// N-D `U32` index tensor matching the src shape, and a src tensor,
781 /// and accumulates src values into base at positions given by
782 /// substituting `indices` at position `dim`. `out[p with dim ←
783 /// indices[p]] += src[p]`.
784 ScatterAdd { dim: usize },
785
786 /// Data-determined nonzero-index extraction — the keystone primitive
787 /// for **data-dependent dynamic shapes** (SSM autoregressive decode,
788 /// MoE sparse dispatch, MLA compressed-KV). Given an input value
789 /// tensor, produces the flat indices of its nonzero elements over a
790 /// **fixed-capacity buffer** plus the true runtime count, using the
791 /// multi-output bundle mechanism ([12-multi-output]):
792 ///
793 /// - slot 0 (primary): `indices`, shape `[capacity]`, dtype `U32`,
794 /// where `capacity = input.elem_count()` (the static worst-case
795 /// bound). The first `count` entries are the flat (row-major)
796 /// indices of the input's nonzero elements in ascending order; the
797 /// tail `[count..capacity]` is unspecified padding.
798 /// - slot 1: `count`, shape `[1]`, dtype `U32` — the number of
799 /// nonzero elements found.
800 ///
801 /// "Nonzero" means `!= 0` in the input dtype's arithmetic (a `0.0`
802 /// float, an all-zero integer). The runtime `count` is published into
803 /// the per-pass [`SymEnv`](fuel_ir::SymEnv) under `count_sym` by the
804 /// executor *after* this op realizes, so downstream ops consume it as
805 /// a [`DynScalar::Sym`] / dynamic [`Extent`](fuel_ir::shape::Extent) —
806 /// the same host-scalar-extent pattern the KV-cache `cached_len`
807 /// uses. This is the **first op whose output length is determined by
808 /// its input data**, not by build-time shapes (the [`fuel_ir::symbol::SymEnv`] bind is
809 /// the one net-new realize-time seam). Primitive (in the base map by
810 /// construction — no `decompose`). Non-differentiable: discrete
811 /// indices, backward drops gradient like `Op::Gather`'s index path.
812 NonZeroIndices { count_sym: SymId },
813
814 // --- 2-D convolution + fused linear ---
815 //
816 // Phase 7.6 step 5 (2026-05-11): `Conv2D { stride, padding, groups }`
817 // and `FusedLinear` have been dropped — both flow through
818 // `Op::Fused(FusedOpId, FusedOpParams)` per the registry split.
819 // See `fuel-graph/src/registry/{conv2d,fused_linear}.rs` for the
820 // current entry shapes.
821
822 // Phase 7.6 step 5 (continued, 2026-05-11): `FlashAttn`,
823 // `PagedAttn`, and `ConvTranspose2D` dropped — all three flow
824 // through `Op::Fused(<id>, FusedOpParams::<variant>)` per the
825 // registry split. See `fuel-graph/src/registry/{flash_attn,
826 // paged_attn, conv_transpose_2d}.rs`.
827
828 // --- cross-device transfer ---
829 /// Copy the input tensor to a specific device. Source stays
830 /// resident (non-destructive). Source device is implicit from
831 /// `inputs[0]`'s current residency. When source and target
832 /// devices match, the backend is free to turn this into a cheap
833 /// clone; when they differ, the backend must actually transfer
834 /// the data (today: through a host buffer — Phase 3 has no P2P
835 /// fast path yet).
836 ///
837 /// Phase 3 of the unified scheduler work. The scheduler (Phase 4)
838 /// inserts these nodes automatically; users can also construct
839 /// them explicitly via `NodeHandle::copy_to_device`.
840 Copy { target: DeviceLocation },
841
842 /// Release the input tensor's device-resident storage. Produces a
843 /// zero-element marker output (NodeId placeholder for graph
844 /// bookkeeping; no meaningful data). After this op runs, the
845 /// input's device storage is gone; any subsequent reader of the
846 /// input's NodeId must get its data from a different path (a
847 /// sibling Copy output, or re-execution of the producer).
848 ///
849 /// Destructive on `inputs[0]`. Scheduler must pin `Op::Release`
850 /// to run after every other reader of its input via
851 /// [`opt::derive_ordering`].
852 ///
853 /// **Multi-output bundles** (Option C, Session 3): when
854 /// `inputs[0]` is a multi-output producer (its Storage carries a
855 /// [`fuel_ir::storage::OutputView`] bundle), the bundle
856 /// is the single eviction unit — the Release evicts the whole
857 /// bundle, not a single slot. `opt::collect_alias_set` treats
858 /// every `Op::View` of the producer as part of the producer's
859 /// alias set, so `derive_ordering` pins Release after every
860 /// reader of every View; the bundle drops only when the LAST
861 /// View consumer finishes. Op::ViewOwned consumers may run
862 /// freely after Release: their forward memcpy ran before the
863 /// Release fires (data-dep edge), and the resulting standalone
864 /// Storage is independent of the producer's bundle. Per-slot
865 /// eviction (releasing one slot's bytes while another stays
866 /// live) is intentionally a follow-up — v1 keeps the bundle as
867 /// a single unit.
868 Release,
869
870 /// Transfer the input tensor to `target` device, destroying the
871 /// source in the process. Semantically equivalent to
872 /// `Op::Copy { target }` followed by `Op::Release` on the source,
873 /// with the explicit guarantee that backends MAY fast-path the
874 /// fused form as a single transfer (e.g., a zero-copy handoff if
875 /// source and target are the same memory type).
876 ///
877 /// Output is a fresh tensor on `target` with the input's shape
878 /// and dtype. Destructive on `inputs[0]`; the scheduler pins this
879 /// op to run after every non-destructive reader of the source via
880 /// [`opt::derive_ordering`].
881 Move { target: DeviceLocation },
882
883 /// In-place scatter write: copies `inputs[1]`'s bytes into a
884 /// rectangular slab of `inputs[0]`'s storage, defined per-dim by
885 /// `ranges[i] = (start, end)`. After the op runs, `inputs[0]`'s
886 /// bytes inside the slab are replaced; bytes outside the slab are
887 /// untouched.
888 ///
889 /// Shape contract: `inputs[0].rank() == inputs[1].rank() ==
890 /// ranges.len()`. For each axis `i`,
891 /// `inputs[1].dims()[i] == ranges[i].1 - ranges[i].0`, and
892 /// `ranges[i].1 <= inputs[0].dims()[i]`. Dtypes must match.
893 ///
894 /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
895 /// Layout — same shape, same bytes, post-write. Consumers that
896 /// want a sub-extent of the destination compose an explicit
897 /// `Op::Slice` after the write (WriteSlice does not encode
898 /// post-write extents).
899 ///
900 /// Destructive on `inputs[0]` (the destination is consumed; only
901 /// the write op's output NodeId may read its bytes afterward).
902 /// Non-destructive on `inputs[1]`. The scheduler pins this op to
903 /// run after every other reader of the destination via
904 /// [`opt::derive_ordering`].
905 ///
906 /// Phase E.3.2: introduced to back persistent KV-cache writes
907 /// (`InferenceContext` + `KvCache`). Non-differentiable; backward
908 /// panics — KV-cache writes are forward-only.
909 ///
910 /// `dyn_offset` (Phase D symbolic extents): `None` ⇒ fully static
911 /// (`ranges` alone defines the slab — today's behavior). `Some((axis,
912 /// off))` ⇒ the destination start on `axis` is `off.resolve(env)`
913 /// against the per-pass [`fuel_ir::SymEnv`] at realize,
914 /// overriding `ranges[axis].0`; the slab width on that axis stays
915 /// `ranges[axis].1 - ranges[axis].0`. This is the input-determined
916 /// dynamic-offset path (a [`DynScalar`] over the one `SymEnv`),
917 /// distinct from [`Op::WriteSliceRotating`]'s data-determined
918 /// position (a tensor input). It backs the persistent decode
919 /// KV-cache write, whose append offset (`cached_len`) is a per-token
920 /// runtime value over a fixed-capacity buffer, so the graph
921 /// structure stays identical across tokens and the plan is reused.
922 /// Build a node with this set via [`NodeHandle::write_slice_dyn`]; the
923 /// resolved `offset + width` is bounds-checked against the
924 /// destination capacity at realize (a typed error, never a panic).
925 WriteSlice {
926 ranges: Vec<(usize, usize)>,
927 dyn_offset: Option<(usize, DynScalar)>,
928 },
929
930 /// Like [`Op::WriteSlice`] but the `axis` axis wraps modulo
931 /// `modulus`. The dynamic write position comes through `inputs[2]`
932 /// (rank-0 U32); at realize time the kernel computes
933 /// `start = position % modulus` and writes `inputs[1]` into
934 /// `inputs[0]` at the wrapped offset, splitting across the
935 /// boundary if `start + write_len > modulus`.
936 ///
937 /// Inputs:
938 /// - `inputs[0]`: destination tensor (the rotating buffer). Shape
939 /// on `axis` is the full storage extent — typically equal to
940 /// `modulus`.
941 /// - `inputs[1]`: source slice. Shape on non-rotating axes is the
942 /// slab in `ranges`; shape on `axis` is the write length.
943 /// - `inputs[2]`: dynamic write position, rank-0 `U32`. Wrapped
944 /// modulo `modulus` inside the kernel — callers pass the
945 /// monotonic logical position (token index, etc.).
946 ///
947 /// `ranges` describes the destination slab on every axis. For the
948 /// rotating axis `axis`, `ranges[axis].0` is ignored (start is
949 /// dynamic) and `ranges[axis].1 - ranges[axis].0` must equal
950 /// `inputs[1].dims()[axis]` (the write length). For other axes
951 /// the same shape contract as `Op::WriteSlice` applies.
952 ///
953 /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
954 /// Layout, post-write. Destructive on `inputs[0]`; scheduled like
955 /// `Op::WriteSlice`.
956 ///
957 /// Phase C of the eager-NodeHandle retirement program. Backs
958 /// sliding-window KV caches (Mistral / Phi-3 sliding-window /
959 /// sliding-window Qwen). Non-differentiable; backward panics.
960 WriteSliceRotating {
961 axis: usize,
962 modulus: usize,
963 ranges: Vec<(usize, usize)>,
964 },
965
966 /// Like [`Op::WriteSlice`] but the start offset on `axis` is a
967 /// **device-resident** scalar read from `inputs[2]` (rank-0 `I64`)
968 /// at kernel-launch time — NOT host-resolved. This is the CUDA-
969 /// graph-capturable append: under capture, the offset buffer is
970 /// updated by a per-token fixed-address H2D memcpy before each
971 /// replay, so the captured graph is reused across decode steps
972 /// while the write lands at the live position. No modulo wrap
973 /// (unlike [`Op::WriteSliceRotating`]); the offset is the raw
974 /// start (`cached_len`).
975 ///
976 /// Inputs:
977 /// - `inputs[0]`: destination tensor (the fixed-capacity buffer).
978 /// - `inputs[1]`: source slab. Shape on non-`axis` axes is the slab
979 /// in `ranges`; shape on `axis` is the write width.
980 /// - `inputs[2]`: device offset, rank-0 `I64` — the start on `axis`.
981 /// Overrides `ranges[axis].0` (which is a placeholder ignored by
982 /// the kernel).
983 ///
984 /// `ranges` describes the destination slab on every axis. For the
985 /// dynamic axis, `ranges[axis].0` is ignored (start is device-
986 /// resident) and `ranges[axis].1 - ranges[axis].0` must equal
987 /// `inputs[1].dims()[axis]` (the write width). For other axes the
988 /// same shape contract as [`Op::WriteSlice`] applies.
989 ///
990 /// **Bounds are the caller's contract**: the kernel reads the start
991 /// device-side and does NOT clamp (clamping would perturb the index
992 /// math vs the static path). `offset + width <= dest_dims[axis]`
993 /// must hold — guaranteed by the caller sizing the buffer's
994 /// capacity (`DecodeSession` sizes `max_seq`).
995 ///
996 /// Output adopts `inputs[0]`'s Storage Arc + Layout, post-write.
997 /// Destructive on `inputs[0]`; scheduled like `Op::WriteSlice`.
998 /// Non-differentiable; backward panics.
999 ///
1000 /// CapturedRun (the decode-latency lever, 2026-07): the device-
1001 /// resident-offset WriteSlice is form-B of baracuda's
1002 /// `write_slice_*_doff` launchers.
1003 WriteSliceDoff {
1004 axis: usize,
1005 ranges: Vec<(usize, usize)>,
1006 },
1007
1008 /// Allocate a fresh, zero-initialized Storage of the node's shape +
1009 /// dtype on `target`. Zero inputs — `Op::Alloc` is a *source* op
1010 /// like [`Op::Const`], but its bytes are computed (zeros) rather
1011 /// than seeded from the host.
1012 ///
1013 /// Bridge-retirement Phase 3a (post-9c). Replaces the per-device-
1014 /// location match in `fuel-tensor::inference_context::alloc_zeroed_on`
1015 /// with a graph-level node the optimizer can see + the executor's
1016 /// `WorkItemKind::Alloc` arm dispatches per-backend.
1017 ///
1018 /// **Device-handle requirement**: the executor's Alloc arm derives
1019 /// the per-backend handle (e.g. `&CudaDevice`, `&Arc<VulkanBackend>`)
1020 /// by searching the input cache for any Storage already on
1021 /// `target`'s backend. Callers must seed the cache with at least
1022 /// one such storage before realizing an Op::Alloc on a non-CPU
1023 /// target. `fuel-tensor::pipelined_bridge::device_seed_storage` is
1024 /// the canonical seeder.
1025 Alloc { target: DeviceLocation },
1026
1027 /// Fill the input tensor's bytes with zero, in place. Aliases
1028 /// `inputs[0]`'s Storage Arc as the output (same Storage; the
1029 /// bytes are mutated). Destructive on `inputs[0]` — readers of
1030 /// the input's NodeId after this op see post-fill bytes; new
1031 /// readers should use this op's NodeId.
1032 ///
1033 /// Bridge-retirement Phase 3a follow-up. Paired with
1034 /// [`Op::Alloc`] to give the architecturally clean "alloc uninit +
1035 /// explicit zero" pipeline. Backends with native device-side
1036 /// fills (CUDA `cuMemsetD8Async`, Vulkan `vkCmdFillBuffer`)
1037 /// dispatch through their kernels; CPU does an
1038 /// `Arc::make_mut`-style in-place memset.
1039 ///
1040 /// Future extension: an `Op::Fill { value: u8 }` (or `Scalar`)
1041 /// for non-zero patterns. ZeroFill is the only variant today
1042 /// because zero is the only init pattern any current caller
1043 /// needs.
1044 ZeroFill,
1045
1046 /// Phase 7.6 single-arm delegate to the open
1047 /// [`crate::registry::FusedOpRegistry`]. The id selects which
1048 /// fused op (SoftmaxLastDim, RmsNormLastDim, FlashAttn, ...) and
1049 /// the params carry per-instance data. The registry's metadata
1050 /// side (decompose, backward identity, shape/dtype rules) lives in
1051 /// `fuel-graph::registry`; the kernel side (per-backend `KernelRef`
1052 /// + cost + precision) lives in `fuel-storage::fused`.
1053 ///
1054 /// Adding a new fused op is one registry entry plus one kernel
1055 /// function per backend that supports it — no new `Op` variant.
1056 /// Step 3 of Phase 7.6 migrates SoftmaxLastDim through this arm
1057 /// as the proof of concept.
1058 Fused(FusedOpId, FusedOpParams),
1059
1060 /// Project one logical output out of a multi-output producer node.
1061 /// The producer's realized [`Storage`] carries a
1062 /// [`fuel_ir::storage::OutputView`] side-table; this op
1063 /// reads slot `slot` of that side-table and exposes its
1064 /// dtype/shape/layout as the View node's output.
1065 ///
1066 /// Single input (the multi-output producer). Output shares the
1067 /// producer's `Arc<RwLock<Storage>>` — zero bytes copied. The
1068 /// bundle stays alive as long as any View consumer (or the
1069 /// original producer handle) holds a clone.
1070 ///
1071 /// At graph-build time, the View's shape + dtype + layout come
1072 /// from the producer's slot specs recorded via
1073 /// [`Graph::set_output_views`]; building a `View { slot }` over a
1074 /// producer that hasn't declared slot specs is a typed error
1075 /// surfaced by the View-emitting builder helper. The bundle's
1076 /// per-slot dtype is independent of the producer node's own
1077 /// `Node::dtype` (which is the bundle's primary/slot-0 dtype).
1078 ///
1079 /// Backward (see `fuel-graph::grad`): the per-slot upstream
1080 /// gradient is scattered into a zero-filled bundle of the
1081 /// producer's overall byte shape; the producer's own backward
1082 /// rule then sees a "bundle gradient" as its upstream. Until a
1083 /// real multi-output op author exists (Session 2), the backward
1084 /// rule emits an [`Op::Const`] zero of the producer's primary
1085 /// shape — the scatter-into-slot primitive lands alongside the
1086 /// first differentiable multi-output op.
1087 View { slot: u32 },
1088
1089 /// Like [`Op::View`], but copies the slot's bytes into a fresh
1090 /// standalone Storage. Costs one allocation + one slot-sized
1091 /// memcpy; the producer's bundle Arc can drop as soon as every
1092 /// outstanding `Op::View` over the same producer also drops.
1093 ///
1094 /// The planner promotes a `View` to `ViewOwned` when a slot's
1095 /// liveness substantially outlasts the rest of the bundle (the
1096 /// classic case: Mamba's `last_state` slot retained across an
1097 /// autoregressive step while `y` is consumed immediately). v1
1098 /// emits the same dispatch shape as `Op::Copy` — backend-side it's
1099 /// `Copy` with byte offset + length pulled from the slot spec.
1100 ///
1101 /// Same shape/dtype/layout inference path as `View`; same backward
1102 /// shape too (the forward already paid the copy).
1103 ViewOwned { slot: u32 },
1104
1105 /// Multi-output autograd primitive (Option C, item 4). Takes two
1106 /// inputs:
1107 /// - `inputs[0]`: a bundled tensor (typically a zero-bundle)
1108 /// - `inputs[1]`: the slot's gradient
1109 ///
1110 /// Produces a new bundled tensor identical to `inputs[0]` except
1111 /// that slot `slot`'s byte range is overlaid by `inputs[1]`'s
1112 /// bytes. The output is alias-free with respect to `inputs[0]`
1113 /// (a fresh Storage with the new bytes) so multiple
1114 /// `ScatterIntoSlot` operations on the same `bundle_zero` chain
1115 /// sequentially without aliasing pitfalls.
1116 ///
1117 /// Emitted by `Op::View` / `Op::ViewOwned` backward rules: each
1118 /// View consumer scatters its upstream gradient into a fresh
1119 /// zero-bundle, then the producer's backward receives the
1120 /// composed bundle gradient as its upstream.
1121 ///
1122 /// **Status**: IR-level primitive only in this session. No CPU
1123 /// kernel registration yet. The production multi-output SSM ops
1124 /// (SelectiveScan, SsdChunkScan) are now differentiable via the
1125 /// Op::Scan Phase-2 `lower_scans_for_backward` pre-pass (decompose →
1126 /// `Op::Scan` → `unroll_scan` → node-general autograd), which lowers
1127 /// them to primitives BEFORE the reverse walk — so the autograd
1128 /// differentiates the unrolled `View` projections directly and never
1129 /// reaches a `ScatterIntoSlot` realization on the SSM path.
1130 ScatterIntoSlot { slot: u32 },
1131
1132 /// In-place multi-path (phi/merge) node — the arena representation
1133 /// of the optimized form's divergent-then-reconvergent routes.
1134 ///
1135 /// A `Branch` node's divergent "arms" are encoded in the node's
1136 /// existing `inputs: Vec<NodeId>`: each input is the *exit* of one
1137 /// candidate route, and `reconverge_at` names the explicit node at
1138 /// which those routes merge back into a single value. Because the
1139 /// multi-path structure is an arena fact rather than an overlay, it
1140 /// persists, compacts, graph-walks, and path-filters exactly like
1141 /// any other node; a graph with **zero** `Op::Branch` nodes is
1142 /// exactly today's single-route graph (back-compatible by
1143 /// construction).
1144 ///
1145 /// **Inert until PR-A1.** This variant is the PR-A0 scaffold: the
1146 /// closed `Op` enum carries it and every exhaustive match handles
1147 /// it, but nothing constructs it yet. The `open_branch` /
1148 /// `add_arm` / `finalize_branches` builders (with build-time
1149 /// validation: reconverge must descend from the diverge point, arms
1150 /// internally disjoint, cast-to-uniform at reconverge) land in
1151 /// PR-A1. Until then, accessors return a constant ("branch") and
1152 /// fallible paths (shape inference, autograd, lowering) return a
1153 /// descriptive `Err` rather than panicking.
1154 Branch { reconverge_at: NodeId },
1155
1156 /// Fuel's first sub-graph-carrying primitive: a bounded `lax.scan`-shaped
1157 /// recurrence `scan(body, init_carry, xs, consts) -> (final_carry, ys)`.
1158 ///
1159 /// The body is encoded in this node's own `inputs`, exactly like
1160 /// [`Op::Branch`]'s arms. Node layout:
1161 /// `inputs = [ init_carry_0..init_carry_{n_carries-1}, xs_0..xs_{n_xs-1},
1162 /// consts..., body_new_carry_0..body_new_carry_{n_carries-1}, body_y ]`
1163 /// — the two body-exit NodeIds are the LAST two inputs, so `base_map_hash`,
1164 /// `topo_order_multi`, and reachability see the body for free. The body
1165 /// references `Op::ScanPlaceholder{Carry,0}` for the per-step carry and
1166 /// `Op::ScanPlaceholder{Elem,i}` for the per-step slice of `xs[i]`; consts
1167 /// are referenced by real NodeId. `n_carries` carries are threaded; the
1168 /// body references `ScanPlaceholder{Carry,k}` for carry `k` (GAP-303 —
1169 /// `n_carries = 1` is the v1 single-carry model).
1170 ///
1171 /// An optimization/verification-time node: it never reaches the executor
1172 /// un-lowered (the SSM decompose emits it, but the executor dispatches the
1173 /// fused op to its kernel; `unroll_scan` materializes primitives on demand
1174 /// for the verify oracle / kernel-absent fallback). No `LoweringRule`
1175 /// matches it — it is a terminal in the base map, which is correct: it IS
1176 /// the primitive. Always a 2-slot bundle (slot 0 = stacked `ys`, slot 1 =
1177 /// final carry). `early_exit` is Phase-2 (see [`ScanPredicate`]).
1178 Scan {
1179 /// How many recurrent carries this scan threads. Symmetric with
1180 /// `n_xs`: the carry NODES live in `inputs` (a positional block, see
1181 /// the layout above); this field is only their COUNT, exactly as
1182 /// `n_xs` is only the count of the `xs` block.
1183 ///
1184 /// GAP-303: `1` reproduces the v1 single-carry model exactly.
1185 n_carries: usize,
1186 n_xs: usize,
1187 bound: usize,
1188 emit: ScanEmit,
1189 early_exit: Option<ScanPredicate>,
1190 },
1191
1192 /// Inert body-hole leaf for [`Op::Scan`] (no inputs). Substituted by
1193 /// `unroll_scan` per step. Never directly realized.
1194 ScanPlaceholder { role: ScanRole, index: usize },
1195}
1196
1197/// What a [`Op::Scan`] emits. `All` stacks the per-step `body_y` over the
1198/// bound (slot 0); `Final` returns only the final carry (slot 1). The op
1199/// always produces the 2-slot bundle; `emit` selects the builder's default
1200/// projection. (`Op::Reduce` is `Op::Scan { emit: Final }` conceptually —
1201/// no separate variant.)
1202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1203pub enum ScanEmit {
1204 All,
1205 Final,
1206}
1207
1208/// Which body hole a [`Op::ScanPlaceholder`] stands in for. `Carry` is the
1209/// per-step recurrent carry (always index 0 in v1's single-carry model);
1210/// `Elem` is the per-step slice of `xs[index]`.
1211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1212pub enum ScanRole {
1213 Carry,
1214 Elem,
1215}
1216
1217/// Phase-1 placeholder for [`Op::Scan`]'s `early_exit` field. The FIELD is
1218/// defined now so the enum shape is final (one `03-ir` MAJOR bump); the
1219/// data-dependent early-exit MECHANISM is Phase 2. It is never `Some` on any
1220/// live Phase-1 path; if a realize/lowering path sees `Some`, that path
1221/// returns a clear `Err` (a surfaced Phase-2 gap), never a panic.
1222#[derive(Debug, Clone, PartialEq)]
1223pub struct ScanPredicate;
1224
1225impl Op {
1226 /// Index into `inputs` that this op destroys on execution. `None`
1227 /// means the op is non-destructive — every input remains readable
1228 /// after the op completes. Destructive ops need the scheduler to
1229 /// pin them to run after all other readers of the destroyed input,
1230 /// via ordering edges derived by [`opt::derive_ordering`].
1231 pub fn destructive_input(&self) -> Option<usize> {
1232 match self {
1233 // --- Destructive: the op writes through input 0 in place, so every
1234 // reader of input 0 (and its view-aliases) must be scheduled BEFORE
1235 // it (`opt::derive_ordering`). ---
1236 Op::Release
1237 | Op::Move { .. }
1238 | Op::WriteSlice { .. }
1239 | Op::WriteSliceRotating { .. }
1240 | Op::WriteSliceDoff { .. }
1241 | Op::ZeroFill
1242 | Op::ReluInplace
1243 | Op::SiluInplace
1244 | Op::GeluTanhInplace
1245 | Op::TanhInplace
1246 | Op::SigmoidInplace
1247 | Op::NegInplace
1248 | Op::AbsInplace
1249 | Op::SqrInplace
1250 | Op::SqrtInplace
1251 | Op::RsqrtInplace
1252 | Op::RecipInplace
1253 | Op::ExpInplace
1254 | Op::LogInplace
1255 | Op::SinInplace
1256 | Op::CosInplace
1257 | Op::SignInplace
1258 | Op::FloorInplace
1259 | Op::CeilInplace
1260 | Op::RoundInplace
1261 | Op::ErfInplace
1262 | Op::GeluInplace
1263 | Op::ClampInplace { .. }
1264 | Op::PowIInplace(_) => Some(0),
1265
1266 // --- Fused ops declare destructiveness as a MANDATORY
1267 // `FusedOpEntry::destructive_input` field (registry-declared, not
1268 // hardcoded here), so the fact lives with the thing and cannot drift.
1269 // Total by construction: a compile-time fused op cannot be registered
1270 // without the field; a runtime-registered fused id is not in the
1271 // compile-time registry and its region is a functional recipe (the
1272 // PatternNode grammar cannot express a destructive op), so `entry` is
1273 // `None` there and the op is non-destructive. GAP-076. ---
1274 Op::Fused(id, _) => crate::registry::default_registry()
1275 .entry(*id)
1276 .and_then(|e| e.destructive_input),
1277
1278 // --- Non-destructive primitives, listed EXHAUSTIVELY (no wildcard)
1279 // so adding an `Op` variant fails to compile here until it is
1280 // classified (`Op` is EXHAUSTIVE-BY-DESIGN — see the marker on
1281 // `enum Op`). A silent `_ => None` was the GAP-076 hazard: a future
1282 // destructive op would read as non-destructive and the scheduler
1283 // would drop its ordering edges — an intermittent data race that
1284 // points nowhere near this function. ---
1285 Op::Const
1286 | Op::Iota { .. }
1287 | Op::Add
1288 | Op::Sub
1289 | Op::Mul
1290 | Op::Div
1291 | Op::Neg
1292 | Op::Sqr
1293 | Op::Sqrt
1294 | Op::Exp
1295 | Op::Log
1296 | Op::Sin
1297 | Op::Cos
1298 | Op::Tanh
1299 | Op::Sigmoid
1300 | Op::Silu
1301 | Op::GeluTanh
1302 | Op::Relu
1303 | Op::Step
1304 | Op::Recip
1305 | Op::Abs
1306 | Op::Equal
1307 | Op::Ne
1308 | Op::Lt
1309 | Op::Le
1310 | Op::Gt
1311 | Op::Ge
1312 | Op::Where
1313 | Op::Floor
1314 | Op::Ceil
1315 | Op::Round
1316 | Op::Sign
1317 | Op::Erf
1318 | Op::Gelu
1319 | Op::Pow
1320 | Op::Rsqrt
1321 | Op::Rem
1322 | Op::Flip { .. }
1323 | Op::Roll { .. }
1324 | Op::CumSum { .. }
1325 | Op::Triu { .. }
1326 | Op::Tril { .. }
1327 | Op::LogSoftmaxLastDim
1328 | Op::MaskedFill { .. }
1329 | Op::Pad { .. }
1330 | Op::PadBackward { .. }
1331 | Op::MatMul
1332 | Op::Transpose
1333 | Op::Permute(_)
1334 | Op::Cast(_)
1335 | Op::BroadcastTo(_)
1336 | Op::Reshape(_)
1337 | Op::Contiguize
1338 | Op::Unsqueeze { .. }
1339 | Op::Squeeze { .. }
1340 | Op::ReduceSumTo(_)
1341 | Op::ReduceMaxTo(_)
1342 | Op::SumAll
1343 | Op::MaxAll
1344 | Op::MinAll
1345 | Op::MeanAll
1346 | Op::SumDim(_)
1347 | Op::MaxDim(_)
1348 | Op::MinDim(_)
1349 | Op::MeanDim(_)
1350 | Op::LogSoftmaxLastDimBackward
1351 | Op::ArgMaxDim(_)
1352 | Op::ArgMinDim(_)
1353 | Op::Concat { .. }
1354 | Op::Slice { .. }
1355 | Op::AddScalar(_)
1356 | Op::MulScalar(_)
1357 | Op::PowI(_)
1358 | Op::Clamp { .. }
1359 | Op::Maximum
1360 | Op::Minimum
1361 | Op::IndexSelect { .. }
1362 | Op::Gather { .. }
1363 | Op::IndexAdd { .. }
1364 | Op::ScatterAdd { .. }
1365 | Op::NonZeroIndices { .. }
1366 | Op::Copy { .. }
1367 | Op::Alloc { .. }
1368 | Op::View { .. }
1369 | Op::ViewOwned { .. }
1370 | Op::ScatterIntoSlot { .. }
1371 | Op::Branch { .. }
1372 | Op::Scan { .. }
1373 | Op::ScanPlaceholder { .. } => None,
1374 }
1375 }
1376
1377 /// Short human-readable name for this op — used by executor error
1378 /// messages to identify the offending graph node without spilling
1379 /// all of `Debug`'s field contents. Keeps panic messages one-liner-
1380 /// friendly while still telling you which kind of op blew up.
1381 pub fn short_name(&self) -> &'static str {
1382 op_short_name(self)
1383 }
1384
1385 /// Whether this op is a metadata-only view: its output shares bytes
1386 /// with its single input, reinterpreting them through new strides
1387 /// and/or offset. Executors realize these without allocating new
1388 /// storage — they wrap the input's Storage in a fresh Layout.
1389 ///
1390 /// Note that `Op::Reshape` is *not* a view op. Reshape produces
1391 /// contiguous output: zero-copy when its input is contiguous, but
1392 /// it materializes via auto-Contiguize when the input is strided.
1393 /// The other shape-altering ops in this set are always view-shaped
1394 /// regardless of the input layout.
1395 pub fn is_view_op(&self) -> bool {
1396 matches!(
1397 self,
1398 Op::Transpose
1399 | Op::Permute(_)
1400 | Op::BroadcastTo(_)
1401 | Op::Slice { .. }
1402 | Op::Unsqueeze { .. }
1403 | Op::Squeeze { .. }
1404 | Op::Flip { .. }
1405 )
1406 }
1407}
1408
1409/// Compute the output [`Layout`] of a metadata-only view op from its
1410/// input layout + the op variant. Returns `Err` if the op variant
1411/// isn't a view op (caller's contract — typically guarded by
1412/// [`Op::is_view_op`]).
1413///
1414/// Used by [`Graph::push`] to auto-populate the layout side-table for
1415/// view-op nodes at construction time, and by lowering rules in
1416/// [`opt`] that emit view-op nodes and need to populate the side-table
1417/// for them. The compiler reads the resulting layouts via
1418/// [`Graph::layout`] without re-deriving.
1419pub fn derive_view_output_layout(op: &Op, input_layout: &Layout) -> Result<Layout, fuel_ir::Error> {
1420 match op {
1421 Op::Transpose => {
1422 let rank = input_layout.shape().rank();
1423 if rank < 2 {
1424 return Err(fuel_ir::Error::Msg(format!(
1425 "Op::Transpose requires rank >= 2, input rank is {rank}",
1426 ))
1427 .bt());
1428 }
1429 input_layout.transpose(rank - 2, rank - 1)
1430 }
1431 Op::Permute(axes) => input_layout.permute(axes),
1432 Op::BroadcastTo(target_shape) => input_layout.broadcast_as(target_shape.clone()),
1433 Op::Slice { dim, start, len } => input_layout.narrow(*dim, *start, *len),
1434 Op::Unsqueeze { dim } => input_layout.unsqueeze(*dim),
1435 Op::Squeeze { dim } => input_layout.squeeze(*dim),
1436 Op::Flip { dim } => input_layout.flip(*dim),
1437 other => Err(fuel_ir::Error::Msg(format!(
1438 "derive_view_output_layout called with non-view op {other:?}",
1439 ))
1440 .bt()),
1441 }
1442}
1443
1444fn op_short_name(op: &Op) -> &'static str {
1445 match op {
1446 Op::Const => "Const",
1447 Op::Iota { .. } => "Iota",
1448 Op::Add => "Add",
1449 Op::Sub => "Sub",
1450 Op::Mul => "Mul",
1451 Op::Div => "Div",
1452 Op::Neg => "Neg",
1453 Op::Sqr => "Sqr",
1454 Op::Sqrt => "Sqrt",
1455 Op::Exp => "Exp",
1456 Op::Log => "Log",
1457 Op::Sin => "Sin",
1458 Op::Cos => "Cos",
1459 Op::Tanh => "Tanh",
1460 Op::Sigmoid => "Sigmoid",
1461 Op::Silu => "Silu",
1462 Op::GeluTanh => "GeluTanh",
1463 Op::Relu => "Relu",
1464 Op::Step => "Step",
1465 Op::Recip => "Recip",
1466 Op::Abs => "Abs",
1467 Op::ReluInplace => "ReluInplace",
1468 Op::SiluInplace => "SiluInplace",
1469 Op::GeluTanhInplace => "GeluTanhInplace",
1470 Op::TanhInplace => "TanhInplace",
1471 Op::SigmoidInplace => "SigmoidInplace",
1472 Op::NegInplace => "NegInplace",
1473 Op::AbsInplace => "AbsInplace",
1474 Op::SqrInplace => "SqrInplace",
1475 Op::SqrtInplace => "SqrtInplace",
1476 Op::RsqrtInplace => "RsqrtInplace",
1477 Op::RecipInplace => "RecipInplace",
1478 Op::ExpInplace => "ExpInplace",
1479 Op::LogInplace => "LogInplace",
1480 Op::SinInplace => "SinInplace",
1481 Op::CosInplace => "CosInplace",
1482 Op::SignInplace => "SignInplace",
1483 Op::FloorInplace => "FloorInplace",
1484 Op::CeilInplace => "CeilInplace",
1485 Op::RoundInplace => "RoundInplace",
1486 Op::ErfInplace => "ErfInplace",
1487 Op::GeluInplace => "GeluInplace",
1488 Op::ClampInplace { .. } => "ClampInplace",
1489 Op::PowIInplace(_) => "PowIInplace",
1490 Op::Equal => "Equal",
1491 Op::Ne => "Ne",
1492 Op::Lt => "Lt",
1493 Op::Le => "Le",
1494 Op::Gt => "Gt",
1495 Op::Ge => "Ge",
1496 Op::Where => "Where",
1497 Op::Floor => "Floor",
1498 Op::Ceil => "Ceil",
1499 Op::Round => "Round",
1500 Op::Sign => "Sign",
1501 Op::Erf => "Erf",
1502 Op::Gelu => "Gelu",
1503 Op::Pow => "Pow",
1504 Op::Rsqrt => "Rsqrt",
1505 Op::Rem => "Rem",
1506 Op::Flip { .. } => "Flip",
1507 Op::Roll { .. } => "Roll",
1508 Op::CumSum { .. } => "CumSum",
1509 Op::Triu { .. } => "Triu",
1510 Op::Tril { .. } => "Tril",
1511 Op::LogSoftmaxLastDim => "LogSoftmaxLastDim",
1512 Op::MaskedFill { .. } => "MaskedFill",
1513 Op::Pad { .. } => "Pad",
1514 Op::PadBackward { .. } => "PadBackward",
1515 Op::MatMul => "MatMul",
1516 Op::Transpose => "Transpose",
1517 Op::Permute(_) => "Permute",
1518 Op::Cast(_) => "Cast",
1519 Op::BroadcastTo(_) => "BroadcastTo",
1520 Op::Reshape(_) => "Reshape",
1521 Op::Contiguize => "Contiguize",
1522 Op::Unsqueeze { .. } => "Unsqueeze",
1523 Op::Squeeze { .. } => "Squeeze",
1524 Op::ReduceSumTo(_) => "ReduceSumTo",
1525 Op::ReduceMaxTo(_) => "ReduceMaxTo",
1526 Op::SumAll => "SumAll",
1527 Op::MaxAll => "MaxAll",
1528 Op::MinAll => "MinAll",
1529 Op::MeanAll => "MeanAll",
1530 Op::SumDim(_) => "SumDim",
1531 Op::MaxDim(_) => "MaxDim",
1532 Op::MinDim(_) => "MinDim",
1533 Op::MeanDim(_) => "MeanDim",
1534 Op::LogSoftmaxLastDimBackward => "LogSoftmaxLastDimBackward",
1535 Op::ArgMaxDim(_) => "ArgMaxDim",
1536 Op::ArgMinDim(_) => "ArgMinDim",
1537 Op::Concat { .. } => "Concat",
1538 Op::Slice { .. } => "Slice",
1539 Op::AddScalar(_) => "AddScalar",
1540 Op::MulScalar(_) => "MulScalar",
1541 Op::PowI(_) => "PowI",
1542 Op::Clamp { .. } => "Clamp",
1543 Op::Maximum => "Maximum",
1544 Op::Minimum => "Minimum",
1545 Op::IndexSelect { .. } => "IndexSelect",
1546 Op::Gather { .. } => "Gather",
1547 Op::IndexAdd { .. } => "IndexAdd",
1548 Op::ScatterAdd { .. } => "ScatterAdd",
1549 Op::NonZeroIndices { .. } => "NonZeroIndices",
1550 Op::Copy { .. } => "Copy",
1551 Op::Release => "Release",
1552 Op::Move { .. } => "Move",
1553 Op::WriteSlice { .. } => "WriteSlice",
1554 Op::WriteSliceRotating { .. } => "WriteSliceRotating",
1555 Op::WriteSliceDoff { .. } => "WriteSliceDoff",
1556 Op::Alloc { .. } => "Alloc",
1557 Op::ZeroFill => "ZeroFill",
1558 // Phase 7.6: registry-extended fused ops. Step 3 wires per-id
1559 // names through a static lookup; until then, all fused ops
1560 // share one short name. Distinguishing in error messages is
1561 // future work — `id` is in the Debug repr.
1562 Op::Fused(_, _) => "Fused",
1563 Op::View { .. } => "View",
1564 Op::ViewOwned { .. } => "ViewOwned",
1565 Op::ScatterIntoSlot { .. } => "ScatterIntoSlot",
1566 // PR-A0 inert scaffold (the multi-path phi/merge node).
1567 Op::Branch { .. } => "Branch",
1568 Op::Scan { .. } => "Scan",
1569 Op::ScanPlaceholder { .. } => "ScanPlaceholder",
1570 }
1571}
1572
1573/// G2 helper: element count of a `HostBuffer`. Used by NodeHandle's
1574/// constructors to validate that the supplied data matches the
1575/// declared shape's `elem_count` before allocating Storage.
1576fn host_buffer_elem_count(buf: &fuel_ir::HostBuffer) -> usize {
1577 use fuel_ir::HostBuffer;
1578 match buf {
1579 HostBuffer::F32(v) => v.len(),
1580 HostBuffer::F64(v) => v.len(),
1581 HostBuffer::BF16(v) => v.len(),
1582 HostBuffer::F16(v) => v.len(),
1583 HostBuffer::U8(v) => v.len(),
1584 HostBuffer::U32(v) => v.len(),
1585 HostBuffer::I64(v) => v.len(),
1586 other => panic!(
1587 "NodeHandle::from_*: unsupported host-buffer dtype {:?}",
1588 other.dtype(),
1589 ),
1590 }
1591}
1592
1593/// A single node in the graph: an operation and the IDs of its inputs.
1594/// The node also caches its output shape and dtype so downstream builders
1595/// can validate without walking back through the graph.
1596#[derive(Debug, Clone)]
1597pub struct Node {
1598 pub op: Op,
1599 pub inputs: Vec<NodeId>,
1600 pub shape: Shape,
1601 pub dtype: DType,
1602}
1603
1604/// How a node's storage is shared and how long it lives — its **storage
1605/// class** ([03-ir §"Storage classes and sessions"]). A node is a
1606/// structural fact and does not need storage to exist; when storage *is*
1607/// attached, its class governs sharing and lifetime so one optimized graph
1608/// can serve many concurrent sessions (weights shared, session state
1609/// `SessionId`-keyed, activations per-realize scratch).
1610///
1611/// The class is **inferred from the op** ([`infer_storage_class`]) with an
1612/// **explicit override** recorded in the graph's `storage_class` side-table
1613/// — e.g. KV-cache placeholder `Op::Const`s, which are session state, not
1614/// shared weights.
1615///
1616/// Phase D substrate (PR-D1): the classification is recorded but not yet
1617/// consumed by realize. Session keying (D2) and the persistent decode graph
1618/// (D3–D5) build on it.
1619#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1620pub enum StorageClass {
1621 /// Weights / constants: one storage for the whole model, identical
1622 /// across all sessions; keyed by `NodeId`. The op-inferred default for
1623 /// `Op::Const`.
1624 Shared,
1625 /// Per-session durable buffers (KV-caches + explicit cache-write
1626 /// targets): one storage per session, keyed by `(NodeId, SessionId)`.
1627 /// The op-inferred default for the in-place cache-write ops
1628 /// (`Op::WriteSlice` / `Op::WriteSliceRotating`); KV-cache placeholder
1629 /// `Op::Const`s take it via an explicit override.
1630 SessionState,
1631 /// Activations / scratch: ephemeral, allocated per realize and freed
1632 /// after use; never persisted. The op-inferred default for everything
1633 /// else. A transient value may cross devices mid-realize (a D2D
1634 /// `Op::Copy`) but never crosses to disk.
1635 Transient,
1636}
1637
1638/// The op-inferred storage class for a node, **before** any explicit
1639/// override (see [`StorageClass`] and [`Graph::storage_class`]):
1640/// - `Op::Const` → [`StorageClass::Shared`] (weights);
1641/// - `Op::WriteSlice` / `Op::WriteSliceRotating` → [`StorageClass::SessionState`]
1642/// (they write into a per-session durable buffer);
1643/// - everything else → [`StorageClass::Transient`].
1644pub fn infer_storage_class(op: &Op) -> StorageClass {
1645 match op {
1646 Op::Const => StorageClass::Shared,
1647 Op::WriteSlice { .. } | Op::WriteSliceRotating { .. } | Op::WriteSliceDoff { .. } => {
1648 StorageClass::SessionState
1649 }
1650 _ => StorageClass::Transient,
1651 }
1652}
1653
1654/// The graph arena. Stores every node added during a computation-building
1655/// session. Nodes are append-only and indexed by [`NodeId`].
1656///
1657/// Placement metadata (`DeviceLocation` per node) lives in a side-table
1658/// so existing `Node { ... }` construction sites don't need to be
1659/// modified. This is the Phase-1 shape: placements are opt-in, inert
1660/// hints that the executor may validate but does not yet act on.
1661/// `Default` is implemented **manually** (not derived) so that every graph —
1662/// however it is created — mints a fresh [`GraphId`] from the monotonic
1663/// counter. A derived `Default` would hand out a zeroed id, so two
1664/// `Graph::default()` graphs would claim the same identity and affinity
1665/// diagnostics would report nonsense.
1666#[derive(Debug)]
1667pub struct Graph {
1668 nodes: Vec<Node>,
1669 /// Sparse map of per-node placement hints. Entries are only present
1670 /// when explicitly set via [`Graph::set_placement`]. Absent entries
1671 /// mean "inherit from the executor's default device."
1672 placements: HashMap<NodeId, DeviceLocation>,
1673 /// NodeIds the executor must schedule even when their outputs are
1674 /// unreachable from the user's roots. Populated by graph-mutating
1675 /// rules that emit side-effecting ops (e.g. `Op::Release` for
1676 /// residency eviction). See [`Graph::add_side_effect_root`].
1677 side_effect_roots: Vec<NodeId>,
1678 /// Phase 7.5 work item G: graph-owned realized-storage map.
1679 /// Slots are populated for `Op::Const` leaves at construction
1680 /// time and for non-leaf nodes at realize time. Values are
1681 /// `Arc<RwLock<Storage>>` so consumers (NodeHandle handles, executor
1682 /// caches, residency machinery) share Storage cheaply via Arc
1683 /// clones. Lifetime is tied to the Graph; when the graph drops,
1684 /// any slots not held by external Arc clones are freed.
1685 storage_map: HashMap<NodeId, Arc<RwLock<Storage>>>,
1686 /// Phase 7.5 storage-unification B2: per-node dispatch
1687 /// resolution result. Set by the dispatch resolver (Phase B3+)
1688 /// when DAG construction picks which backend will execute the
1689 /// node's op given its inputs' dtype + residency. Sparse like
1690 /// `placements`: absent entries mean "not yet resolved" and the
1691 /// executor falls back to per-op-eval dispatch (today's
1692 /// behavior). After full migration, every Node has an entry.
1693 ///
1694 /// Note: this is a *side-table*, not a `Node` field, so that
1695 /// existing `Node { ... }` constructors don't need to change
1696 /// during the migration. Mirrors the `placements` pattern.
1697 target_backends: HashMap<NodeId, BackendId>,
1698 /// Phase 7.5 storage-unification — Layout-on-Node side-table.
1699 /// Sparse: every Node has a logical [`Layout`], but for the
1700 /// common case (contiguous result of a kernel) we don't store
1701 /// it explicitly — [`Graph::layout`] returns
1702 /// `Layout::contiguous(node.shape)` as the fallback. Entries
1703 /// are written here exclusively by metadata-only view ops
1704 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1705 /// 0-copy `Op::Reshape`) where the output is a strided view
1706 /// over an upstream node's Storage.
1707 ///
1708 /// Coherence rule: if `layouts[id]` is present, its
1709 /// `shape()` must equal `nodes[id].shape` — Layout adds
1710 /// strides + offset; the visible shape is identical.
1711 layouts: HashMap<NodeId, Layout>,
1712 /// Per-node multi-output side-table. Populated only for nodes
1713 /// whose op produces a bundled [`Storage`] with N>1 logical
1714 /// outputs (Session 1 of the multi-output-nodes design — see
1715 /// [`OutputView`](fuel_ir::storage::OutputView)). `Op::View`
1716 /// and `Op::ViewOwned` builders read this side-table to derive
1717 /// their own output shape/dtype/layout from the producer's
1718 /// declared slot specs.
1719 ///
1720 /// Coherence rule: when present, slot 0's `dtype` must equal the
1721 /// producer node's `Node::dtype` (which the multi-output op's
1722 /// allocator also uses as the inner backend storage's dtype).
1723 /// The producer's `Node::shape` reflects slot 0's logical shape
1724 /// for back-compat with single-output infrastructure; non-primary
1725 /// slots may have unrelated shapes and dtypes.
1726 node_output_views: HashMap<NodeId, Arc<[fuel_ir::storage::OutputView]>>,
1727 /// Per-node **storage-class override** ([`StorageClass`]). Sparse:
1728 /// entries are present only where the class differs from the op-inferred
1729 /// default ([`infer_storage_class`]) — chiefly KV-cache placeholder
1730 /// `Op::Const`s, which are session state, not shared weights.
1731 /// [`Graph::storage_class`] returns the override if present, else the
1732 /// inferred default, so every node has a well-defined class.
1733 /// Phase D substrate (PR-D1); not yet consumed by realize.
1734 storage_class: HashMap<NodeId, StorageClass>,
1735 /// Per-node **data-determined matmul row count** — the sparse-MoE
1736 /// capacity-buffer support. Present only on `Op::MatMul` nodes whose
1737 /// M (row count) is a runtime value: the node's `Node::shape` carries
1738 /// the row **capacity**, and this side-table carries the [`DynScalar`]
1739 /// that resolves (at compile if input-determined, else at execute from
1740 /// the producer-bound `SymEnv`) to how many rows to actually compute.
1741 /// Absent ⇒ a normal, static-M matmul. A side-table (not an `Op::MatMul`
1742 /// field) so the dense-matmul enum + its every match arm stay untouched.
1743 node_matmul_row_count: HashMap<NodeId, DynScalar>,
1744 /// Process-unique identity for this graph, minted at construction.
1745 ///
1746 /// Tensors are **graph-affine**: every binary op requires both operands to
1747 /// live on the same `Graph`, checked by `Arc::ptr_eq`. Pointer identity is
1748 /// the right *check* but a useless thing to *report* — so each graph also
1749 /// carries a small monotonic id, letting an affinity failure say "lhs is on
1750 /// graph #1, rhs on graph #2" instead of only that the two differ. That
1751 /// turns an abstract invariant into an observation the caller can act on:
1752 /// *you made two graphs.*
1753 id: GraphId,
1754}
1755
1756/// Process-unique identifier for a [`Graph`], minted monotonically by
1757/// [`Graph::new`]. Exists so affinity diagnostics can name *which* graphs
1758/// disagree; it is not a stable address, an index, or anything to persist.
1759#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1760pub struct GraphId(u64);
1761
1762impl std::fmt::Display for GraphId {
1763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1764 write!(f, "{}", self.0)
1765 }
1766}
1767
1768/// Monotonic source for [`GraphId`]. Starts at 1 so `#0` never appears and a
1769/// zeroed/defaulted id is visibly wrong.
1770static NEXT_GRAPH_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1771
1772impl Default for Graph {
1773 fn default() -> Self {
1774 Self::new()
1775 }
1776}
1777
1778impl Graph {
1779 /// Create an empty graph.
1780 pub fn new() -> Self {
1781 Self {
1782 id: GraphId(NEXT_GRAPH_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)),
1783 nodes: Vec::new(),
1784 placements: HashMap::new(),
1785 side_effect_roots: Vec::new(),
1786 storage_map: HashMap::new(),
1787 target_backends: HashMap::new(),
1788 layouts: HashMap::new(),
1789 node_output_views: HashMap::new(),
1790 storage_class: HashMap::new(),
1791 node_matmul_row_count: HashMap::new(),
1792 }
1793 }
1794
1795 /// This graph's process-unique [`GraphId`]. Used by affinity diagnostics to
1796 /// name *which* graphs disagree; see [`NodeHandle::graph_id`].
1797 pub fn id(&self) -> GraphId {
1798 self.id
1799 }
1800
1801 /// Look up the resolved target backend for a node, if any has
1802 /// been set. Returns `None` if dispatch resolution hasn't
1803 /// happened yet for this node — common during the migration
1804 /// because old op-builder paths don't call the resolver.
1805 ///
1806 /// Phase 7.5 B2.
1807 pub fn target_backend(&self, id: NodeId) -> Option<BackendId> {
1808 self.target_backends.get(&id).copied()
1809 }
1810
1811 /// Record the resolved target backend for `id`. Set once at DAG
1812 /// construction time (or first-realize time, depending on the
1813 /// dispatch policy chosen in Phase B3). Idempotent: calling
1814 /// twice with the same value is fine; calling twice with
1815 /// different values overwrites.
1816 ///
1817 /// Phase 7.5 B2.
1818 pub fn set_target_backend(&mut self, id: NodeId, backend: BackendId) {
1819 assert!(
1820 id.0 < self.nodes.len(),
1821 "set_target_backend: id out of bounds",
1822 );
1823 self.target_backends.insert(id, backend);
1824 }
1825
1826 /// Number of nodes with a resolved target backend. Mostly for
1827 /// tests and diagnostics.
1828 pub fn target_backend_count(&self) -> usize {
1829 self.target_backends.len()
1830 }
1831
1832 /// The storage class of `id`: the explicit override if one was set via
1833 /// [`Graph::set_storage_class`], else the op-inferred default
1834 /// ([`infer_storage_class`]). Every node has a well-defined class.
1835 ///
1836 /// Phase D substrate (PR-D1).
1837 pub fn storage_class(&self, id: NodeId) -> StorageClass {
1838 if let Some(c) = self.storage_class.get(&id).copied() {
1839 return c;
1840 }
1841 infer_storage_class(&self.nodes[id.0].op)
1842 }
1843
1844 /// Record an explicit storage-class override for `id`, replacing the
1845 /// op-inferred default. Used for nodes whose op does not determine the
1846 /// class — chiefly KV-cache placeholder `Op::Const`s, which are session
1847 /// state rather than shared weights.
1848 ///
1849 /// Phase D substrate (PR-D1).
1850 pub fn set_storage_class(&mut self, id: NodeId, class: StorageClass) {
1851 assert!(
1852 id.0 < self.nodes.len(),
1853 "set_storage_class: id out of bounds",
1854 );
1855 self.storage_class.insert(id, class);
1856 }
1857
1858 /// Whether `id` carries an explicit storage-class override (as opposed
1859 /// to relying on the op-inferred default).
1860 pub fn has_storage_class_override(&self, id: NodeId) -> bool {
1861 self.storage_class.contains_key(&id)
1862 }
1863
1864 /// Number of explicit storage-class overrides. Mostly for tests and
1865 /// diagnostics.
1866 pub fn storage_class_override_count(&self) -> usize {
1867 self.storage_class.len()
1868 }
1869
1870 /// The [`Layout`] associated with `id`. If the side-table has
1871 /// no explicit entry, returns `Layout::contiguous(shape)` —
1872 /// every Node logically has a Layout; the side-table is just
1873 /// the sparse storage for the strided / offset cases.
1874 ///
1875 /// Phase 7.5 storage-unification: metadata-only view ops
1876 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1877 /// 0-copy `Op::Reshape`) populate this side-table during
1878 /// graph construction. Kernel ops produce contiguous results
1879 /// and rely on the fallback.
1880 pub fn layout(&self, id: NodeId) -> Layout {
1881 if let Some(l) = self.layouts.get(&id) {
1882 return l.clone();
1883 }
1884 Layout::contiguous(self.node(id).shape.clone())
1885 }
1886
1887 /// Record an explicit [`Layout`] for `id`. The Layout's
1888 /// `shape()` must equal `nodes[id].shape` — otherwise the
1889 /// graph becomes incoherent (downstream ops were validated
1890 /// against `node.shape`). Panics in `debug_assertions` mode
1891 /// on mismatch; in release the mismatch is silently kept
1892 /// because the alternative would require this method to
1893 /// return `Result`, which would break call ergonomics in
1894 /// graph-construction code.
1895 ///
1896 /// Set this exactly when an op produces a strided / offset
1897 /// view over upstream Storage. For the common case
1898 /// (contiguous kernel output), don't call this at all —
1899 /// [`Graph::layout`] returns `Layout::contiguous(shape)`
1900 /// as the implicit fallback.
1901 pub fn set_layout(&mut self, id: NodeId, layout: Layout) {
1902 assert!(id.0 < self.nodes.len(), "set_layout: id out of bounds");
1903 debug_assert_eq!(
1904 layout.shape(),
1905 &self.nodes[id.0].shape,
1906 "set_layout: Layout shape disagrees with Node shape \
1907 (Layout sets strides/offset, not the visible shape)",
1908 );
1909 self.layouts.insert(id, layout);
1910 }
1911
1912 /// Whether `id` has an explicit Layout entry in the side-table
1913 /// (i.e. it's a strided / offset view; not the default
1914 /// contiguous case).
1915 pub fn has_explicit_layout(&self, id: NodeId) -> bool {
1916 self.layouts.contains_key(&id)
1917 }
1918
1919 /// Number of nodes with an explicit (non-contiguous) Layout.
1920 /// Mostly for tests and diagnostics.
1921 pub fn explicit_layout_count(&self) -> usize {
1922 self.layouts.len()
1923 }
1924
1925 // -------------------------------------------------------------------
1926 // Multi-output side-table (Op::View / Op::ViewOwned)
1927 // -------------------------------------------------------------------
1928
1929 /// Borrow the per-slot output-view specs for `id`, if it's been
1930 /// declared as a multi-output producer. Returns `None` for
1931 /// single-output nodes (the common case).
1932 ///
1933 /// `Op::View` and `Op::ViewOwned` builders read this to derive
1934 /// the slot's shape/dtype/layout at graph-build time.
1935 pub fn output_views(&self, id: NodeId) -> Option<&[fuel_ir::storage::OutputView]> {
1936 self.node_output_views.get(&id).map(|a| a.as_ref())
1937 }
1938
1939 /// Clone the `Arc` handle to `id`'s per-slot output-view specs.
1940 /// Used by the realization path to attach the same bundle metadata
1941 /// to the realized [`Storage`] without copying the slice.
1942 pub fn output_views_arc(&self, id: NodeId) -> Option<Arc<[fuel_ir::storage::OutputView]>> {
1943 self.node_output_views.get(&id).cloned()
1944 }
1945
1946 /// Declare `id` as a multi-output producer with the given per-slot
1947 /// specs. Validates at graph-build time:
1948 /// 1. `id` is in bounds.
1949 /// 2. `views` is non-empty (a "multi-output" node with zero slots
1950 /// is a contract bug — use single-output if there's nothing to
1951 /// project).
1952 /// 3. Slot 0's dtype equals `nodes[id].dtype` (the bundle's
1953 /// primary dtype convention).
1954 /// 4. Slot 0's shape equals `nodes[id].shape` (slot 0 is the
1955 /// "primary" slot whose shape the single-output infrastructure
1956 /// already sees).
1957 /// 5. Each slot's `layout.shape()` equals the slot's `shape`
1958 /// (Layout adds strides/offset; the visible shape is identical).
1959 ///
1960 /// Idempotent on (id, views). Replacing an existing declaration
1961 /// asserts the new specs are byte-identical to the old in debug
1962 /// builds; in release the last write wins (matches the layouts
1963 /// side-table pattern).
1964 pub fn set_output_views(
1965 &mut self,
1966 id: NodeId,
1967 views: Arc<[fuel_ir::storage::OutputView]>,
1968 ) -> Result<(), fuel_ir::Error> {
1969 if id.0 >= self.nodes.len() {
1970 return Err(fuel_ir::Error::Msg(format!(
1971 "set_output_views: NodeId({}) out of bounds (len={})",
1972 id.0,
1973 self.nodes.len(),
1974 ))
1975 .bt());
1976 }
1977 if views.is_empty() {
1978 return Err(fuel_ir::Error::Msg(
1979 "set_output_views: slot list must be non-empty".into(),
1980 )
1981 .bt());
1982 }
1983 let node = &self.nodes[id.0];
1984 let slot0 = &views[0];
1985 if slot0.dtype != node.dtype {
1986 return Err(fuel_ir::Error::Msg(format!(
1987 "set_output_views: slot 0 dtype {:?} disagrees with \
1988 Node::dtype {:?} on Node#{} (slot 0 is the primary; \
1989 dtypes must match)",
1990 slot0.dtype, node.dtype, id.0,
1991 ))
1992 .bt());
1993 }
1994 if slot0.shape != node.shape {
1995 return Err(fuel_ir::Error::Msg(format!(
1996 "set_output_views: slot 0 shape {:?} disagrees with \
1997 Node::shape {:?} on Node#{} (slot 0 is the primary)",
1998 slot0.shape, node.shape, id.0,
1999 ))
2000 .bt());
2001 }
2002 for (i, v) in views.iter().enumerate() {
2003 if v.layout.shape() != &v.shape {
2004 return Err(fuel_ir::Error::Msg(format!(
2005 "set_output_views: slot {i} layout.shape() = {:?} \
2006 disagrees with declared slot shape {:?}",
2007 v.layout.shape(),
2008 v.shape,
2009 ))
2010 .bt());
2011 }
2012 }
2013 self.node_output_views.insert(id, views);
2014 Ok(())
2015 }
2016
2017 /// Whether `id` has been declared as a multi-output producer.
2018 pub fn is_multi_output(&self, id: NodeId) -> bool {
2019 self.node_output_views.contains_key(&id)
2020 }
2021
2022 /// Number of nodes declared as multi-output producers. Mostly for
2023 /// tests and diagnostics.
2024 pub fn multi_output_count(&self) -> usize {
2025 self.node_output_views.len()
2026 }
2027
2028 /// Whether some node in this graph *produces* (binds mid-realize) the
2029 /// runtime value `sym` — i.e. `sym` is **data-determined**, computed by
2030 /// an op during the pass rather than supplied up front. Used to tell a
2031 /// data-determined `DynScalar::Sym` (which is legitimately unbound in
2032 /// the compile-time `SymEnv` and must be resolved at *execute* time)
2033 /// apart from a caller error (a truly-unbound input-determined sym,
2034 /// which must surface as an error at realize). Today the only producer
2035 /// of a data-determined symbol is [`Op::NonZeroIndices`] (its
2036 /// `count_sym`); extend this match as more data-determined producers
2037 /// land.
2038 pub fn binds_data_determined_sym(&self, sym: SymId) -> bool {
2039 self.nodes.iter().any(|n| match &n.op {
2040 Op::NonZeroIndices { count_sym } => *count_sym == sym,
2041 _ => false,
2042 })
2043 }
2044
2045 /// The next data-determined [`SymId`] not yet used by any producer in
2046 /// this graph — one past the max `Op::NonZeroIndices` `count_sym`, or
2047 /// `SymId(0)` if none exist. Lets a builder that emits several
2048 /// data-determined producers (e.g. one `NonZeroIndices` per MoE expert,
2049 /// across several stacked layers on the same graph) allocate
2050 /// non-colliding count syms without threading an external
2051 /// [`fuel_ir::SymGen`]: each call reflects the producers already added,
2052 /// so successive layers claim strictly higher ranges.
2053 ///
2054 /// This covers the data-determined space (the only producers of which
2055 /// are `NonZeroIndices` nodes). A graph that *also* mixes
2056 /// input-determined symbolic extents in the same low sym range should
2057 /// thread a shared `SymGen` instead — those live in a separate
2058 /// compile-time `SymEnv` this scan does not see.
2059 pub fn next_data_determined_sym(&self) -> SymId {
2060 let max = self
2061 .nodes
2062 .iter()
2063 .filter_map(|n| match &n.op {
2064 Op::NonZeroIndices { count_sym } => Some(count_sym.0),
2065 _ => None,
2066 })
2067 .max();
2068 match max {
2069 Some(m) => SymId(m + 1),
2070 None => SymId(0),
2071 }
2072 }
2073
2074 /// Attach a data-determined row count to an `Op::MatMul` node — the
2075 /// sparse-MoE capacity-buffer support. The node's `Node::shape` stays
2076 /// the row-capacity output shape; `row_count` (a [`DynScalar`]) is how
2077 /// many rows to actually compute. See [`NodeHandle::matmul_dyn_m`].
2078 pub fn set_matmul_row_count(&mut self, id: NodeId, row_count: DynScalar) {
2079 assert!(
2080 id.0 < self.nodes.len(),
2081 "set_matmul_row_count: id out of bounds"
2082 );
2083 self.node_matmul_row_count.insert(id, row_count);
2084 }
2085
2086 /// The data-determined row count for `id`, if it carries one (i.e. it
2087 /// is a dynamic-M matmul). `None` ⇒ an ordinary static-M matmul.
2088 pub fn matmul_row_count(&self, id: NodeId) -> Option<DynScalar> {
2089 self.node_matmul_row_count.get(&id).copied()
2090 }
2091
2092 /// Look up the realized storage for a node, if any has been
2093 /// registered. Returns an Arc clone — the slot stays in the map
2094 /// after this call.
2095 pub fn storage_for(&self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2096 self.storage_map.get(&id).cloned()
2097 }
2098
2099 /// Register a realized-storage slot for `id`. Replaces any
2100 /// existing entry (callers responsible for ensuring this is the
2101 /// intended semantics — e.g. re-realization after eviction).
2102 pub fn set_storage(&mut self, id: NodeId, storage: Arc<RwLock<Storage>>) {
2103 assert!(id.0 < self.nodes.len(), "set_storage: id out of bounds");
2104 self.storage_map.insert(id, storage);
2105 }
2106
2107 /// Convenience: register an owned `Storage` directly. Wraps in
2108 /// `Arc<RwLock<...>>`.
2109 pub fn set_storage_owned(&mut self, id: NodeId, storage: Storage) {
2110 self.set_storage(id, Arc::new(RwLock::new(storage)));
2111 }
2112
2113 /// Remove a slot. Used by eviction / `Op::Release` paths.
2114 /// Returns the Arc if present so callers that want to keep the
2115 /// bytes alive can hold it; otherwise drops on the floor and any
2116 /// outstanding Arc clones still see the bytes.
2117 pub fn remove_storage(&mut self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2118 self.storage_map.remove(&id)
2119 }
2120
2121 /// Whether a slot is currently registered for `id`.
2122 pub fn has_storage(&self, id: NodeId) -> bool {
2123 self.storage_map.contains_key(&id)
2124 }
2125
2126 /// Number of registered storage slots.
2127 pub fn storage_len(&self) -> usize {
2128 self.storage_map.len()
2129 }
2130
2131 /// Register a NodeId as a side-effect root — a node whose output
2132 /// isn't reachable from any user-requested root but whose
2133 /// execution the executor must still schedule. Used for
2134 /// destructive ops (e.g. `Op::Release`) emitted by graph-mutating
2135 /// rules: the rule needs Release to run (freeing device memory),
2136 /// but Release's zero-element marker has no consumer.
2137 ///
2138 /// The executor's realize paths walk the user's roots AND these
2139 /// side-effect roots via a single combined `execution_plan` call.
2140 pub fn add_side_effect_root(&mut self, id: NodeId) {
2141 assert!(
2142 id.0 < self.nodes.len(),
2143 "add_side_effect_root: id out of bounds"
2144 );
2145 if !self.side_effect_roots.contains(&id) {
2146 self.side_effect_roots.push(id);
2147 }
2148 }
2149
2150 /// Snapshot the registered side-effect roots. Executor concatenates
2151 /// these with the user's requested roots before computing the plan.
2152 pub fn side_effect_roots(&self) -> &[NodeId] {
2153 &self.side_effect_roots
2154 }
2155
2156 /// The number of nodes currently in the graph.
2157 pub fn len(&self) -> usize {
2158 self.nodes.len()
2159 }
2160
2161 /// Whether the graph has any nodes.
2162 pub fn is_empty(&self) -> bool {
2163 self.nodes.is_empty()
2164 }
2165
2166 /// Borrow a node by ID. Panics if the ID is out of bounds — it should
2167 /// not be possible for a valid `NodeHandle` handle to produce an invalid
2168 /// ID, so any such panic indicates a bug in graph construction.
2169 pub fn node(&self, id: NodeId) -> &Node {
2170 &self.nodes[id.0]
2171 }
2172
2173 /// Produce a one-line human-readable description of a node and its
2174 /// immediate inputs — the identifier string that executor panics
2175 /// prepend so realize-time failures can be localized to the exact
2176 /// graph position that blew up. Format is stable enough for grep
2177 /// but explicitly intended for humans reading panic output, not for
2178 /// parsing.
2179 pub fn describe_node(&self, id: NodeId) -> String {
2180 let n = self.node(id);
2181 // GAP-303: `short_name()` renders every scan as the bare string "Scan",
2182 // so a body built from the WRONG scan was invisible in every dump and
2183 // every executor panic. Baracuda's requirement, adopted verbatim: make
2184 // something PRINT the carry count on the path that constructs the body —
2185 // not assert it. "A control tells you the encoding is sound; only the
2186 // subject's identity tells you what it encoded."
2187 let scan_params = match n.op {
2188 Op::Scan {
2189 n_carries,
2190 n_xs,
2191 bound,
2192 emit,
2193 ref early_exit,
2194 } => format!(
2195 " n_carries={n_carries} n_xs={n_xs} bound={bound} emit={emit:?} early_exit={}",
2196 early_exit.is_some()
2197 ),
2198 Op::ScanPlaceholder { role, index } => format!(" role={role:?} index={index}"),
2199 _ => String::new(),
2200 };
2201 let op_short = n.op.short_name();
2202 if n.inputs.is_empty() {
2203 return format!(
2204 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?})",
2205 id.0, n.shape, n.dtype,
2206 );
2207 }
2208 let inputs: Vec<String> = n
2209 .inputs
2210 .iter()
2211 .map(|&inp| {
2212 let ni = self.node(inp);
2213 let ip = ni.op.short_name();
2214 format!("Node#{}[{ip}, {:?}, {:?}]", inp.0, ni.shape, ni.dtype)
2215 })
2216 .collect();
2217 format!(
2218 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?}, inputs=[{}])",
2219 id.0,
2220 n.shape,
2221 n.dtype,
2222 inputs.join(", "),
2223 )
2224 }
2225
2226 /// Append a node and return its fresh ID. Used by the `NodeHandle`
2227 /// builders, by `opt` passes that canonicalize or rewrite the
2228 /// graph by appending fresh nodes, and by external consumers
2229 /// (fuel-storage's pipelined executor tests, custom-op authors)
2230 /// that need direct graph construction.
2231 ///
2232 /// For metadata-only view ops (`Op::Transpose`, `Op::Permute`,
2233 /// `Op::BroadcastTo`, `Op::Slice`) this also populates the
2234 /// [`layouts`](Self::layout) side-table by deriving the output
2235 /// layout from the input's layout via
2236 /// [`derive_view_output_layout`]. After this call,
2237 /// `graph.layout(new_id)` returns the strided/offset view layout
2238 /// without any further work — the side-table is the single source
2239 /// of truth for layout, with [`Layout::contiguous`] as the
2240 /// fallback for kernel-output nodes.
2241 ///
2242 /// Misuse (malformed Node, dangling input ids, etc.) is caught
2243 /// at execute time as a typed error, not a panic — per project's
2244 /// no-panic-in-production rule.
2245 pub fn push(&mut self, node: Node) -> NodeId {
2246 let id = NodeId(self.nodes.len());
2247 let is_view = node.op.is_view_op();
2248 let view_input = if is_view {
2249 node.inputs.first().copied()
2250 } else {
2251 None
2252 };
2253 let op_for_derive = if is_view { Some(node.op.clone()) } else { None };
2254 self.nodes.push(node);
2255 if let (Some(input_id), Some(op)) = (view_input, op_for_derive)
2256 && input_id.0 < self.nodes.len()
2257 {
2258 let input_layout = self.layout(input_id);
2259 if let Ok(out_layout) = derive_view_output_layout(&op, &input_layout) {
2260 self.set_layout(id, out_layout);
2261 }
2262 }
2263 id
2264 }
2265
2266 /// Rewrite every occurrence of `old_input` in `node`'s input list to
2267 /// `new_input`. In-place mutation — the *only* exception to the
2268 /// otherwise append-only invariant.
2269 ///
2270 /// Callers are responsible for ensuring `new_input` is semantically
2271 /// equivalent to `old_input` at this edge: same shape, same dtype,
2272 /// and produces data the consumer can read without error on the
2273 /// relevant device. Used by transform passes (residency eviction,
2274 /// fusion) that need to redirect a specific consumer's edge.
2275 pub(crate) fn rewrite_input(&mut self, node: NodeId, old_input: NodeId, new_input: NodeId) {
2276 assert!(
2277 node.0 < self.nodes.len(),
2278 "rewrite_input: node out of bounds"
2279 );
2280 let inputs = &mut self.nodes[node.0].inputs;
2281 for inp in inputs.iter_mut() {
2282 if *inp == old_input {
2283 *inp = new_input;
2284 }
2285 }
2286 }
2287
2288 /// **Collapse a decision point to a single baked arm** — the graph-side
2289 /// half of *optimize-time kernel-variant baking* (04-optimization:
2290 /// "kernel-variant choice is largely baked at optimize time"). Given a
2291 /// finalized [`Op::Branch`] and the arm the optimizer chose (`winner_arm`,
2292 /// an index into the branch's `inputs`), this rewrites the graph so the
2293 /// chosen arm is the **realized route** and the branch is no longer a
2294 /// decision point:
2295 ///
2296 /// 1. The `reconverge_at` merge is rewired to read the **winner's exit**
2297 /// (`inputs[winner_arm]`) in place of arm 0's exit (`inputs[0]`). For
2298 /// `winner_arm == 0` this is a no-op (the merge already reads arm 0,
2299 /// the runnability fallback).
2300 /// 2. The branch's `inputs` are reduced to `[winner_exit]` — a **single-arm
2301 /// branch**, which [`run::extract_runs_multi`] / `non_chosen_arm_nodes` /
2302 /// the route picker all treat as *no decision* (`arms.len() < 2`), so the
2303 /// winner's region lowers inline and the non-chosen arms become
2304 /// orphaned (pruned from the reachable set — nothing reads them once the
2305 /// merge is rewired). The arm-0 runnability invariant is preserved:
2306 /// after the reduce, `inputs[0]` is the winner and the merge reads it.
2307 ///
2308 /// This is the "the Branch collapses" resolution the constitution names for
2309 /// same-device **kernel-variant** choices (decomposed-region vs. a fused
2310 /// kernel on the *same* device), as distinct from **placement** choices
2311 /// (arms on *different* devices) which stay live `Op::Branch` decision
2312 /// points for the runtime route picker (06-runtime). The optimizer decides
2313 /// *which* branches are variant branches and computes `winner_arm`; this
2314 /// method only performs the structural collapse.
2315 ///
2316 /// Never-panic: returns [`fuel_ir::Error::InvalidBranch`] on a
2317 /// non-`Op::Branch` node or an out-of-range `winner_arm`, mutating nothing.
2318 /// Idempotent on an already-collapsed (single-arm) branch when
2319 /// `winner_arm == 0`.
2320 pub fn collapse_variant_branch(
2321 &mut self,
2322 branch: NodeId,
2323 winner_arm: usize,
2324 ) -> std::result::Result<(), fuel_ir::Error> {
2325 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2326 if branch.0 >= self.nodes.len() {
2327 return Err(invalid(format!(
2328 "collapse_variant_branch: branch Node#{} is out of bounds \
2329 (graph has {} nodes)",
2330 branch.0,
2331 self.nodes.len(),
2332 )));
2333 }
2334 let reconverge_at = match self.nodes[branch.0].op {
2335 Op::Branch { reconverge_at } => reconverge_at,
2336 ref other => {
2337 return Err(invalid(format!(
2338 "collapse_variant_branch: Node#{} is not an Op::Branch (got \
2339 {other:?})",
2340 branch.0,
2341 )));
2342 }
2343 };
2344 let arms = &self.nodes[branch.0].inputs;
2345 if arms.is_empty() {
2346 return Err(invalid(format!(
2347 "collapse_variant_branch: branch Node#{} has no arms",
2348 branch.0,
2349 )));
2350 }
2351 if winner_arm >= arms.len() {
2352 return Err(invalid(format!(
2353 "collapse_variant_branch: winner_arm {winner_arm} is out of range \
2354 (branch Node#{} has {} arms)",
2355 branch.0,
2356 arms.len(),
2357 )));
2358 }
2359 let old_arm0 = arms[0];
2360 let winner = arms[winner_arm];
2361
2362 // (1) Rewire the merge to read the winner's exit (no-op for arm 0).
2363 if winner != old_arm0 {
2364 self.rewrite_input(reconverge_at, old_arm0, winner);
2365 }
2366 // (2) Reduce the branch to the single winning arm (now arm 0). A
2367 // single-arm branch is inert: the run extractor / picker skip it,
2368 // so the non-chosen arms are pruned and the winner lowers inline.
2369 self.nodes[branch.0].inputs = vec![winner];
2370 Ok(())
2371 }
2372
2373 /// Tag a node with a target device. The executor will validate
2374 /// (post-Phase-1) that the node's op can be evaluated on that
2375 /// device. In Phase 1 the tag is informational only.
2376 pub fn set_placement(&mut self, id: NodeId, loc: DeviceLocation) {
2377 assert!(id.0 < self.nodes.len(), "set_placement: id out of bounds");
2378 self.placements.insert(id, loc);
2379 }
2380
2381 /// Read a node's placement hint, or `None` if the node inherits from
2382 /// the executor default.
2383 pub fn placement(&self, id: NodeId) -> Option<DeviceLocation> {
2384 self.placements.get(&id).copied()
2385 }
2386
2387 /// Open a [`BranchBuilder`] rooted at a shared `diverge` point — the
2388 /// first half of the `open_branch` / `add_arm` / `finalize_branches`
2389 /// trio that constructs an [`Op::Branch`] (phi/merge) node with
2390 /// build-time validation (Phase A PR-A1 of the "plan IS the graph"
2391 /// rebuild).
2392 ///
2393 /// `diverge` names the single node from which every candidate route
2394 /// (arm) departs; each arm's *exit* (added via
2395 /// [`BranchBuilder::add_arm`]) becomes one `inputs[i]` of the emitted
2396 /// `Op::Branch`. The builder borrows nothing — it is a pure
2397 /// accumulator of `NodeId`s — so the graph stays free to keep building
2398 /// arms between `open_branch` and `finalize_branches`. All validation
2399 /// (descendant `reconverge_at`, internally-disjoint arms,
2400 /// cast-to-uniform shape/dtype, arm-0 runnability) happens in
2401 /// [`BranchBuilder::finalize_branches`], which returns a typed
2402 /// [`fuel_ir::error::Error::InvalidBranch`] rather than panicking.
2403 pub fn open_branch(&self, diverge: NodeId) -> BranchBuilder {
2404 BranchBuilder {
2405 diverge,
2406 arms: Vec::new(),
2407 }
2408 }
2409
2410 /// Forward-reachable set (the node and all its transitive *consumers*)
2411 /// from `from`, computed against a precomputed consumer adjacency.
2412 /// Used by branch validation to test descendant-hood and arm
2413 /// containment without re-scanning the whole arena per query.
2414 fn forward_reachable(
2415 consumers: &HashMap<NodeId, Vec<NodeId>>,
2416 from: NodeId,
2417 ) -> HashSet<NodeId> {
2418 let mut seen: HashSet<NodeId> = HashSet::new();
2419 let mut stack = vec![from];
2420 while let Some(n) = stack.pop() {
2421 if !seen.insert(n) {
2422 continue;
2423 }
2424 if let Some(cs) = consumers.get(&n) {
2425 for &c in cs {
2426 if !seen.contains(&c) {
2427 stack.push(c);
2428 }
2429 }
2430 }
2431 }
2432 seen
2433 }
2434
2435 /// Backward-reachable set (the node and all its transitive *inputs*)
2436 /// from `from`. Used to bound an arm to the nodes that actually lie
2437 /// on a path `diverge → exit`.
2438 fn backward_reachable(&self, from: NodeId) -> HashSet<NodeId> {
2439 let mut seen: HashSet<NodeId> = HashSet::new();
2440 let mut stack = vec![from];
2441 while let Some(n) = stack.pop() {
2442 if !seen.insert(n) {
2443 continue;
2444 }
2445 for &inp in &self.nodes[n.0].inputs {
2446 if !seen.contains(&inp) {
2447 stack.push(inp);
2448 }
2449 }
2450 }
2451 seen
2452 }
2453
2454 // -------------------------------------------------------------------
2455 // Compaction of the append-only arena (PR-B4)
2456 // -------------------------------------------------------------------
2457
2458 /// The set of nodes that constitute the **live structure** of the
2459 /// graph relative to `roots`: everything reachable, following node
2460 /// `inputs`, from the union of
2461 ///
2462 /// - the caller's `roots`,
2463 /// - the `side_effect_roots` (nodes the executor must schedule even
2464 /// when no output reads them — e.g. `Op::Release` eviction), and
2465 /// - the full multi-path structure: for every reachable `Op::Branch`,
2466 /// its `reconverge_at` and **all its arms** (the arm exits, which
2467 /// are the Branch node's `inputs`, and transitively their interiors).
2468 /// Phase C's route picker needs every arm, so the alternative arms
2469 /// must survive even though nothing downstream reads them directly
2470 /// (the `reconverge_at` node reads only arm 0).
2471 ///
2472 /// A finalized `Op::Branch` is itself typically orphaned — nothing
2473 /// downstream reads it (PR-A1's runnability invariant has the merge
2474 /// read arm 0 directly, not the Branch). So a plain forward walk from
2475 /// `roots` would miss it. We therefore mirror [`run::extract_runs_multi`]'s
2476 /// `effective_roots` discipline: scan the arena and seed any Branch
2477 /// whose `reconverge_at` (or any arm exit) is already reachable, to a
2478 /// fixpoint, then take the input-closure of all seeds. The result is
2479 /// the exact set compaction must keep.
2480 fn live_set(&self, roots: &[NodeId]) -> HashSet<NodeId> {
2481 // Seeds: roots + side-effect roots. We grow this set with the
2482 // Branch nodes that participate in the reachable computation, then
2483 // take its full input-closure.
2484 let mut seeds: Vec<NodeId> = Vec::new();
2485 let mut seed_set: HashSet<NodeId> = HashSet::new();
2486 let push_seed = |id: NodeId, seeds: &mut Vec<NodeId>, seed_set: &mut HashSet<NodeId>| {
2487 if id.0 < self.nodes.len() && seed_set.insert(id) {
2488 seeds.push(id);
2489 }
2490 };
2491 for &r in roots {
2492 push_seed(r, &mut seeds, &mut seed_set);
2493 }
2494 for &r in &self.side_effect_roots {
2495 push_seed(r, &mut seeds, &mut seed_set);
2496 }
2497
2498 // Grow the seed set with participating Branch nodes to a fixpoint.
2499 // A Branch "participates" when its merge target or any arm exit is
2500 // already reachable from the current seeds (following inputs). Each
2501 // newly-seeded Branch may pull in further arms whose interiors then
2502 // make another Branch participate, hence the fixpoint.
2503 loop {
2504 let reachable = self.input_closure(&seeds);
2505 let mut added = false;
2506 for idx in 0..self.nodes.len() {
2507 let id = NodeId(idx);
2508 if seed_set.contains(&id) {
2509 continue;
2510 }
2511 let Op::Branch { reconverge_at } = self.nodes[idx].op else {
2512 continue;
2513 };
2514 let participates = reachable.contains(&reconverge_at)
2515 || self.nodes[idx].inputs.iter().any(|a| reachable.contains(a));
2516 if participates {
2517 seed_set.insert(id);
2518 seeds.push(id);
2519 added = true;
2520 }
2521 }
2522 if !added {
2523 break;
2524 }
2525 }
2526
2527 // The live set is the full input-closure of the (roots + side-effect
2528 // + participating-Branch) seeds, plus each reachable Branch's
2529 // explicit `reconverge_at` (which is downstream of the arms, so it
2530 // is not pulled in by following inputs from the Branch). The merge
2531 // node is normally reachable from `roots` already, but seeding it
2532 // explicitly makes the live set self-consistent — a Branch never
2533 // outlives its merge target.
2534 let mut live = self.input_closure(&seeds);
2535 let recon_seeds: Vec<NodeId> = live
2536 .iter()
2537 .filter_map(|&id| match self.nodes[id.0].op {
2538 Op::Branch { reconverge_at } => Some(reconverge_at),
2539 _ => None,
2540 })
2541 .collect();
2542 if !recon_seeds.is_empty() {
2543 for n in self.input_closure(&recon_seeds) {
2544 live.insert(n);
2545 }
2546 }
2547 live
2548 }
2549
2550 /// Every node reachable from any of `from`, following node `inputs`
2551 /// transitively (the backward / input cone). Mirrors
2552 /// [`topo_order_multi`] but returns just the set.
2553 fn input_closure(&self, from: &[NodeId]) -> HashSet<NodeId> {
2554 let mut seen: HashSet<NodeId> = HashSet::new();
2555 let mut stack: Vec<NodeId> = from.to_vec();
2556 while let Some(n) = stack.pop() {
2557 if n.0 >= self.nodes.len() || !seen.insert(n) {
2558 continue;
2559 }
2560 for &inp in &self.nodes[n.0].inputs {
2561 if !seen.contains(&inp) {
2562 stack.push(inp);
2563 }
2564 }
2565 }
2566 seen
2567 }
2568
2569 /// **Required compaction of the append-only arena** (PR-B4).
2570 ///
2571 /// Drops every node *not* in the live structure relative to `roots`
2572 /// (the exploration debris that pathfinders leave) and rebuilds the
2573 /// arena with contiguous, renumbered [`NodeId`]s, remapping **every**
2574 /// `NodeId` reference in the graph. Returns the [`NodeRemap`] from old
2575 /// to new ids so callers can fix up their own `NodeHandle` handles / roots.
2576 ///
2577 /// The live set follows node `inputs` from: `roots`, the
2578 /// `side_effect_roots`, and the full multi-path structure — for every
2579 /// reachable [`Op::Branch`], its `reconverge_at` **and all its arms**
2580 /// (so the route picker's alternatives survive). See [`Graph::live_set`].
2581 ///
2582 /// What is remapped (the correctness crux — a missed remap is silent
2583 /// corruption). Every NodeId-bearing structure in the graph:
2584 /// - each surviving [`Node`]'s `inputs`;
2585 /// - the `NodeId` carried *inside* an op variant — [`Op::Branch`]'s
2586 /// `reconverge_at` (the only `Op` variant carrying a `NodeId`);
2587 /// - every NodeId-keyed side-table on [`Graph`]: `placements`,
2588 /// `target_backends`, `layouts`, `storage_map`, `node_output_views`;
2589 /// - the `side_effect_roots` vector.
2590 ///
2591 /// # Not in the per-realize hot path
2592 ///
2593 /// Compaction renumbers `NodeId`s, which would invalidate a realize
2594 /// already built around the current ids (the dispatch order and the
2595 /// `StorageCache` key are `NodeId`). It is therefore a **standalone
2596 /// pass**, deliberately **not** registered as an `Optimizer` in the
2597 /// per-realize driver / `optimize_graph` loop. It runs at load-time
2598 /// **between optimization rounds** (Phase D) and is **required before
2599 /// finalize-to-disk** (Phase E) so the persisted `.fuel` holds the lean
2600 /// result, not exploration debris. Neither caller exists yet.
2601 ///
2602 /// Orphans never change results, so this is a *size* pass, not a
2603 /// *correctness* one — but the remap it performs must be exhaustive or
2604 /// it would itself introduce corruption, which is the property the
2605 /// born-red tests + [`Graph::verify_no_dangling`] guard.
2606 ///
2607 /// This is the implementation behind the free function [`compact`];
2608 /// call that.
2609 fn compact_in_place(&mut self, roots: &[NodeId]) -> NodeRemap {
2610 let live = self.live_set(roots);
2611 let n = self.nodes.len();
2612
2613 // Assign new contiguous ids in ascending old-id order, so the
2614 // relative order of surviving nodes (and hence any topological
2615 // property over them) is preserved.
2616 let mut old_to_new: Vec<Option<NodeId>> = vec![None; n];
2617 let mut next = 0usize;
2618 #[expect(
2619 clippy::needless_range_loop,
2620 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"
2621 )]
2622 for idx in 0..n {
2623 if live.contains(&NodeId(idx)) {
2624 old_to_new[idx] = Some(NodeId(next));
2625 next += 1;
2626 }
2627 }
2628 let remap = NodeRemap { old_to_new };
2629
2630 // Rebuild the node arena, remapping each surviving node's inputs and
2631 // any op-carried NodeId. Surviving nodes' inputs are themselves
2632 // always live (the live set is input-closed), so every `map` here
2633 // resolves.
2634 let mut new_nodes: Vec<Node> = Vec::with_capacity(next);
2635 for idx in 0..n {
2636 if remap.old_to_new[idx].is_none() {
2637 continue;
2638 }
2639 let mut node = self.nodes[idx].clone();
2640 for inp in node.inputs.iter_mut() {
2641 *inp = remap.expect(*inp);
2642 }
2643 if let Op::Branch { reconverge_at } = &mut node.op {
2644 *reconverge_at = remap.expect(*reconverge_at);
2645 }
2646 new_nodes.push(node);
2647 }
2648 self.nodes = new_nodes;
2649
2650 // Remap every NodeId-keyed side-table. Drop entries for dropped
2651 // nodes; rekey survivors to their new id.
2652 self.placements = remap.rekey(std::mem::take(&mut self.placements));
2653 self.target_backends = remap.rekey(std::mem::take(&mut self.target_backends));
2654 self.layouts = remap.rekey(std::mem::take(&mut self.layouts));
2655 self.storage_map = remap.rekey(std::mem::take(&mut self.storage_map));
2656 self.node_output_views = remap.rekey(std::mem::take(&mut self.node_output_views));
2657 self.storage_class = remap.rekey(std::mem::take(&mut self.storage_class));
2658 self.node_matmul_row_count = remap.rekey(std::mem::take(&mut self.node_matmul_row_count));
2659
2660 // Remap the side-effect-roots vector (every entry is live — they
2661 // were reachability seeds — so each maps).
2662 self.side_effect_roots = self
2663 .side_effect_roots
2664 .iter()
2665 .map(|&id| remap.expect(id))
2666 .collect();
2667
2668 debug_assert!(
2669 self.verify_no_dangling().is_ok(),
2670 "compact left a dangling NodeId reference: {:?}",
2671 self.verify_no_dangling().err(),
2672 );
2673 remap
2674 }
2675
2676 /// Verify that **no** `NodeId` reference in the graph points outside
2677 /// the arena — the post-compaction safety net for a missed remap.
2678 /// Checks every node's `inputs`, the op-carried `Op::Branch`
2679 /// `reconverge_at`, every NodeId-keyed side-table, and the
2680 /// `side_effect_roots` vector. Returns the first offending reference as
2681 /// a typed error (never panics); used by [`crate::compact`]'s
2682 /// `debug_assert` and by tests.
2683 pub fn verify_no_dangling(&self) -> std::result::Result<(), fuel_ir::Error> {
2684 let n = self.nodes.len();
2685 let bad = |what: String| {
2686 Err(fuel_ir::Error::Msg(format!(
2687 "dangling NodeId reference: {what} (arena has {n} nodes)",
2688 )))
2689 };
2690 for (idx, node) in self.nodes.iter().enumerate() {
2691 for &inp in &node.inputs {
2692 if inp.0 >= n {
2693 return bad(format!("Node#{idx} input Node#{}", inp.0));
2694 }
2695 }
2696 if let Op::Branch { reconverge_at } = node.op
2697 && reconverge_at.0 >= n
2698 {
2699 return bad(format!(
2700 "Node#{idx} Branch.reconverge_at Node#{}",
2701 reconverge_at.0
2702 ));
2703 }
2704 }
2705 for id in self.placements.keys() {
2706 if id.0 >= n {
2707 return bad(format!("placements key Node#{}", id.0));
2708 }
2709 }
2710 for id in self.target_backends.keys() {
2711 if id.0 >= n {
2712 return bad(format!("target_backends key Node#{}", id.0));
2713 }
2714 }
2715 for id in self.layouts.keys() {
2716 if id.0 >= n {
2717 return bad(format!("layouts key Node#{}", id.0));
2718 }
2719 }
2720 for id in self.storage_map.keys() {
2721 if id.0 >= n {
2722 return bad(format!("storage_map key Node#{}", id.0));
2723 }
2724 }
2725 for id in self.node_output_views.keys() {
2726 if id.0 >= n {
2727 return bad(format!("node_output_views key Node#{}", id.0));
2728 }
2729 }
2730 for id in self.storage_class.keys() {
2731 if id.0 >= n {
2732 return bad(format!("storage_class key Node#{}", id.0));
2733 }
2734 }
2735 for &id in &self.side_effect_roots {
2736 if id.0 >= n {
2737 return bad(format!("side_effect_root Node#{}", id.0));
2738 }
2739 }
2740 Ok(())
2741 }
2742}
2743
2744/// **Required compaction of the append-only arena** (PR-B4).
2745///
2746/// Drops every node *not* in the live structure relative to `roots` (the
2747/// exploration debris that pathfinders leave) and rebuilds the arena with
2748/// contiguous, renumbered [`NodeId`]s, remapping **every** `NodeId`
2749/// reference in the graph. Returns the [`NodeRemap`] from old → new ids so
2750/// callers can fix up their own roots / `NodeHandle` handles.
2751///
2752/// The live set follows node `inputs` from `roots`, the
2753/// `side_effect_roots`, and the full multi-path structure — for every
2754/// reachable [`Op::Branch`], its `reconverge_at` **and all its arms** (so
2755/// Phase C's route picker keeps its alternatives). Everything else is
2756/// dropped.
2757///
2758/// **Not in the per-realize hot path.** Compaction renumbers `NodeId`s,
2759/// which would invalidate a realize built around the current ids (the
2760/// dispatch order + the `StorageCache` key are `NodeId`). It is a
2761/// standalone pass — deliberately **not** registered as an `Optimizer` in
2762/// the per-realize driver / `optimize_graph` loop — run at load-time
2763/// **between optimization rounds** (Phase D) and **required before
2764/// finalize-to-disk** (Phase E). Neither caller exists yet.
2765///
2766/// See [`Graph::verify_no_dangling`] for the post-condition the
2767/// `debug_assert` checks: no `NodeId` reference (node inputs, the
2768/// op-carried `Op::Branch.reconverge_at`, any side-table, or
2769/// `side_effect_roots`) points outside the new arena.
2770pub fn compact(graph: &mut Graph, roots: &[NodeId]) -> NodeRemap {
2771 graph.compact_in_place(roots)
2772}
2773
2774/// The old → new `NodeId` mapping produced by [`compact`].
2775///
2776/// Indexed by the *old* `NodeId`: `old_to_new[old.0]` is `Some(new)` if the
2777/// node survived compaction, or `None` if it was dropped as unreachable
2778/// debris. Callers use [`NodeRemap::get`] to translate roots / `NodeHandle`
2779/// ids they still hold; passes that know a node must have survived use
2780/// `NodeRemap::expect`.
2781#[derive(Debug, Clone)]
2782pub struct NodeRemap {
2783 old_to_new: Vec<Option<NodeId>>,
2784}
2785
2786impl NodeRemap {
2787 /// The new id for `old`, or `None` if `old` was dropped (or is out of
2788 /// range of the pre-compaction arena).
2789 pub fn get(&self, old: NodeId) -> Option<NodeId> {
2790 self.old_to_new.get(old.0).copied().flatten()
2791 }
2792
2793 /// Whether `old` survived compaction.
2794 pub fn survived(&self, old: NodeId) -> bool {
2795 self.get(old).is_some()
2796 }
2797
2798 /// The new id for `old`, asserting it survived. Used internally when
2799 /// remapping a reference that is known-live (a surviving node's input,
2800 /// a reachable Branch's `reconverge_at`, a side-effect root) — a `None`
2801 /// here would mean the live-set computation was unsound.
2802 fn expect(&self, old: NodeId) -> NodeId {
2803 self.get(old).unwrap_or_else(|| {
2804 panic!(
2805 "NodeRemap::expect: Node#{} was expected to survive compaction \
2806 but was dropped — the live set is unsound (a referenced node \
2807 was not kept)",
2808 old.0,
2809 )
2810 })
2811 }
2812
2813 /// Rekey a `NodeId`-keyed side-table: drop entries whose key was
2814 /// dropped, rewrite surviving keys to their new id. Values are moved,
2815 /// not cloned.
2816 fn rekey<V>(&self, table: HashMap<NodeId, V>) -> HashMap<NodeId, V> {
2817 let mut out = HashMap::with_capacity(table.len());
2818 for (old, v) in table {
2819 if let Some(new) = self.get(old) {
2820 out.insert(new, v);
2821 }
2822 }
2823 out
2824 }
2825}
2826
2827/// Accumulates the arms of an in-construction [`Op::Branch`] (phi/merge)
2828/// node before [`finalize_branches`](Self::finalize_branches) validates
2829/// them and emits the node. Created by [`Graph::open_branch`].
2830///
2831/// The multi-path structure is an **arena fact, not an overlay**: a
2832/// `Branch` node's divergent arms are its `inputs` (each input is one
2833/// route's *exit*), and the op carries an explicit `reconverge_at`. The
2834/// builder is a pure `NodeId` accumulator — it holds no graph reference —
2835/// so the graph remains free to keep appending nodes (further arms) while
2836/// the builder is open. Nothing mutates the arena until
2837/// `finalize_branches`, which is the single validation gate.
2838#[derive(Debug, Clone)]
2839pub struct BranchBuilder {
2840 /// The shared node every arm departs from.
2841 diverge: NodeId,
2842 /// Each arm's *exit* node, in priority order. `arms[0]` is the
2843 /// runnability fallback (arm 0): the route a finalized-but-unpicked
2844 /// graph realizes on.
2845 arms: Vec<NodeId>,
2846}
2847
2848impl BranchBuilder {
2849 /// Append one arm by its *exit* node — the node whose value the merge
2850 /// reads for this route. The first arm added is **arm 0**, the
2851 /// runnability fallback: `reconverge_at` must read arm 0's exit so a
2852 /// finalized-but-not-yet-route-picked graph still realizes (validated
2853 /// in [`finalize_branches`](Self::finalize_branches)).
2854 ///
2855 /// Returns `&mut Self` for chaining. Validation is deferred to
2856 /// finalize — `add_arm` never inspects the graph and never fails.
2857 pub fn add_arm(&mut self, exit: NodeId) -> &mut Self {
2858 self.arms.push(exit);
2859 self
2860 }
2861
2862 /// The shared diverge point this branch departs from.
2863 pub fn diverge(&self) -> NodeId {
2864 self.diverge
2865 }
2866
2867 /// The arm exits accumulated so far, in add order (arm 0 first).
2868 pub fn arms(&self) -> &[NodeId] {
2869 &self.arms
2870 }
2871
2872 /// Validate and emit the [`Op::Branch`] node, returning its fresh
2873 /// `NodeId`. This is the single build-time gate; it **never panics**,
2874 /// surfacing every rejection as [`fuel_ir::error::Error::InvalidBranch`].
2875 ///
2876 /// Returns:
2877 /// - `Ok(Some(branch_id))` — a multi-arm branch was emitted.
2878 /// - `Ok(None)` — a **single-arm branch collapsed** to that arm (no
2879 /// real decision point), leaving the arena untouched.
2880 /// - `Err(Error::InvalidBranch { .. })` — a validation rule failed.
2881 ///
2882 /// Validation rules (all checked before any mutation):
2883 /// 1. At least one arm; `diverge`, `reconverge_at`, and every arm
2884 /// exit are in-bounds.
2885 /// 2. **Descendant `reconverge_at`** — the merge must be a forward
2886 /// descendant of (and distinct from) `diverge`.
2887 /// 3. **Internally-disjoint arms** — each arm's interior nodes (the
2888 /// nodes on paths `diverge → exit`, excluding the shared `diverge`)
2889 /// must neither be shared with another arm nor read by any node
2890 /// outside the branch (`reconverge_at` reading an arm exit is the
2891 /// one allowed external consumer).
2892 /// 4. **Cast-to-uniform** — all arm exits agree on shape & dtype.
2893 /// PR-A1 *validates* uniformity and errors on mismatch (it does not
2894 /// insert `Cast` nodes); dtype-lowered alternatives must therefore
2895 /// cast back to the merge dtype *inside* their arm before the exit.
2896 /// 5. **Arm-0 runnability** — `reconverge_at` must read arm 0's exit,
2897 /// so a finalized-but-unpicked graph still realizes on arm 0.
2898 pub fn finalize_branches(
2899 self,
2900 graph: &mut Graph,
2901 reconverge_at: NodeId,
2902 ) -> std::result::Result<Option<NodeId>, fuel_ir::Error> {
2903 let n = graph.nodes.len();
2904 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2905
2906 // (1a) At least one arm.
2907 if self.arms.is_empty() {
2908 return Err(invalid(
2909 "branch has no arms; at least one route is required".to_string(),
2910 ));
2911 }
2912 // (1b) Bounds-check every referenced node up front so later
2913 // arena indexing cannot panic.
2914 let in_bounds = |id: NodeId| id.0 < n;
2915 if !in_bounds(self.diverge) {
2916 return Err(invalid(format!(
2917 "diverge Node#{} is out of bounds (graph has {n} nodes)",
2918 self.diverge.0,
2919 )));
2920 }
2921 if !in_bounds(reconverge_at) {
2922 return Err(invalid(format!(
2923 "reconverge_at Node#{} is out of bounds (graph has {n} nodes)",
2924 reconverge_at.0,
2925 )));
2926 }
2927 for &arm in &self.arms {
2928 if !in_bounds(arm) {
2929 return Err(invalid(format!(
2930 "arm exit Node#{} is out of bounds (graph has {n} nodes)",
2931 arm.0,
2932 )));
2933 }
2934 }
2935
2936 // (d) Single-arm branches collapse back to that arm — no real
2937 // decision point, so no Op::Branch is emitted and the arena is
2938 // left untouched.
2939 if self.arms.len() == 1 {
2940 return Ok(None);
2941 }
2942
2943 // Build a consumer (reverse) adjacency once for the reachability
2944 // queries below.
2945 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2946 for (idx, node) in graph.nodes.iter().enumerate() {
2947 let consumer = NodeId(idx);
2948 for &inp in &node.inputs {
2949 consumers.entry(inp).or_default().push(consumer);
2950 }
2951 }
2952
2953 // (2) reconverge_at must be a forward descendant of diverge and
2954 // distinct from it.
2955 if reconverge_at == self.diverge {
2956 return Err(invalid(format!(
2957 "reconverge_at Node#{} must be a strict descendant of the \
2958 diverge point, not the diverge point itself",
2959 reconverge_at.0,
2960 )));
2961 }
2962 let fwd_from_diverge = Graph::forward_reachable(&consumers, self.diverge);
2963 if !fwd_from_diverge.contains(&reconverge_at) {
2964 return Err(invalid(format!(
2965 "reconverge_at Node#{} is not a descendant of diverge Node#{}",
2966 reconverge_at.0, self.diverge.0,
2967 )));
2968 }
2969
2970 // (4) Cast-to-uniform: every arm exit must agree on shape & dtype
2971 // with arm 0 (PR-A1 validates uniformity rather than inserting
2972 // Cast nodes).
2973 let arm0 = self.arms[0];
2974 let (want_shape, want_dtype) = {
2975 let a0 = &graph.nodes[arm0.0];
2976 (a0.shape.clone(), a0.dtype)
2977 };
2978 for &arm in &self.arms[1..] {
2979 let node = &graph.nodes[arm.0];
2980 if node.shape != want_shape || node.dtype != want_dtype {
2981 return Err(invalid(format!(
2982 "arm exit Node#{} ({:?} {:?}) disagrees with arm 0 Node#{} \
2983 ({:?} {:?}); arms must cast to a uniform shape & dtype at \
2984 reconverge",
2985 arm.0, node.shape, node.dtype, arm0.0, want_shape, want_dtype,
2986 )));
2987 }
2988 }
2989
2990 // (5) Arm-0 runnability: reconverge_at must read arm 0's exit, so
2991 // an unpicked graph realizes on arm 0.
2992 if !graph.nodes[reconverge_at.0].inputs.contains(&arm0) {
2993 return Err(invalid(format!(
2994 "reconverge_at Node#{} does not read arm-0 exit Node#{}; the \
2995 arm-0 runnability invariant requires the merge to read arm 0 \
2996 so a not-yet-route-picked graph still realizes",
2997 reconverge_at.0, arm0.0,
2998 )));
2999 }
3000
3001 // (3) Internal disjointness. Each arm's node set is the nodes on
3002 // paths diverge → exit: backward-reachable from the exit AND
3003 // forward-reachable from diverge. The arm *interior* excludes the
3004 // shared diverge point.
3005 let mut arm_interiors: Vec<HashSet<NodeId>> = Vec::with_capacity(self.arms.len());
3006 for &exit in &self.arms {
3007 let back = graph.backward_reachable(exit);
3008 let mut interior: HashSet<NodeId> =
3009 back.intersection(&fwd_from_diverge).copied().collect();
3010 interior.remove(&self.diverge);
3011 // The exit itself is always part of the arm even if (for a
3012 // degenerate arm) it equals the diverge point — but a
3013 // diverge-equals-exit arm has an empty interior, which would
3014 // make the arm indistinguishable from "no route", so reject.
3015 if interior.is_empty() {
3016 return Err(invalid(format!(
3017 "arm exit Node#{} has no interior strictly after diverge \
3018 Node#{}; an arm must add at least one node between the \
3019 diverge point and its exit",
3020 exit.0, self.diverge.0,
3021 )));
3022 }
3023 arm_interiors.push(interior);
3024 }
3025
3026 // (3a) Arms must not share interior nodes.
3027 for i in 0..arm_interiors.len() {
3028 for j in (i + 1)..arm_interiors.len() {
3029 if let Some(shared) = arm_interiors[i].intersection(&arm_interiors[j]).next() {
3030 return Err(invalid(format!(
3031 "arms {i} and {j} share interior Node#{}; arms must be \
3032 internally disjoint",
3033 shared.0,
3034 )));
3035 }
3036 }
3037 }
3038
3039 // (3b) No arm-interior node may be read from outside the branch.
3040 // The branch's universe is the union of all arm interiors plus
3041 // the merge node; reconverge_at reading an arm exit is the one
3042 // legitimate "external" consumer.
3043 let mut branch_universe: HashSet<NodeId> = HashSet::new();
3044 for interior in &arm_interiors {
3045 branch_universe.extend(interior.iter().copied());
3046 }
3047 branch_universe.insert(reconverge_at);
3048 for (i, interior) in arm_interiors.iter().enumerate() {
3049 for &m in interior {
3050 if let Some(cs) = consumers.get(&m) {
3051 for &c in cs {
3052 if !branch_universe.contains(&c) {
3053 return Err(invalid(format!(
3054 "arm {i} interior Node#{} is read from outside \
3055 the branch by Node#{}; arm interiors must not be \
3056 reachable from outside the branch",
3057 m.0, c.0,
3058 )));
3059 }
3060 }
3061 }
3062 }
3063 }
3064
3065 // All validation passed — emit the Branch node. Its inputs ARE the
3066 // arm exits, in priority order (arm 0 first); reconverge_at is
3067 // carried on the op. Shape/dtype mirror arm 0 (the uniform merge
3068 // type validated above).
3069 let branch = graph.push(Node {
3070 op: Op::Branch { reconverge_at },
3071 inputs: self.arms.clone(),
3072 shape: want_shape,
3073 dtype: want_dtype,
3074 });
3075 Ok(Some(branch))
3076 }
3077}
3078
3079/// A shared, mutable graph. Builders clone this cheaply and hand it to
3080/// every derived tensor so that all tensors in one computation point to
3081/// the same arena.
3082pub type SharedGraph = Arc<RwLock<Graph>>;
3083
3084/// A handle to a node in a shared graph. Cheap to clone. Carries the
3085/// graph reference so builder methods have everything they need to append
3086/// a new node.
3087#[derive(Debug, Clone)]
3088pub struct NodeHandle {
3089 graph: SharedGraph,
3090 id: NodeId,
3091}
3092
3093impl NodeHandle {
3094 /// Wrap an existing `(graph, node_id)` pair as a NodeHandle handle.
3095 /// Used by graph-rewriting passes (e.g., `opt::insert_copies`)
3096 /// that produce new root `NodeId`s and need to hand them back to
3097 /// call sites as Tensors.
3098 pub fn from_existing(graph: SharedGraph, id: NodeId) -> Self {
3099 Self { graph, id }
3100 }
3101
3102 /// The node ID this handle points to.
3103 pub fn id(&self) -> NodeId {
3104 self.id
3105 }
3106
3107 /// The shared graph this handle belongs to. Exposed so executors and
3108 /// tests can walk the underlying arena.
3109 pub fn graph(&self) -> &SharedGraph {
3110 &self.graph
3111 }
3112
3113 /// This tensor's graph identity — see [`GraphId`].
3114 ///
3115 /// Two tensors can be combined **iff** their `graph_id`s match. Affinity is
3116 /// still *checked* by pointer identity (`Arc::ptr_eq`, which cannot alias);
3117 /// this is the human-readable form, so a failure can say *which* graphs are
3118 /// involved rather than only that they differ.
3119 pub fn graph_id(&self) -> GraphId {
3120 self.graph.read().unwrap().id()
3121 }
3122
3123 /// The shape of this tensor, read from the underlying node.
3124 pub fn shape(&self) -> Shape {
3125 self.graph.read().unwrap().node(self.id).shape.clone()
3126 }
3127
3128 /// The dtype of this tensor, read from the underlying node.
3129 pub fn dtype(&self) -> DType {
3130 self.graph.read().unwrap().node(self.id).dtype
3131 }
3132
3133 /// Phase 7.5 work item G: look up the realized-storage slot for
3134 /// this tensor's node, if any. Returns an Arc clone so the slot
3135 /// stays in the map after this call and the caller's Arc keeps
3136 /// the bytes alive even if a later eviction removes the map
3137 /// entry. `None` means "not realized yet" — the caller should
3138 /// realize the graph first.
3139 pub fn storage_for(&self) -> Option<Arc<RwLock<Storage>>> {
3140 self.graph.read().unwrap().storage_for(self.id)
3141 }
3142
3143 /// The placement hint for this tensor's node, if one was set. `None`
3144 /// means "inherit from the executor's default device."
3145 pub fn placement(&self) -> Option<DeviceLocation> {
3146 self.graph.read().unwrap().placement(self.id)
3147 }
3148
3149 /// Tag this tensor's node with a target device. The executor will
3150 /// validate (post-Phase-1) that the node's op can be evaluated on
3151 /// that device. Returns the same `NodeHandle` handle so this composes
3152 /// with builder-style graph construction:
3153 ///
3154 /// ```ignore
3155 /// let y = a.matmul(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3156 /// ```
3157 pub fn on_device(self, loc: DeviceLocation) -> Self {
3158 self.graph.write().unwrap().set_placement(self.id, loc);
3159 self
3160 }
3161
3162 /// Release this tensor's device-resident storage. Appends an
3163 /// `Op::Release` node whose output is a zero-element marker (shape
3164 /// `[0]`, same dtype as self). Destructive on `self` — after this
3165 /// op runs, `self`'s storage is gone.
3166 ///
3167 /// The ordering-analysis pass (`opt::derive_ordering`, arriving in
3168 /// a follow-up PR) automatically pins the Release to run after
3169 /// every non-destructive reader of `self`. Callers should NOT
3170 /// invoke this directly in a graph that has other readers of
3171 /// `self` until that pass is in place — today's executor has no
3172 /// mechanism to stop them running in the wrong order.
3173 pub fn release(&self) -> Self {
3174 let dtype = self.dtype();
3175 let id = self.graph.write().unwrap().push(Node {
3176 op: Op::Release,
3177 inputs: vec![self.id],
3178 shape: Shape::from_dims(&[0]),
3179 dtype,
3180 });
3181 NodeHandle {
3182 graph: Arc::clone(&self.graph),
3183 id,
3184 }
3185 }
3186
3187 /// Move this tensor's data to `target` device — destroying the
3188 /// source in the process. Appends an `Op::Move` node. The output
3189 /// has the same shape and dtype as the input and lives on
3190 /// `target`; the source's device storage is freed once the op
3191 /// runs.
3192 ///
3193 /// Semantically equivalent to `copy_to_device(target)` followed
3194 /// by dropping the source. Use this when you KNOW the source
3195 /// won't be needed after the transfer — it lets backends skip
3196 /// the intermediate alloc in fast-path cases and lets the
3197 /// scheduler free the source's device memory immediately.
3198 ///
3199 /// If the source may still be read by other ops, use
3200 /// [`Self::copy_to_device`] instead — Copy leaves the source
3201 /// resident.
3202 ///
3203 /// The ordering-analysis pass (`opt::derive_ordering`)
3204 /// automatically pins this op to run after every non-destructive
3205 /// reader of the source. The caller does NOT need to worry about
3206 /// topo ordering — just emit the Move wherever the data-flow
3207 /// says it should go.
3208 pub fn move_to_device(&self, target: DeviceLocation) -> Self {
3209 let shape = self.shape();
3210 let dtype = self.dtype();
3211 let id = self.graph.write().unwrap().push(Node {
3212 op: Op::Move { target },
3213 inputs: vec![self.id],
3214 shape,
3215 dtype,
3216 });
3217 NodeHandle {
3218 graph: Arc::clone(&self.graph),
3219 id,
3220 }
3221 }
3222
3223 /// Copy this tensor's data to `target` device. Source stays
3224 /// resident. Appends an `Op::Copy` node. The output has the same
3225 /// shape and dtype as the input; only residency changes.
3226 ///
3227 /// Same-device copies are still a legal thing to ask for — the
3228 /// backend can optimize them into a cheap clone (or the scheduler
3229 /// can elide the Copy node entirely). Cross-device copies resolve
3230 /// through the pipelined executor's Copy arm (kernel lookup at
3231 /// `(OpKind::Copy, [dt, dt], source backend)`) — today a host
3232 /// round-trip; P2P comes later.
3233 pub fn copy_to_device(&self, target: DeviceLocation) -> Self {
3234 let shape = self.shape();
3235 let dtype = self.dtype();
3236 let id = self.graph.write().unwrap().push(Node {
3237 op: Op::Copy { target },
3238 inputs: vec![self.id],
3239 shape,
3240 dtype,
3241 });
3242 NodeHandle {
3243 graph: Arc::clone(&self.graph),
3244 id,
3245 }
3246 }
3247
3248 /// Project one logical output out of a multi-output producer node.
3249 ///
3250 /// `self` must have been declared as a multi-output producer via
3251 /// [`Graph::set_output_views`] (Session 2's authoring contract will
3252 /// drive this for real fused ops; Session 1 tests drive it
3253 /// directly). The View's output shape, dtype, and layout come from
3254 /// `output_views(self.id)[slot]`. Zero bytes are moved at
3255 /// realization time — the View shares the producer's bundled
3256 /// `Arc<RwLock<Storage>>` and exposes the slot's typed window.
3257 ///
3258 /// **Returns `Result`**: the producer must have declared its slot
3259 /// specs; `slot` must be in range. Errors at graph-build time
3260 /// (per the `validate-at-graph-build-time` rule); the executor
3261 /// never sees a malformed View node.
3262 pub fn view(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3263 let mut graph_w = self.graph.write().unwrap();
3264 let (slot_shape, slot_dtype, slot_byte_offset, slot_layout) = {
3265 let views = graph_w.output_views(self.id).ok_or_else(|| {
3266 fuel_ir::Error::Msg(format!(
3267 "NodeHandle::view: Node#{} is not a multi-output \
3268 producer (no output_views registered)",
3269 self.id.0,
3270 ))
3271 .bt()
3272 })?;
3273 let idx = slot as usize;
3274 let v = views.get(idx).ok_or_else(|| {
3275 fuel_ir::Error::Msg(format!(
3276 "NodeHandle::view: slot {idx} out of range \
3277 (producer has {} slots)",
3278 views.len(),
3279 ))
3280 .bt()
3281 })?;
3282 (v.shape.clone(), v.dtype, v.byte_offset, v.layout.clone())
3283 };
3284 let id = graph_w.push(Node {
3285 op: Op::View { slot },
3286 inputs: vec![self.id],
3287 shape: slot_shape.clone(),
3288 dtype: slot_dtype,
3289 });
3290 // Compose the slot's intrinsic layout (which carries
3291 // slot-relative strides + start_offset) with the slot's
3292 // byte_offset inside the bundle. The result is the layout a
3293 // downstream kernel sees when treating the producer's bundle
3294 // bytes as `slot_dtype` elements: start_offset is in slot-
3295 // dtype-element units; bundle byte_offset is divided by the
3296 // dtype's size_in_bytes to land at the slot's first byte. The
3297 // bundled allocator (`compose_bundle`) aligns each slot's
3298 // byte_offset to its dtype size — so the division is exact.
3299 let dtype_bytes = slot_dtype.size_in_bytes().max(1);
3300 let extra_offset = slot_byte_offset / dtype_bytes;
3301 let effective_layout = if extra_offset == 0 {
3302 slot_layout
3303 } else {
3304 Layout::new(
3305 slot_layout.shape().clone(),
3306 slot_layout.stride().to_vec().into_iter().collect(),
3307 slot_layout.start_offset() + extra_offset,
3308 )
3309 };
3310 // The side-table is set whenever the effective layout differs
3311 // from `Layout::contiguous(slot_shape)` — i.e. whenever the
3312 // slot has a strided layout OR a non-zero composed offset
3313 // (slot 1+ in any bundle).
3314 if effective_layout != Layout::contiguous(slot_shape) {
3315 graph_w.set_layout(id, effective_layout);
3316 }
3317 drop(graph_w);
3318 Ok(NodeHandle {
3319 graph: Arc::clone(&self.graph),
3320 id,
3321 })
3322 }
3323
3324 /// Owned variant of [`Self::view`] — the slot's bytes are copied
3325 /// into a fresh contiguous Storage at realization time, so the
3326 /// producer's bundle Arc can drop independently. Output layout
3327 /// is always contiguous.
3328 ///
3329 /// Same validation as `view`; same error surface.
3330 pub fn view_owned(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3331 let mut graph_w = self.graph.write().unwrap();
3332 let (slot_shape, slot_dtype) = {
3333 let views = graph_w.output_views(self.id).ok_or_else(|| {
3334 fuel_ir::Error::Msg(format!(
3335 "NodeHandle::view_owned: Node#{} is not a multi-output \
3336 producer (no output_views registered)",
3337 self.id.0,
3338 ))
3339 .bt()
3340 })?;
3341 let idx = slot as usize;
3342 let v = views.get(idx).ok_or_else(|| {
3343 fuel_ir::Error::Msg(format!(
3344 "NodeHandle::view_owned: slot {idx} out of range \
3345 (producer has {} slots)",
3346 views.len(),
3347 ))
3348 .bt()
3349 })?;
3350 (v.shape.clone(), v.dtype)
3351 };
3352 let id = graph_w.push(Node {
3353 op: Op::ViewOwned { slot },
3354 inputs: vec![self.id],
3355 shape: slot_shape,
3356 dtype: slot_dtype,
3357 });
3358 drop(graph_w);
3359 Ok(NodeHandle {
3360 graph: Arc::clone(&self.graph),
3361 id,
3362 })
3363 }
3364
3365 /// Append an `Op::WriteSlice` node — copies `source`'s bytes into
3366 /// `self` at the rectangular slab defined by `ranges`. Per-axis,
3367 /// `ranges[i] = (start, end)` is the half-open destination range;
3368 /// `source.dims()[i]` must equal `end - start`, and `end` must
3369 /// not exceed `self.dims()[i]`. Dtypes must match.
3370 ///
3371 /// Destructive on `self`: after the write, `self`'s NodeId is no
3372 /// longer readable (the scheduler pins this op to run after every
3373 /// other reader of `self` via [`opt::derive_ordering`]). The
3374 /// returned tensor adopts `self`'s Storage and Layout; downstream
3375 /// consumers read post-write bytes through this NodeId.
3376 ///
3377 /// Phase E.3.2: introduced to back persistent KV-cache writes
3378 /// (`InferenceContext` + `KvCache`). Non-differentiable.
3379 ///
3380 /// **Returns `Result`**: rank/shape/range mismatches surface as a
3381 /// typed error.
3382 pub fn write_slice(
3383 &self,
3384 source: &NodeHandle,
3385 ranges: Vec<(usize, usize)>,
3386 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3387 self.require_same_graph(source, "write_slice", "source")?;
3388 let dest_shape = self.shape();
3389 let dest_dims = dest_shape.dims();
3390 let src_shape = source.shape();
3391 let src_dims = src_shape.dims();
3392 let rank = dest_dims.len();
3393 if ranges.len() != rank {
3394 return Err(fuel_ir::Error::Msg(format!(
3395 "write_slice: ranges.len() ({}) must equal destination rank ({rank})",
3396 ranges.len(),
3397 ))
3398 .bt());
3399 }
3400 if src_dims.len() != rank {
3401 return Err(fuel_ir::Error::Msg(format!(
3402 "write_slice: source rank ({}) must equal destination rank ({rank})",
3403 src_dims.len(),
3404 ))
3405 .bt());
3406 }
3407 for (i, &(start, end)) in ranges.iter().enumerate() {
3408 if end < start {
3409 return Err(fuel_ir::Error::Msg(format!(
3410 "write_slice: ranges[{i}] = ({start}, {end}) has end < start"
3411 ))
3412 .bt());
3413 }
3414 if end > dest_dims[i] {
3415 return Err(fuel_ir::Error::Msg(format!(
3416 "write_slice: ranges[{i}].end ({end}) > destination dim {i} ({})",
3417 dest_dims[i],
3418 ))
3419 .bt());
3420 }
3421 let slab = end - start;
3422 if src_dims[i] != slab {
3423 return Err(fuel_ir::Error::Msg(format!(
3424 "write_slice: source dim {i} ({}) must equal slab width ({slab}) \
3425 = ranges[{i}].end - ranges[{i}].start",
3426 src_dims[i],
3427 ))
3428 .bt());
3429 }
3430 }
3431 if self.dtype() != source.dtype() {
3432 return Err(fuel_ir::Error::Msg(format!(
3433 "write_slice: dtype mismatch — destination {:?} vs source {:?}",
3434 self.dtype(),
3435 source.dtype(),
3436 ))
3437 .bt());
3438 }
3439 let dtype = self.dtype();
3440 let id = self.graph.write().unwrap().push(Node {
3441 op: Op::WriteSlice {
3442 ranges,
3443 dyn_offset: None,
3444 },
3445 inputs: vec![self.id, source.id],
3446 shape: dest_shape,
3447 dtype,
3448 });
3449 Ok(NodeHandle {
3450 graph: Arc::clone(&self.graph),
3451 id,
3452 })
3453 }
3454
3455 /// Append an `Op::WriteSlice` whose start on `dyn_axis` is a runtime
3456 /// value resolved through the per-pass [`fuel_ir::SymEnv`] at
3457 /// realize, rather than the build-time `ranges[dyn_axis].0`.
3458 ///
3459 /// This is the **input-determined** dynamic-offset path (a
3460 /// [`DynScalar`] over the one `SymEnv`), distinct from
3461 /// [`Self::write_slice_rotating`]'s **data-determined** position (a
3462 /// tensor input read mid-pass). It backs the persistent decode
3463 /// KV-cache write: the append offset is `cached_len`, a per-token
3464 /// runtime value over a fixed-capacity buffer, so the graph
3465 /// structure (and every shape) stays identical across tokens and the
3466 /// plan is reused (Phase D symbolic extents).
3467 ///
3468 /// On `dyn_axis`, `ranges[dyn_axis].0` is ignored (the start is
3469 /// dynamic) and `ranges[dyn_axis].1 - ranges[dyn_axis].0` is the slab
3470 /// width, which must equal `source.dims()[dyn_axis]` and not exceed
3471 /// the destination capacity on that axis. On every other axis the
3472 /// same shape contract as [`Self::write_slice`] applies. The runtime
3473 /// `offset + width` is bounds-checked against the destination
3474 /// capacity at realize (a typed error, never a panic).
3475 ///
3476 /// **Returns `Result`**: rank/dtype/axis-bound/width mismatches
3477 /// surface as a typed error at build time.
3478 pub fn write_slice_dyn(
3479 &self,
3480 source: &NodeHandle,
3481 ranges: Vec<(usize, usize)>,
3482 dyn_axis: usize,
3483 offset: DynScalar,
3484 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3485 self.require_same_graph(source, "write_slice_dyn", "source")?;
3486 let dest_shape = self.shape();
3487 let dest_dims = dest_shape.dims();
3488 let src_shape = source.shape();
3489 let src_dims = src_shape.dims();
3490 let rank = dest_dims.len();
3491 if ranges.len() != rank {
3492 return Err(fuel_ir::Error::Msg(format!(
3493 "write_slice_dyn: ranges.len() ({}) must equal destination rank ({rank})",
3494 ranges.len(),
3495 ))
3496 .bt());
3497 }
3498 if src_dims.len() != rank {
3499 return Err(fuel_ir::Error::Msg(format!(
3500 "write_slice_dyn: source rank ({}) must equal destination rank ({rank})",
3501 src_dims.len(),
3502 ))
3503 .bt());
3504 }
3505 if dyn_axis >= rank {
3506 return Err(fuel_ir::Error::Msg(format!(
3507 "write_slice_dyn: dyn_axis ({dyn_axis}) out of bounds for rank {rank}",
3508 ))
3509 .bt());
3510 }
3511 for (i, &(start, end)) in ranges.iter().enumerate() {
3512 if end < start {
3513 return Err(fuel_ir::Error::Msg(format!(
3514 "write_slice_dyn: ranges[{i}] = ({start}, {end}) has end < start"
3515 ))
3516 .bt());
3517 }
3518 let slab = end - start;
3519 if src_dims[i] != slab {
3520 return Err(fuel_ir::Error::Msg(format!(
3521 "write_slice_dyn: source dim {i} ({}) must equal slab width ({slab}) \
3522 = ranges[{i}].end - ranges[{i}].start",
3523 src_dims[i],
3524 ))
3525 .bt());
3526 }
3527 if i == dyn_axis {
3528 // The start on `dyn_axis` is dynamic, so `ranges[i].0`/`.1`
3529 // are not bounded by `dest_dims[i]` here — only the slab
3530 // WIDTH must fit the capacity. The runtime `offset + width`
3531 // is bounds-checked against `dest_dims[i]` at realize.
3532 if slab > dest_dims[i] {
3533 return Err(fuel_ir::Error::Msg(format!(
3534 "write_slice_dyn: dynamic-axis slab width ({slab}) > destination capacity \
3535 dim {i} ({})",
3536 dest_dims[i],
3537 ))
3538 .bt());
3539 }
3540 } else if end > dest_dims[i] {
3541 return Err(fuel_ir::Error::Msg(format!(
3542 "write_slice_dyn: ranges[{i}].end ({end}) > destination dim {i} ({})",
3543 dest_dims[i],
3544 ))
3545 .bt());
3546 }
3547 }
3548 if self.dtype() != source.dtype() {
3549 return Err(fuel_ir::Error::Msg(format!(
3550 "write_slice_dyn: dtype mismatch — destination {:?} vs source {:?}",
3551 self.dtype(),
3552 source.dtype(),
3553 ))
3554 .bt());
3555 }
3556 let dtype = self.dtype();
3557 let id = self.graph.write().unwrap().push(Node {
3558 op: Op::WriteSlice {
3559 ranges,
3560 dyn_offset: Some((dyn_axis, offset)),
3561 },
3562 inputs: vec![self.id, source.id],
3563 shape: dest_shape,
3564 dtype,
3565 });
3566 Ok(NodeHandle {
3567 graph: Arc::clone(&self.graph),
3568 id,
3569 })
3570 }
3571
3572 /// Append an [`Op::WriteSliceRotating`] node — copies `source`'s
3573 /// bytes into `self` at the rectangular slab defined by `ranges`,
3574 /// with the `axis` axis wrapping modulo `modulus`. The dynamic
3575 /// write position comes through `position` (a rank-0 `U32`
3576 /// tensor); the kernel computes `start = position % modulus` and
3577 /// splits the write across the ring boundary if needed.
3578 ///
3579 /// `ranges[axis].0` is ignored (the rotating-axis start is
3580 /// dynamic). `ranges[axis].1 - ranges[axis].0` is the write
3581 /// length on the rotating axis and must equal `source.dims()[axis]`.
3582 /// On every other axis the same shape contract as `write_slice`
3583 /// applies.
3584 ///
3585 /// Destructive on `self`; scheduled like `write_slice`. Backward
3586 /// panics — sliding-window KV-cache writes are forward-only.
3587 ///
3588 /// **Returns `Result`**: rank/dtype/axis-bound/modulus/range
3589 /// mismatches surface as a typed error at build time.
3590 pub fn write_slice_rotating(
3591 &self,
3592 source: &NodeHandle,
3593 position: &NodeHandle,
3594 axis: usize,
3595 modulus: usize,
3596 ranges: Vec<(usize, usize)>,
3597 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3598 self.require_same_graph(source, "write_slice_rotating", "source")?;
3599 self.require_same_graph(position, "write_slice_rotating", "position")?;
3600 let dest_shape = self.shape();
3601 let dest_dims = dest_shape.dims();
3602 let src_shape = source.shape();
3603 let src_dims = src_shape.dims();
3604 let rank = dest_dims.len();
3605 if ranges.len() != rank {
3606 return Err(fuel_ir::Error::Msg(format!(
3607 "write_slice_rotating: ranges.len() ({}) must equal destination rank ({rank})",
3608 ranges.len(),
3609 ))
3610 .bt());
3611 }
3612 if src_dims.len() != rank {
3613 return Err(fuel_ir::Error::Msg(format!(
3614 "write_slice_rotating: source rank ({}) must equal destination rank ({rank})",
3615 src_dims.len(),
3616 ))
3617 .bt());
3618 }
3619 if axis >= rank {
3620 return Err(fuel_ir::Error::Msg(format!(
3621 "write_slice_rotating: axis {axis} out of bounds for rank {rank}",
3622 ))
3623 .bt());
3624 }
3625 if modulus == 0 {
3626 return Err(
3627 fuel_ir::Error::Msg("write_slice_rotating: modulus must be >= 1".into()).bt(),
3628 );
3629 }
3630 if modulus > dest_dims[axis] {
3631 return Err(fuel_ir::Error::Msg(format!(
3632 "write_slice_rotating: modulus ({modulus}) must not exceed destination dim {axis} ({})",
3633 dest_dims[axis],
3634 )).bt());
3635 }
3636 for (i, &(start, end)) in ranges.iter().enumerate() {
3637 if end < start {
3638 return Err(fuel_ir::Error::Msg(format!(
3639 "write_slice_rotating: ranges[{i}] = ({start}, {end}) has end < start"
3640 ))
3641 .bt());
3642 }
3643 let slab = end - start;
3644 if i == axis {
3645 if slab == 0 {
3646 return Err(fuel_ir::Error::Msg(format!(
3647 "write_slice_rotating: ranges[axis={axis}] slab is 0",
3648 ))
3649 .bt());
3650 }
3651 if slab > modulus {
3652 return Err(fuel_ir::Error::Msg(format!(
3653 "write_slice_rotating: rotating-axis write length ({slab}) > modulus ({modulus})",
3654 )).bt());
3655 }
3656 if src_dims[i] != slab {
3657 return Err(fuel_ir::Error::Msg(format!(
3658 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3659 src_dims[i],
3660 ))
3661 .bt());
3662 }
3663 // ranges[axis].1 itself isn't bounded by dest_dims[axis] —
3664 // the kernel wraps the start, so the logical end is meaningless.
3665 // We still require .1 <= modulus to make the slab description
3666 // self-consistent inside the window.
3667 if end > modulus {
3668 return Err(fuel_ir::Error::Msg(format!(
3669 "write_slice_rotating: ranges[axis={axis}].end ({end}) > modulus ({modulus})",
3670 )).bt());
3671 }
3672 } else {
3673 if end > dest_dims[i] {
3674 return Err(fuel_ir::Error::Msg(format!(
3675 "write_slice_rotating: ranges[{i}].end ({end}) > destination dim {i} ({})",
3676 dest_dims[i],
3677 ))
3678 .bt());
3679 }
3680 if src_dims[i] != slab {
3681 return Err(fuel_ir::Error::Msg(format!(
3682 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3683 src_dims[i],
3684 ))
3685 .bt());
3686 }
3687 }
3688 }
3689 if self.dtype() != source.dtype() {
3690 return Err(fuel_ir::Error::Msg(format!(
3691 "write_slice_rotating: dtype mismatch — destination {:?} vs source {:?}",
3692 self.dtype(),
3693 source.dtype(),
3694 ))
3695 .bt());
3696 }
3697 if position.dtype() != DType::U32 {
3698 return Err(fuel_ir::Error::Msg(format!(
3699 "write_slice_rotating: position must be U32, got {:?}",
3700 position.dtype(),
3701 ))
3702 .bt());
3703 }
3704 if !position.shape().dims().is_empty() {
3705 return Err(fuel_ir::Error::Msg(format!(
3706 "write_slice_rotating: position must be rank-0 scalar, got {:?}",
3707 position.shape().dims(),
3708 ))
3709 .bt());
3710 }
3711 let dtype = self.dtype();
3712 let id = self.graph.write().unwrap().push(Node {
3713 op: Op::WriteSliceRotating {
3714 axis,
3715 modulus,
3716 ranges,
3717 },
3718 inputs: vec![self.id, source.id, position.id],
3719 shape: dest_shape,
3720 dtype,
3721 });
3722 Ok(NodeHandle {
3723 graph: Arc::clone(&self.graph),
3724 id,
3725 })
3726 }
3727
3728 /// Append an [`Op::WriteSliceDoff`] node — copies `source`'s bytes
3729 /// into `self` at the rectangular slab defined by `ranges`, with
3730 /// the start on `axis` read from `offset` (a rank-0 `I64` tensor)
3731 /// **device-side** at kernel launch. No modulo wrap: `offset` is
3732 /// the raw start on `axis`.
3733 ///
3734 /// `ranges[axis].0` is ignored (the dynamic-axis start is device-
3735 /// resident). `ranges[axis].1 - ranges[axis].0` is the write width
3736 /// on `axis` and must equal `source.dims()[axis]`. On every other
3737 /// axis the same shape contract as [`write_slice`](Self::write_slice)
3738 /// applies.
3739 ///
3740 /// **Bounds are the caller's contract**: `offset` is device-only at
3741 /// build time, so `offset + width <= dest_dims[axis]` cannot be
3742 /// checked here and the kernel does NOT clamp. The caller must size
3743 /// `self`'s capacity on `axis` to cover the largest offset (this is
3744 /// the CUDA-graph-capturable KV-cache append; `DecodeSession` sizes
3745 /// `max_seq`). The static slab width IS checked against capacity.
3746 ///
3747 /// Destructive on `self`; scheduled like `write_slice`. Backward
3748 /// panics — decode-time KV-cache appends are forward-only.
3749 ///
3750 /// **Returns `Result`**: rank / dtype / axis-bound / static-width /
3751 /// offset-dtype mismatches surface as a typed error at build time.
3752 pub fn write_slice_doff(
3753 &self,
3754 source: &NodeHandle,
3755 offset: &NodeHandle,
3756 axis: usize,
3757 ranges: Vec<(usize, usize)>,
3758 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3759 self.require_same_graph(source, "write_slice_doff", "source")?;
3760 self.require_same_graph(offset, "write_slice_doff", "offset")?;
3761 let dest_shape = self.shape();
3762 let dest_dims = dest_shape.dims();
3763 let src_dims = source.shape().dims().to_vec();
3764 let rank = dest_dims.len();
3765 if ranges.len() != rank {
3766 return Err(fuel_ir::Error::Msg(format!(
3767 "write_slice_doff: ranges.len() ({}) must equal destination rank ({rank})",
3768 ranges.len(),
3769 ))
3770 .bt());
3771 }
3772 if src_dims.len() != rank {
3773 return Err(fuel_ir::Error::Msg(format!(
3774 "write_slice_doff: source rank ({}) must equal destination rank ({rank})",
3775 src_dims.len(),
3776 ))
3777 .bt());
3778 }
3779 if axis >= rank {
3780 return Err(fuel_ir::Error::Msg(format!(
3781 "write_slice_doff: axis {axis} out of bounds for rank {rank}",
3782 ))
3783 .bt());
3784 }
3785 for (i, &(start, end)) in ranges.iter().enumerate() {
3786 if end < start {
3787 return Err(fuel_ir::Error::Msg(format!(
3788 "write_slice_doff: ranges[{i}] = ({start}, {end}) has end < start"
3789 ))
3790 .bt());
3791 }
3792 let slab = end - start;
3793 if i == axis {
3794 if slab == 0 {
3795 return Err(fuel_ir::Error::Msg(format!(
3796 "write_slice_doff: ranges[axis={axis}] slab is 0",
3797 ))
3798 .bt());
3799 }
3800 // The write width can't exceed the buffer capacity on
3801 // `axis` even at offset 0 (the offset itself is dynamic
3802 // and bounds-checked device-side by the caller's sizing).
3803 if slab > dest_dims[axis] {
3804 return Err(fuel_ir::Error::Msg(format!(
3805 "write_slice_doff: dynamic-axis write width ({slab}) > destination dim {axis} ({})",
3806 dest_dims[axis],
3807 )).bt());
3808 }
3809 if src_dims[i] != slab {
3810 return Err(fuel_ir::Error::Msg(format!(
3811 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3812 src_dims[i],
3813 ))
3814 .bt());
3815 }
3816 } else {
3817 if end > dest_dims[i] {
3818 return Err(fuel_ir::Error::Msg(format!(
3819 "write_slice_doff: ranges[{i}].end ({end}) > destination dim {i} ({})",
3820 dest_dims[i],
3821 ))
3822 .bt());
3823 }
3824 if src_dims[i] != slab {
3825 return Err(fuel_ir::Error::Msg(format!(
3826 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3827 src_dims[i],
3828 ))
3829 .bt());
3830 }
3831 }
3832 }
3833 if self.dtype() != source.dtype() {
3834 return Err(fuel_ir::Error::Msg(format!(
3835 "write_slice_doff: dtype mismatch — destination {:?} vs source {:?}",
3836 self.dtype(),
3837 source.dtype(),
3838 ))
3839 .bt());
3840 }
3841 if offset.dtype() != DType::I64 {
3842 return Err(fuel_ir::Error::Msg(format!(
3843 "write_slice_doff: offset must be I64 (device-resident start), got {:?}",
3844 offset.dtype(),
3845 ))
3846 .bt());
3847 }
3848 if !offset.shape().dims().is_empty() {
3849 return Err(fuel_ir::Error::Msg(format!(
3850 "write_slice_doff: offset must be rank-0 scalar, got {:?}",
3851 offset.shape().dims(),
3852 ))
3853 .bt());
3854 }
3855 let dtype = self.dtype();
3856 let id = self.graph.write().unwrap().push(Node {
3857 op: Op::WriteSliceDoff { axis, ranges },
3858 inputs: vec![self.id, source.id, offset.id],
3859 shape: dest_shape,
3860 dtype,
3861 });
3862 Ok(NodeHandle {
3863 graph: Arc::clone(&self.graph),
3864 id,
3865 })
3866 }
3867
3868 /// Build a `Const` tensor from an `f32` slice and shape on a fresh
3869 /// graph. The new graph is returned via the tensor's `graph` handle.
3870 ///
3871 /// `data` takes `impl Into<Arc<[f32]>>` so both `Vec<f32>` (one-time
3872 /// conversion at the call site) and `Arc<[f32]>` (free clone that
3873 /// shares buffers across forward passes) work.
3874 ///
3875 /// Phase 7.5 work item G2: `device` is the device on which the
3876 /// realized Storage is allocated. The graph's storage_map slot is
3877 /// populated with that Storage and `Op::Const` is emitted —
3878 /// no host-side `ConstData` payload rides on the node.
3879 pub fn from_f32(
3880 data: impl Into<Arc<[f32]>>,
3881 shape: impl Into<Shape>,
3882 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3883 ) -> Result<Self, fuel_ir::Error> {
3884 let v: Arc<[f32]> = data.into();
3885 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
3886 Self::from_host_buffer(buf, DType::F32, shape, device)
3887 }
3888
3889 /// Build a `Const` tensor from an `f64` slice and shape on a fresh graph.
3890 /// `device` selects where the realized Storage is allocated.
3891 pub fn from_f64(
3892 data: impl Into<Arc<[f64]>>,
3893 shape: impl Into<Shape>,
3894 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3895 ) -> Result<Self, fuel_ir::Error> {
3896 let v: Arc<[f64]> = data.into();
3897 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
3898 Self::from_host_buffer(buf, DType::F64, shape, device)
3899 }
3900
3901 /// Build a `Const` tensor from a `bf16` slice and shape on a fresh graph.
3902 /// `device` selects where the realized Storage is allocated.
3903 pub fn from_bf16(
3904 data: impl Into<Arc<[bf16]>>,
3905 shape: impl Into<Shape>,
3906 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3907 ) -> Result<Self, fuel_ir::Error> {
3908 let v: Arc<[bf16]> = data.into();
3909 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
3910 Self::from_host_buffer(buf, DType::BF16, shape, device)
3911 }
3912
3913 /// Build a `Const` tensor from an `f16` slice and shape on a fresh graph.
3914 /// `device` selects where the realized Storage is allocated.
3915 pub fn from_f16(
3916 data: impl Into<Arc<[f16]>>,
3917 shape: impl Into<Shape>,
3918 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3919 ) -> Result<Self, fuel_ir::Error> {
3920 let v: Arc<[f16]> = data.into();
3921 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
3922 Self::from_host_buffer(buf, DType::F16, shape, device)
3923 }
3924
3925 /// Build a `Const` tensor from a `u32` slice and shape on a fresh
3926 /// graph. Primarily used to construct index tensors for gather /
3927 /// scatter / index_select. `u32` is the index type all real fuel
3928 /// backends use (Candle CPU, CUDA, Metal), so keeping the reference
3929 /// on the same type means oracle-equivalence tests do not need any
3930 /// index-type translation. `device` selects where the realized
3931 /// Storage is allocated.
3932 pub fn from_u32(
3933 data: impl Into<Arc<[u32]>>,
3934 shape: impl Into<Shape>,
3935 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3936 ) -> Result<Self, fuel_ir::Error> {
3937 let v: Arc<[u32]> = data.into();
3938 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
3939 Self::from_host_buffer(buf, DType::U32, shape, device)
3940 }
3941
3942 /// G2 internal funnel: allocate Storage on `device` from `buf`,
3943 /// register the slot, emit `Op::Const`. Per-dtype `from_*` methods
3944 /// delegate here.
3945 fn from_host_buffer(
3946 buf: fuel_ir::HostBuffer,
3947 dtype: DType,
3948 shape: impl Into<Shape>,
3949 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3950 ) -> Result<Self, fuel_ir::Error> {
3951 let graph = Arc::new(RwLock::new(Graph::new()));
3952 Self::from_host_buffer_on(&graph, buf, dtype, shape, device)
3953 }
3954
3955 /// `from_host_buffer` against an **existing** graph — the shared body of the
3956 /// `from_*_on` family. Identical to `from_host_buffer` except that the caller
3957 /// supplies the graph instead of one being minted.
3958 fn from_host_buffer_on(
3959 graph: &SharedGraph,
3960 buf: fuel_ir::HostBuffer,
3961 dtype: DType,
3962 shape: impl Into<Shape>,
3963 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3964 ) -> Result<Self, fuel_ir::Error> {
3965 let shape = shape.into();
3966 let n = host_buffer_elem_count(&buf);
3967 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM because
3968 // `docs/gaps.md` and `CLAUDE.md` both anchor on it -- a prose anchor is
3969 // rename-proof, so changing the words here would orphan two citations
3970 // that no identifier rename could have touched.
3971 if n != shape.elem_count() {
3972 return Err(fuel_ir::Error::Msg(format!(
3973 "NodeHandle::from_*: data length {n} does not match shape element count {}",
3974 shape.elem_count(),
3975 )));
3976 }
3977 // GAP-003: was `.expect(...)`. This is the sibling panic the row's
3978 // anchor could not see -- it carries a DIFFERENT message, and a
3979 // message-specific anchor is blind to exactly that.
3980 let backend_storage = device
3981 .storage_from_host_buffer_owned_dyn(buf)
3982 .map_err(|e| {
3983 fuel_ir::Error::Msg(format!(
3984 "NodeHandle::from_*: device.storage_from_host_buffer_owned_dyn failed: {e}"
3985 ))
3986 })?;
3987 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
3988 let id = {
3989 let mut g = graph.write().unwrap();
3990 let id = g.push(Node {
3991 op: Op::Const,
3992 inputs: vec![],
3993 shape,
3994 dtype,
3995 });
3996 g.set_storage(id, storage_arc);
3997 id
3998 };
3999 Ok(Self {
4000 graph: Arc::clone(graph),
4001 id,
4002 })
4003 }
4004
4005 /// Build an `f32` `Const` leaf **on the graph you pass in**, rather than on a
4006 /// fresh one.
4007 ///
4008 /// This is the non-anchor route for adding a tensor to an existing graph.
4009 /// `NodeHandle::from_f32` mints a NEW graph, so two `from_*` tensors can never be
4010 /// combined; `from_f32_on` puts the new leaf on `graph`, and
4011 /// [`const_f32_like`](Self::const_f32_like) does the same thing when what you
4012 /// have to hand is a sibling *tensor* rather than the graph itself.
4013 ///
4014 /// ```ignore
4015 /// let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
4016 /// let a = NodeHandle::from_f32_on(&g, a_data, [2, 3], &device);
4017 /// let w = NodeHandle::from_f32_on(&g, w_data, [3, 2], &device);
4018 /// let y = a.matmul(&w); // same graph ✓
4019 /// ```
4020 pub fn from_f32_on(
4021 graph: &SharedGraph,
4022 data: impl Into<Arc<[f32]>>,
4023 shape: impl Into<Shape>,
4024 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4025 ) -> Result<Self, fuel_ir::Error> {
4026 let v: Arc<[f32]> = data.into();
4027 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
4028 Self::from_host_buffer_on(graph, buf, DType::F32, shape, device)
4029 }
4030
4031 /// `f64` sibling of [`from_f32_on`](Self::from_f32_on) — builds on the given
4032 /// graph rather than a fresh one.
4033 pub fn from_f64_on(
4034 graph: &SharedGraph,
4035 data: impl Into<Arc<[f64]>>,
4036 shape: impl Into<Shape>,
4037 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4038 ) -> Result<Self, fuel_ir::Error> {
4039 let v: Arc<[f64]> = data.into();
4040 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
4041 Self::from_host_buffer_on(graph, buf, DType::F64, shape, device)
4042 }
4043
4044 /// `bf16` sibling of [`from_f32_on`](Self::from_f32_on). The common
4045 /// mixed-precision shape — f32 activations, bf16 weights — is exactly this
4046 /// plus [`from_f32_on`](Self::from_f32_on) against one shared graph.
4047 pub fn from_bf16_on(
4048 graph: &SharedGraph,
4049 data: impl Into<Arc<[half::bf16]>>,
4050 shape: impl Into<Shape>,
4051 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4052 ) -> Result<Self, fuel_ir::Error> {
4053 let v: Arc<[half::bf16]> = data.into();
4054 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
4055 Self::from_host_buffer_on(graph, buf, DType::BF16, shape, device)
4056 }
4057
4058 /// `f16` sibling of [`from_f32_on`](Self::from_f32_on).
4059 pub fn from_f16_on(
4060 graph: &SharedGraph,
4061 data: impl Into<Arc<[half::f16]>>,
4062 shape: impl Into<Shape>,
4063 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4064 ) -> Result<Self, fuel_ir::Error> {
4065 let v: Arc<[half::f16]> = data.into();
4066 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
4067 Self::from_host_buffer_on(graph, buf, DType::F16, shape, device)
4068 }
4069
4070 /// `u32` sibling of [`from_f32_on`](Self::from_f32_on) — index tensors for
4071 /// gather/index_select built straight onto the graph they will be used on.
4072 pub fn from_u32_on(
4073 graph: &SharedGraph,
4074 data: impl Into<Arc<[u32]>>,
4075 shape: impl Into<Shape>,
4076 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4077 ) -> Result<Self, fuel_ir::Error> {
4078 let v: Arc<[u32]> = data.into();
4079 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
4080 Self::from_host_buffer_on(graph, buf, DType::U32, shape, device)
4081 }
4082
4083 /// Phase 7.5 work item G2: build a `Const` leaf on a fresh graph
4084 /// whose realized bytes already live in `storage`. The graph's
4085 /// storage_map slot for the new node is populated with `storage`
4086 /// directly. The executor's slot-first dispatch returns the slot's
4087 /// Arc on realize.
4088 pub fn from_storage(
4089 storage: Arc<RwLock<Storage>>,
4090 shape: impl Into<Shape>,
4091 dtype: DType,
4092 ) -> Self {
4093 let shape = shape.into();
4094 // Sanity-check the slot's dtype matches the declared dtype.
4095 // The slot's bytes don't carry a logical shape — that's the
4096 // node's job — so we don't validate elem_count here.
4097 debug_assert_eq!(
4098 storage.read().unwrap().dtype(),
4099 dtype,
4100 "NodeHandle::from_storage: declared dtype {:?} does not match storage dtype {:?}",
4101 dtype,
4102 storage.read().unwrap().dtype(),
4103 );
4104 let graph = Arc::new(RwLock::new(Graph::new()));
4105 let id = {
4106 let mut g = graph.write().unwrap();
4107 let id = g.push(Node {
4108 op: Op::Const,
4109 inputs: vec![],
4110 shape,
4111 dtype,
4112 });
4113 g.set_storage(id, storage);
4114 id
4115 };
4116 Self { graph, id }
4117 }
4118
4119 /// Build a second `Const` tensor that lives on the same graph as
4120 /// `self`. Use this to add more inputs to an existing computation.
4121 ///
4122 /// Phase 7.5 G2: the realized Storage is allocated on the device
4123 /// derived from `self`'s graph (any existing slot's device — the
4124 /// graph always has at least one slot-bearing leaf by the time
4125 /// const_*_like is called). For cross-device const construction,
4126 /// build a fresh graph with [`NodeHandle::from_f32`] and link via
4127 /// [`Op::Move`] / [`Op::Copy`].
4128 pub fn const_f32_like(
4129 &self,
4130 data: impl Into<Arc<[f32]>>,
4131 shape: impl Into<Shape>,
4132 ) -> Result<Self, fuel_ir::Error> {
4133 let v: Arc<[f32]> = data.into();
4134 self.const_like_host_buffer(fuel_ir::HostBuffer::F32(v.to_vec()), DType::F32, shape)
4135 }
4136
4137 /// Build a second `Const f64` tensor on the same graph as `self`.
4138 pub fn const_f64_like(
4139 &self,
4140 data: impl Into<Arc<[f64]>>,
4141 shape: impl Into<Shape>,
4142 ) -> Result<Self, fuel_ir::Error> {
4143 let v: Arc<[f64]> = data.into();
4144 self.const_like_host_buffer(fuel_ir::HostBuffer::F64(v.to_vec()), DType::F64, shape)
4145 }
4146
4147 /// Build a second `Const bf16` tensor on the same graph as `self`.
4148 pub fn const_bf16_like(
4149 &self,
4150 data: impl Into<Arc<[bf16]>>,
4151 shape: impl Into<Shape>,
4152 ) -> Result<Self, fuel_ir::Error> {
4153 let v: Arc<[bf16]> = data.into();
4154 self.const_like_host_buffer(fuel_ir::HostBuffer::BF16(v.to_vec()), DType::BF16, shape)
4155 }
4156
4157 /// Build a second `Const f16` tensor on the same graph as `self`.
4158 pub fn const_f16_like(
4159 &self,
4160 data: impl Into<Arc<[f16]>>,
4161 shape: impl Into<Shape>,
4162 ) -> Result<Self, fuel_ir::Error> {
4163 let v: Arc<[f16]> = data.into();
4164 self.const_like_host_buffer(fuel_ir::HostBuffer::F16(v.to_vec()), DType::F16, shape)
4165 }
4166
4167 /// Build a second `Const u32` (index) tensor on the same graph as `self`.
4168 pub fn const_u32_like(
4169 &self,
4170 data: impl Into<Arc<[u32]>>,
4171 shape: impl Into<Shape>,
4172 ) -> Result<Self, fuel_ir::Error> {
4173 let v: Arc<[u32]> = data.into();
4174 self.const_like_host_buffer(fuel_ir::HostBuffer::U32(v.to_vec()), DType::U32, shape)
4175 }
4176
4177 /// Build a sibling U8 `Const` on the same graph. Used by
4178 /// byte-stream inputs (e.g. NF4 quantized weights packed two
4179 /// codes per byte).
4180 pub fn const_u8_like(
4181 &self,
4182 data: impl Into<Arc<[u8]>>,
4183 shape: impl Into<Shape>,
4184 ) -> Result<Self, fuel_ir::Error> {
4185 let v: Arc<[u8]> = data.into();
4186 self.const_like_host_buffer(fuel_ir::HostBuffer::U8(v.to_vec()), DType::U8, shape)
4187 }
4188
4189 /// Build a sibling I64 `Const` on the same graph. Used by
4190 /// integer-target ops (e.g. cross-entropy with class indices in
4191 /// PyTorch convention).
4192 pub fn const_i64_like(
4193 &self,
4194 data: impl Into<Arc<[i64]>>,
4195 shape: impl Into<Shape>,
4196 ) -> Result<Self, fuel_ir::Error> {
4197 let v: Arc<[i64]> = data.into();
4198 self.const_like_host_buffer(fuel_ir::HostBuffer::I64(v.to_vec()), DType::I64, shape)
4199 }
4200
4201 /// G2 internal funnel for the per-graph const_*_like family. The
4202 /// device is derived from `self`'s graph slot (any existing one)
4203 /// so callers don't have to thread a device through hot paths
4204 /// like RoPE table construction or LoRA application — the const
4205 /// goes on the same device as the graph it joins.
4206 fn const_like_host_buffer(
4207 &self,
4208 buf: fuel_ir::HostBuffer,
4209 dtype: DType,
4210 shape: impl Into<Shape>,
4211 ) -> Result<Self, fuel_ir::Error> {
4212 let shape = shape.into();
4213 let n = host_buffer_elem_count(&buf);
4214 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM -- gaps.md
4215 // and CLAUDE.md both anchor on this prose, and a prose anchor is the one
4216 // an identifier rename cannot reach.
4217 if n != shape.elem_count() {
4218 return Err(fuel_ir::Error::Msg(format!(
4219 "const_*_like: data length {n} does not match shape element count {}",
4220 shape.elem_count(),
4221 )));
4222 }
4223 let device = pick_device_from_graph(&self.graph);
4224 // GAP-003: the sibling panic, converted with it -- the same pair
4225 // `from_host_buffer_on` had, and the second anchor the row named.
4226 let backend_storage = device
4227 .storage_from_host_buffer_owned_dyn(buf)
4228 .map_err(|e| {
4229 fuel_ir::Error::Msg(format!(
4230 "NodeHandle::const_like: device.storage_from_host_buffer_owned_dyn failed: {e}"
4231 ))
4232 })?;
4233 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
4234 let id = {
4235 let mut g = self.graph.write().unwrap();
4236 let id = g.push(Node {
4237 op: Op::Const,
4238 inputs: vec![],
4239 shape,
4240 dtype,
4241 });
4242 g.set_storage(id, storage_arc);
4243 id
4244 };
4245 Ok(Self {
4246 graph: self.graph.clone(),
4247 id,
4248 })
4249 }
4250
4251 /// Push a `Const` node on the same graph as `self` **without**
4252 /// populating the graph's storage_map. The caller is responsible
4253 /// for binding the storage Arc into the realize call's initial
4254 /// StorageCache, typically via
4255 /// [`InferenceContext::insert`](../fuel_core/inference_context/struct.InferenceContext.html#method.insert).
4256 ///
4257 /// Used by the Phase 7.6 step 9c E.3.3 forward path to bind
4258 /// pre-allocated KV-cache storage Arcs (held as the new
4259 /// `Arc<RwLock<fuel_memory::Storage>>` type, not the legacy
4260 /// `fuel_backend_contract::Storage` that `const_like_from_storage` takes)
4261 /// into a per-step graph without re-uploading or type-converting.
4262 ///
4263 /// **Caller contract**: the same NodeId must appear in the
4264 /// `initial` StorageCache passed to the realize call. If not, the
4265 /// executor surfaces a clean error pointing at the missing slot
4266 /// — there's no implicit fallback to `graph.storage_map`.
4267 pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: DType) -> Self {
4268 let shape = shape.into();
4269 let id = {
4270 let mut g = self.graph.write().unwrap();
4271 g.push(Node {
4272 op: Op::Const,
4273 inputs: vec![],
4274 shape,
4275 dtype,
4276 })
4277 };
4278 Self {
4279 graph: self.graph.clone(),
4280 id,
4281 }
4282 }
4283
4284 /// Phase 7.5 work item G2: build a second `Const` leaf on the same
4285 /// graph as `self` whose realized bytes already live in `storage`.
4286 /// Companion to [`NodeHandle::from_storage`] for the multi-input case.
4287 pub fn const_like_from_storage(
4288 &self,
4289 storage: Arc<RwLock<Storage>>,
4290 shape: impl Into<Shape>,
4291 dtype: DType,
4292 ) -> Self {
4293 let shape = shape.into();
4294 debug_assert_eq!(
4295 storage.read().unwrap().dtype(),
4296 dtype,
4297 "NodeHandle::const_like_from_storage: declared dtype {:?} does not match storage dtype {:?}",
4298 dtype,
4299 storage.read().unwrap().dtype(),
4300 );
4301 let id = {
4302 let mut g = self.graph.write().unwrap();
4303 let id = g.push(Node {
4304 op: Op::Const,
4305 inputs: vec![],
4306 shape,
4307 dtype,
4308 });
4309 g.set_storage(id, storage);
4310 id
4311 };
4312 Self {
4313 graph: self.graph.clone(),
4314 id,
4315 }
4316 }
4317
4318 /// Append an `Add` node `self + other` to the shared graph and return
4319 /// a handle to the result. Requires matching shapes and matching
4320 /// graphs.
4321 ///
4322 /// # Panics
4323 ///
4324 /// Panics if any operand belongs to a different [`Graph`] than the one this
4325 /// builder is building into. Operand identity is graph-scoped and checked by
4326 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4327 /// deliberate and replaces the hang a cross-graph handle used to produce.
4328 /// Build every operand from one graph, or use a `Result`-returning entry
4329 /// point where one exists.
4330 pub fn add(&self, other: &NodeHandle) -> NodeHandle {
4331 self.binary_op("add", Op::Add, other, self.shape())
4332 }
4333
4334 /// Append a `Mul` node `self * other`.
4335 ///
4336 /// # Panics
4337 ///
4338 /// Panics if any operand belongs to a different [`Graph`] than the one this
4339 /// builder is building into. Operand identity is graph-scoped and checked by
4340 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4341 /// deliberate and replaces the hang a cross-graph handle used to produce.
4342 /// Build every operand from one graph, or use a `Result`-returning entry
4343 /// point where one exists.
4344 pub fn mul(&self, other: &NodeHandle) -> NodeHandle {
4345 self.binary_op("mul", Op::Mul, other, self.shape())
4346 }
4347
4348 /// Append a `MatMul` node. Both operands must have rank ≥ 2. The
4349 /// last two dims are the matrix dims; leading dims are batch dims.
4350 ///
4351 /// - If both operands have the same rank, their batch dims must
4352 /// match exactly.
4353 /// - If one operand is rank-2 and the other is higher rank, the
4354 /// rank-2 operand is auto-broadcast to match the higher-rank
4355 /// operand's batch prefix. This is the common "linear layer
4356 /// across a batch" pattern (`[batch, seq, d_model] @ [d_model, d_out]`).
4357 /// - Any other rank combination panics; users must reshape first.
4358 ///
4359 /// Shape examples:
4360 /// - `[m, k] @ [k, n]` → `[m, n]`
4361 /// - `[batch, m, k] @ [batch, k, n]` → `[batch, m, n]`
4362 /// - `[batch, seq, k] @ [k, n]` → `[batch, seq, n]` (rhs auto-broadcast)
4363 /// - `[k, n]` @ `[batch, n, m]` → `[batch, k, m]` (lhs auto-broadcast)
4364 ///
4365 /// # Panics
4366 ///
4367 /// Panics if any operand belongs to a different [`Graph`] than the one this
4368 /// builder is building into. Operand identity is graph-scoped and checked by
4369 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4370 /// deliberate and replaces the hang a cross-graph handle used to produce.
4371 /// Build every operand from one graph, or use a `Result`-returning entry
4372 /// point where one exists.
4373 pub fn matmul(&self, other: &NodeHandle) -> NodeHandle {
4374 assert!(
4375 Arc::ptr_eq(&self.graph, &other.graph),
4376 "matmul: tensors must live on the same graph — lhs is on graph #{}, rhs on graph \
4377 #{}; each `from_*` constructor mints a NEW graph, so build `other` on this \
4378 tensor's graph with `from_f32_on(self.graph(), ..)` or `const_*_like`",
4379 self.graph_id(),
4380 other.graph_id(),
4381 );
4382 // Mixed-precision matmul: activations stay in their native
4383 // dtype while weights can live as a lower-precision type on
4384 // device. Currently supported: (F32 × BF16) → F32 for bf16-
4385 // quantized LLM serving. Other heterogeneous combinations
4386 // are rejected.
4387 let dtypes_ok = self.dtype() == other.dtype()
4388 || (self.dtype() == DType::F32 && other.dtype() == DType::BF16);
4389 assert!(
4390 dtypes_ok,
4391 "matmul: unsupported dtype combination: lhs={:?}, rhs={:?}",
4392 self.dtype(),
4393 other.dtype(),
4394 );
4395 let l = self.shape();
4396 let r = other.shape();
4397 let ld = l.dims();
4398 let rd = r.dims();
4399 assert!(
4400 ld.len() >= 2 && rd.len() >= 2,
4401 "matmul: both operands must be rank ≥ 2, got {ld:?} and {rd:?}",
4402 );
4403
4404 // Auto-broadcast the rank-2 operand against the other's batch
4405 // prefix. If ranks already match, this is a no-op.
4406 let (lhs, rhs) = if ld.len() == rd.len() {
4407 (self.clone(), other.clone())
4408 } else if ld.len() == 2 && rd.len() > 2 {
4409 let mut bc_shape: Vec<usize> = rd[..rd.len() - 2].to_vec();
4410 bc_shape.push(ld[0]);
4411 bc_shape.push(ld[1]);
4412 (
4413 self.broadcast_to(Shape::from_dims(&bc_shape)),
4414 other.clone(),
4415 )
4416 } else if rd.len() == 2 && ld.len() > 2 {
4417 let mut bc_shape: Vec<usize> = ld[..ld.len() - 2].to_vec();
4418 bc_shape.push(rd[0]);
4419 bc_shape.push(rd[1]);
4420 (
4421 self.clone(),
4422 other.broadcast_to(Shape::from_dims(&bc_shape)),
4423 )
4424 } else {
4425 panic!(
4426 "matmul: unsupported rank combination {} vs {} — only same-rank or (rank-2 × higher-rank) is supported; reshape first",
4427 ld.len(),
4428 rd.len(),
4429 );
4430 };
4431
4432 // Now both operands have the same rank. Validate batch prefix
4433 // and build the output node.
4434 let lhs_shape = lhs.shape();
4435 let rhs_shape = rhs.shape();
4436 let l = lhs_shape.dims();
4437 let r = rhs_shape.dims();
4438 let rank = l.len();
4439 let batch_rank = rank - 2;
4440 for i in 0..batch_rank {
4441 // GQA-style matmul: A may have more batch heads than B
4442 // (e.g. Q[1,32,1,64] @ K^T[1,4,64,S]). The n_rep factor
4443 // is inferred by the backend at dispatch time; at the
4444 // graph level we just validate divisibility.
4445 let (la, ra) = (l[i], r[i]);
4446 let ok = la == ra || (la > ra && ra > 0 && la % ra == 0);
4447 assert!(
4448 ok,
4449 "matmul: batch dim mismatch at axis {i}: {la} vs {ra} (not equal and not a GQA-divisible pair)",
4450 );
4451 }
4452 let k = l[rank - 1];
4453 let k2 = r[rank - 2];
4454 assert_eq!(k, k2, "matmul: inner dim mismatch (lhs k={k}, rhs k={k2})",);
4455 // Output shape + dtype now flow from primitive_shape (the single source
4456 // of truth); the same-rank operands + validated batch prefix / inner
4457 // dim above guarantee it infers cleanly. (The GQA batch-prefix carry
4458 // uses lhs's batch dims, matching primitive_shape's `l[..rank-2]`.)
4459 let (shape, dtype) = crate::shape::primitive_shape(
4460 &Op::MatMul,
4461 &[lhs_shape.clone(), rhs_shape.clone()],
4462 &[lhs.dtype(), rhs.dtype()],
4463 )
4464 .expect("matmul: operands validated (same-rank, inner dim) before primitive_shape");
4465 let id = self.graph.write().unwrap().push(Node {
4466 op: Op::MatMul,
4467 inputs: vec![lhs.id, rhs.id],
4468 shape,
4469 dtype,
4470 });
4471 Self {
4472 graph: self.graph.clone(),
4473 id,
4474 }
4475 }
4476
4477 /// Data-determined-M matmul: like [`Self::matmul`], but the LHS row
4478 /// count `M` is a **runtime** value `row_count` rather than the static
4479 /// `lhs.shape[-2]`. The LHS and output are **capacity buffers** of
4480 /// `lhs.shape[-2]` rows; only `row_count` rows are computed, the rest
4481 /// left zeroed. This is the sparse-MoE expert-FFN primitive — gather an
4482 /// expert's `count_e` routed tokens into a capacity buffer, then
4483 /// compute exactly `count_e` FFN rows (the FLOP saving). `row_count`
4484 /// resolves at compile if input-determined, else at execute from the
4485 /// producer-bound `SymEnv` (e.g. `Op::NonZeroIndices`'s count). The
4486 /// output shape is the capacity shape `[..., lhs.shape[-2], n]`.
4487 ///
4488 /// # Panics
4489 ///
4490 /// Panics if any operand belongs to a different [`Graph`] than the one this
4491 /// builder is building into. Operand identity is graph-scoped and checked by
4492 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4493 /// deliberate and replaces the hang a cross-graph handle used to produce.
4494 /// Build every operand from one graph, or use a `Result`-returning entry
4495 /// point where one exists.
4496 pub fn matmul_dyn_m(&self, other: &NodeHandle, row_count: DynScalar) -> NodeHandle {
4497 self.assert_same_graph(other, "matmul_dyn_m", "other");
4498 // Only the F32 CPU capacity kernel honors a data-determined row
4499 // count today; other dtypes/backends compute all capacity rows.
4500 // Guard here so a dynamic-M matmul can never be built where it
4501 // would silently over-compute.
4502 assert_eq!(
4503 self.dtype(),
4504 DType::F32,
4505 "matmul_dyn_m: data-determined-M is F32-only today (got lhs {:?})",
4506 self.dtype(),
4507 );
4508 let out = self.matmul(other);
4509 self.graph
4510 .write()
4511 .unwrap()
4512 .set_matmul_row_count(out.id, row_count);
4513 out
4514 }
4515
4516 /// Append an [`Op::Fused`] node carrying
4517 /// [`crate::registry::FusedOpParams::QMatMul`] that multiplies `self` (F32
4518 /// activations, shape `[..., M, K]`) with a Q-type quantized
4519 /// weight matrix of logical shape `[N, K]` stored as a raw byte
4520 /// stream (passed in as a U32 tensor; length = n_bytes / 4).
4521 ///
4522 /// Output shape: `[..., M, N]` F32. The backend dequantizes the
4523 /// weight blocks on the fly inside the matmul kernel, so the
4524 /// quantized blocks stay resident at their compressed size.
4525 ///
4526 /// # Panics
4527 ///
4528 /// Panics if any operand belongs to a different [`Graph`] than the one this
4529 /// builder is building into. Operand identity is graph-scoped and checked by
4530 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4531 /// deliberate and replaces the hang a cross-graph handle used to produce.
4532 /// Build every operand from one graph, or use a `Result`-returning entry
4533 /// point where one exists.
4534 pub fn qmatmul(
4535 &self,
4536 weight_bytes: &NodeHandle,
4537 quant_type: QuantType,
4538 k: usize,
4539 n: usize,
4540 ) -> NodeHandle {
4541 assert!(
4542 Arc::ptr_eq(&self.graph, &weight_bytes.graph),
4543 "qmatmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
4544 );
4545 assert_eq!(
4546 self.dtype(),
4547 DType::F32,
4548 "qmatmul: activations must be F32, got {:?}",
4549 self.dtype(),
4550 );
4551 assert_eq!(
4552 weight_bytes.dtype(),
4553 DType::U32,
4554 "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
4555 weight_bytes.dtype(),
4556 );
4557 let a_dims = self.shape();
4558 let a_dims = a_dims.dims();
4559 assert!(
4560 a_dims.len() >= 2,
4561 "qmatmul: activations must be rank ≥ 2, got {a_dims:?}",
4562 );
4563 assert_eq!(
4564 a_dims[a_dims.len() - 1],
4565 k,
4566 "qmatmul: last dim of activations ({}) must equal k ({k})",
4567 a_dims[a_dims.len() - 1],
4568 );
4569 assert_eq!(
4570 k % quant_type.elements_per_block(),
4571 0,
4572 "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({})",
4573 quant_type.elements_per_block(),
4574 );
4575 // Validate the weight byte count matches [N, K/block_size] blocks.
4576 let expected_bytes =
4577 n * (k / quant_type.elements_per_block()) * quant_type.bytes_per_block();
4578 let expected_u32_elems = expected_bytes / 4;
4579 assert_eq!(
4580 weight_bytes.shape().elem_count(),
4581 expected_u32_elems,
4582 "qmatmul: weight_bytes has {} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
4583 weight_bytes.shape().elem_count(),
4584 );
4585 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
4586 out_dims.push(n);
4587 // Phase 7.6 step 4 (final): emits Op::Fused(QMATMUL, _) per
4588 // the registry split.
4589 let id = self.graph.write().unwrap().push(Node {
4590 op: Op::Fused(
4591 crate::registry::FusedOps::QMATMUL,
4592 crate::registry::FusedOpParams::QMatMul { quant_type, k, n },
4593 ),
4594 inputs: vec![self.id, weight_bytes.id],
4595 shape: Shape::from_dims(&out_dims),
4596 dtype: DType::F32,
4597 });
4598 Self {
4599 graph: self.graph.clone(),
4600 id,
4601 }
4602 }
4603
4604 /// Append an [`Op::Fused`] node carrying
4605 /// [`crate::registry::FusedOpParams::Conv2D`]. `self` must be `[N, Cin, H, W]`
4606 /// (rank 4); `weight` must be `[Cout, Cin/groups, Kh, Kw]` (rank
4607 /// 4) and live on the same graph. `bias` is optional — when
4608 /// present it must be rank 1 with length `Cout`. Returns a rank-4
4609 /// tensor of shape `[N, Cout, Hout, Wout]`.
4610 ///
4611 /// Panics if the input ranks don't match, the channel counts are
4612 /// inconsistent with `groups`, or the output spatial dims would
4613 /// be non-positive.
4614 ///
4615 /// # Panics
4616 ///
4617 /// Panics if any operand belongs to a different [`Graph`] than the one this
4618 /// builder is building into. Operand identity is graph-scoped and checked by
4619 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4620 /// deliberate and replaces the hang a cross-graph handle used to produce.
4621 /// Build every operand from one graph, or use a `Result`-returning entry
4622 /// point where one exists.
4623 pub fn conv2d(
4624 &self,
4625 weight: &NodeHandle,
4626 bias: Option<&NodeHandle>,
4627 stride: (usize, usize),
4628 padding: (usize, usize),
4629 groups: usize,
4630 ) -> NodeHandle {
4631 assert!(
4632 Arc::ptr_eq(&self.graph, &weight.graph),
4633 "conv2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4634 );
4635 if let Some(b) = bias {
4636 assert!(
4637 Arc::ptr_eq(&self.graph, &b.graph),
4638 "conv2d: bias must live on the same graph; use `const_*_like` to build on an existing graph",
4639 );
4640 }
4641 assert!(groups >= 1, "conv2d: groups must be ≥ 1, got {groups}");
4642 let x_dims = self.shape();
4643 let x_dims = x_dims.dims();
4644 let w_dims = weight.shape();
4645 let w_dims = w_dims.dims();
4646 assert_eq!(
4647 x_dims.len(),
4648 4,
4649 "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4650 );
4651 assert_eq!(
4652 w_dims.len(),
4653 4,
4654 "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
4655 );
4656 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4657 let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4658 assert_eq!(
4659 cin,
4660 cin_per_g * groups,
4661 "conv2d: x has {cin} in-channels but weight expects {} ({}·{groups})",
4662 cin_per_g * groups,
4663 cin_per_g,
4664 );
4665 assert_eq!(
4666 cout % groups,
4667 0,
4668 "conv2d: Cout={cout} must be divisible by groups={groups}",
4669 );
4670 if let Some(b) = bias {
4671 let b_dims = b.shape();
4672 let b_dims = b_dims.dims();
4673 assert_eq!(
4674 b_dims,
4675 &[cout],
4676 "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
4677 );
4678 }
4679 // Hout = (H + 2·pad.0 − Kh) / stride.0 + 1
4680 let (stride_h, stride_w) = stride;
4681 let (pad_h, pad_w) = padding;
4682 assert!(stride_h >= 1 && stride_w >= 1, "conv2d: stride must be ≥ 1");
4683 let h_padded = h_in + 2 * pad_h;
4684 let w_padded = w_in + 2 * pad_w;
4685 assert!(
4686 h_padded >= kh && w_padded >= kw,
4687 "conv2d: padded input ({h_padded}×{w_padded}) smaller than kernel ({kh}×{kw})",
4688 );
4689 let h_out = (h_padded - kh) / stride_h + 1;
4690 let w_out = (w_padded - kw) / stride_w + 1;
4691 let dtype = self.dtype();
4692 let mut inputs = vec![self.id, weight.id];
4693 if let Some(b) = bias {
4694 inputs.push(b.id);
4695 }
4696 // Phase 7.6 step 4 (continued): emit
4697 // `Op::Fused(FusedOps::CONV2D, FusedOpParams::Conv2D { … })`
4698 // through the registry-extended arm. The legacy
4699 // `Op::Conv2D { … }` variant remains in the enum during
4700 // migration (Conv2D's backward still constructs inner
4701 // `Op::Fused(CONV2D, _)` nodes; the legacy variant is reached
4702 // only by direct tests until step 5 drops it).
4703 let id = self.graph.write().unwrap().push(Node {
4704 op: Op::Fused(
4705 crate::registry::FusedOps::CONV2D,
4706 crate::registry::FusedOpParams::Conv2D {
4707 stride,
4708 padding,
4709 groups,
4710 },
4711 ),
4712 inputs,
4713 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4714 dtype,
4715 });
4716 Self {
4717 graph: self.graph.clone(),
4718 id,
4719 }
4720 }
4721
4722 /// Append an [`Op::Fused`] node carrying
4723 /// [`crate::registry::FusedOpParams::PagedAttn`]. `self` is the Q tensor of shape
4724 /// `[B, Hq, Sq, D]`; `k_cache` and `v_cache` are the paged caches
4725 /// shaped `[num_blocks, block_size, Hkv, D]`; `block_table` is
4726 /// `[B, max_num_blocks_per_seq]` (u32) mapping logical → physical
4727 /// blocks; `context_lens` is `[B]` (u32) of per-sequence lengths;
4728 /// `alibi_slopes` is the optional `[Hq]` per-head bias.
4729 ///
4730 /// Returns a tensor with `q`'s shape `[B, Hq, Sq, D]`.
4731 ///
4732 /// # Panics
4733 ///
4734 /// Panics if any operand belongs to a different [`Graph`] than the one this
4735 /// builder is building into. Operand identity is graph-scoped and checked by
4736 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4737 /// deliberate and replaces the hang a cross-graph handle used to produce.
4738 /// Build every operand from one graph, or use a `Result`-returning entry
4739 /// point where one exists.
4740 #[allow(clippy::too_many_arguments)]
4741 pub fn paged_attn(
4742 &self,
4743 k_cache: &NodeHandle,
4744 v_cache: &NodeHandle,
4745 block_table: &NodeHandle,
4746 context_lens: &NodeHandle,
4747 alibi_slopes: Option<&NodeHandle>,
4748 softmax_scale: f32,
4749 block_size: usize,
4750 softcap: Option<f32>,
4751 ) -> NodeHandle {
4752 let g = &self.graph;
4753 assert!(
4754 Arc::ptr_eq(g, &k_cache.graph),
4755 "paged_attn: q + k_cache must share graph"
4756 );
4757 assert!(
4758 Arc::ptr_eq(g, &v_cache.graph),
4759 "paged_attn: q + v_cache must share graph"
4760 );
4761 assert!(
4762 Arc::ptr_eq(g, &block_table.graph),
4763 "paged_attn: q + block_table must share graph"
4764 );
4765 assert!(
4766 Arc::ptr_eq(g, &context_lens.graph),
4767 "paged_attn: q + context_lens must share graph"
4768 );
4769 if let Some(a) = alibi_slopes {
4770 assert!(
4771 Arc::ptr_eq(g, &a.graph),
4772 "paged_attn: alibi_slopes must share graph"
4773 );
4774 }
4775 assert!(block_size >= 1, "paged_attn: block_size must be ≥ 1");
4776
4777 let q_dims = self.shape();
4778 let q_dims = q_dims.dims();
4779 let kc_dims = k_cache.shape();
4780 let kc_dims = kc_dims.dims();
4781 let vc_dims = v_cache.shape();
4782 let vc_dims = vc_dims.dims();
4783 let bt_dims = block_table.shape();
4784 let bt_dims = bt_dims.dims();
4785 let cl_dims = context_lens.shape();
4786 let cl_dims = cl_dims.dims();
4787 assert_eq!(
4788 q_dims.len(),
4789 4,
4790 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
4791 );
4792 assert_eq!(
4793 kc_dims.len(),
4794 4,
4795 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}"
4796 );
4797 assert_eq!(
4798 vc_dims.len(),
4799 4,
4800 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}"
4801 );
4802 assert_eq!(
4803 bt_dims.len(),
4804 2,
4805 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}"
4806 );
4807 assert_eq!(
4808 cl_dims.len(),
4809 1,
4810 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}"
4811 );
4812 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
4813 assert_eq!(
4814 kc_dims[1], block_size,
4815 "paged_attn: k_cache block dim {} != block_size {block_size}",
4816 kc_dims[1]
4817 );
4818 assert_eq!(
4819 vc_dims[1], block_size,
4820 "paged_attn: v_cache block dim {} != block_size {block_size}",
4821 vc_dims[1]
4822 );
4823 let hkv = kc_dims[2];
4824 assert_eq!(
4825 vc_dims[2], hkv,
4826 "paged_attn: Hkv mismatch k_cache vs v_cache"
4827 );
4828 assert_eq!(kc_dims[3], d, "paged_attn: D mismatch q vs k_cache");
4829 assert_eq!(vc_dims[3], d, "paged_attn: D mismatch q vs v_cache");
4830 assert_eq!(
4831 hq % hkv,
4832 0,
4833 "paged_attn: Hq={hq} must be a multiple of Hkv={hkv}"
4834 );
4835 assert_eq!(
4836 bt_dims[0], b,
4837 "paged_attn: block_table batch dim {} != B={b}",
4838 bt_dims[0]
4839 );
4840 assert_eq!(
4841 cl_dims[0], b,
4842 "paged_attn: context_lens len {} != B={b}",
4843 cl_dims[0]
4844 );
4845 assert_eq!(
4846 block_table.dtype(),
4847 crate::DType::U32,
4848 "paged_attn: block_table must be U32"
4849 );
4850 assert_eq!(
4851 context_lens.dtype(),
4852 crate::DType::U32,
4853 "paged_attn: context_lens must be U32"
4854 );
4855 if let Some(a) = alibi_slopes {
4856 let ad = a.shape();
4857 let ad = ad.dims();
4858 assert_eq!(
4859 ad,
4860 &[hq],
4861 "paged_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
4862 );
4863 }
4864
4865 let dtype = self.dtype();
4866 let mut inputs = vec![
4867 self.id,
4868 k_cache.id,
4869 v_cache.id,
4870 block_table.id,
4871 context_lens.id,
4872 ];
4873 if let Some(a) = alibi_slopes {
4874 inputs.push(a.id);
4875 }
4876 // Phase 7.6 step 4 (final): emits Op::Fused(PAGED_ATTN, _).
4877 let id = self.graph.write().unwrap().push(Node {
4878 op: Op::Fused(
4879 crate::registry::FusedOps::PAGED_ATTN,
4880 crate::registry::FusedOpParams::PagedAttn {
4881 softmax_scale,
4882 block_size,
4883 softcap,
4884 },
4885 ),
4886 inputs,
4887 shape: Shape::from_dims(q_dims),
4888 dtype,
4889 });
4890 Self {
4891 graph: self.graph.clone(),
4892 id,
4893 }
4894 }
4895
4896 /// Append an [`Op::Fused`] node carrying
4897 /// [`crate::registry::FusedOpParams::ConvTranspose2D`]. `self` must be
4898 /// `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
4899 /// (note transposed channel order vs `conv2d`). Returns a rank-4
4900 /// tensor `[N, Cout, Hout, Wout]`.
4901 ///
4902 /// Panics if ranks don't match, channel counts are inconsistent
4903 /// with `groups`, or output spatial dims would be non-positive.
4904 ///
4905 /// # Panics
4906 ///
4907 /// Panics if any operand belongs to a different [`Graph`] than the one this
4908 /// builder is building into. Operand identity is graph-scoped and checked by
4909 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4910 /// deliberate and replaces the hang a cross-graph handle used to produce.
4911 /// Build every operand from one graph, or use a `Result`-returning entry
4912 /// point where one exists.
4913 pub fn conv_transpose2d(
4914 &self,
4915 weight: &NodeHandle,
4916 stride: (usize, usize),
4917 padding: (usize, usize),
4918 output_padding: (usize, usize),
4919 dilation: (usize, usize),
4920 groups: usize,
4921 ) -> NodeHandle {
4922 assert!(
4923 Arc::ptr_eq(&self.graph, &weight.graph),
4924 "conv_transpose2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4925 );
4926 assert!(
4927 groups >= 1,
4928 "conv_transpose2d: groups must be ≥ 1, got {groups}"
4929 );
4930 let x_dims = self.shape();
4931 let x_dims = x_dims.dims();
4932 let w_dims = weight.shape();
4933 let w_dims = w_dims.dims();
4934 assert_eq!(
4935 x_dims.len(),
4936 4,
4937 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4938 );
4939 assert_eq!(
4940 w_dims.len(),
4941 4,
4942 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
4943 );
4944 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4945 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4946 assert_eq!(
4947 cin, cin_w,
4948 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
4949 );
4950 assert_eq!(
4951 cin % groups,
4952 0,
4953 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
4954 );
4955 let cout = cout_per_g * groups;
4956 let (stride_h, stride_w) = stride;
4957 let (pad_h, pad_w) = padding;
4958 let (out_pad_h, out_pad_w) = output_padding;
4959 let (dil_h, dil_w) = dilation;
4960 assert!(
4961 stride_h >= 1 && stride_w >= 1,
4962 "conv_transpose2d: stride must be ≥ 1"
4963 );
4964 assert!(
4965 dil_h >= 1 && dil_w >= 1,
4966 "conv_transpose2d: dilation must be ≥ 1"
4967 );
4968 // Hout = (Hin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1
4969 let h_out = (h_in.saturating_sub(1)) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
4970 let w_out = (w_in.saturating_sub(1)) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
4971 assert!(
4972 h_out > 2 * pad_h && w_out > 2 * pad_w,
4973 "conv_transpose2d: padding ({pad_h}×{pad_w}) is larger than the produced output dims",
4974 );
4975 let h_out = h_out - 2 * pad_h;
4976 let w_out = w_out - 2 * pad_w;
4977 let dtype = self.dtype();
4978 // Phase 7.6 step 4 (final): emits Op::Fused(CONV_TRANSPOSE2D, _).
4979 let id = self.graph.write().unwrap().push(Node {
4980 op: Op::Fused(
4981 crate::registry::FusedOps::CONV_TRANSPOSE2D,
4982 crate::registry::FusedOpParams::ConvTranspose2D {
4983 stride,
4984 padding,
4985 output_padding,
4986 dilation,
4987 groups,
4988 },
4989 ),
4990 inputs: vec![self.id, weight.id],
4991 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4992 dtype,
4993 });
4994 Self {
4995 graph: self.graph.clone(),
4996 id,
4997 }
4998 }
4999
5000 /// Append a transposed 1D convolution by lifting `self` and
5001 /// `weight` into the rank-4 path and dispatching through
5002 /// [`Self::conv_transpose2d`]. `self` is `[N, Cin, Lin]`;
5003 /// `weight` is `[Cin, Cout/groups, K]` (transposed channel
5004 /// order, matches PyTorch). Returns `[N, Cout, Lout]` where
5005 /// `Lout = (Lin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1`.
5006 ///
5007 /// Used by audio codec models (DAC / EnCodec / SNAC / Mimi /
5008 /// Parler-TTS / MetaVoice / CSM) where the decoder upsamples
5009 /// quantized latents back to waveform with strided transposed
5010 /// convs.
5011 ///
5012 /// # Panics
5013 ///
5014 /// Panics if any operand belongs to a different [`Graph`] than the one this
5015 /// builder is building into. Operand identity is graph-scoped and checked by
5016 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5017 /// deliberate and replaces the hang a cross-graph handle used to produce.
5018 /// Build every operand from one graph, or use a `Result`-returning entry
5019 /// point where one exists.
5020 pub fn conv_transpose1d(
5021 &self,
5022 weight: &NodeHandle,
5023 stride: usize,
5024 padding: usize,
5025 output_padding: usize,
5026 dilation: usize,
5027 groups: usize,
5028 ) -> NodeHandle {
5029 self.assert_same_graph(weight, "conv_transpose1d", "weight");
5030 let x_dims = self.shape();
5031 let x_dims = x_dims.dims();
5032 let w_dims = weight.shape();
5033 let w_dims = w_dims.dims();
5034 assert_eq!(
5035 x_dims.len(),
5036 3,
5037 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
5038 );
5039 assert_eq!(
5040 w_dims.len(),
5041 3,
5042 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
5043 );
5044 let (n, cin, l_in) = (x_dims[0], x_dims[1], x_dims[2]);
5045 let (cin_w, cout_per_g, k) = (w_dims[0], w_dims[1], w_dims[2]);
5046 let x4 = self.reshape(Shape::from_dims(&[n, cin, 1, l_in]));
5047 let w4 = weight.reshape(Shape::from_dims(&[cin_w, cout_per_g, 1, k]));
5048 let y4 = x4.conv_transpose2d(
5049 &w4,
5050 (1, stride),
5051 (0, padding),
5052 (0, output_padding),
5053 (1, dilation),
5054 groups,
5055 );
5056 let y_dims = y4.shape();
5057 let y_dims = y_dims.dims();
5058 let (n_o, cout, _h_one, l_out) = (y_dims[0], y_dims[1], y_dims[2], y_dims[3]);
5059 y4.reshape(Shape::from_dims(&[n_o, cout, l_out]))
5060 }
5061
5062 /// Append an [`Op::Fused`] node carrying
5063 /// [`crate::registry::FusedOpParams::FlashAttn`]. `self` is `q` of shape
5064 /// `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]` with
5065 /// `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional) is
5066 /// `[Hq]`. Returns a tensor with `q`'s shape.
5067 /// Build the `flash_attn` node.
5068 ///
5069 /// # Panics
5070 ///
5071 /// Panics if any operand belongs to a different [`Graph`] than the one this
5072 /// builder is building into. Operand identity is graph-scoped and checked by
5073 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5074 /// deliberate and replaces the hang a cross-graph handle used to produce.
5075 /// Build every operand from one graph, or use a `Result`-returning entry
5076 /// point where one exists.
5077 pub fn flash_attn(
5078 &self,
5079 k: &NodeHandle,
5080 v: &NodeHandle,
5081 alibi_slopes: Option<&NodeHandle>,
5082 softmax_scale: f32,
5083 causal: bool,
5084 window_size_left: Option<usize>,
5085 window_size_right: Option<usize>,
5086 softcap: Option<f32>,
5087 ) -> NodeHandle {
5088 assert!(
5089 Arc::ptr_eq(&self.graph, &k.graph),
5090 "flash_attn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5091 );
5092 assert!(
5093 Arc::ptr_eq(&self.graph, &v.graph),
5094 "flash_attn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5095 );
5096 if let Some(a) = alibi_slopes {
5097 assert!(
5098 Arc::ptr_eq(&self.graph, &a.graph),
5099 "flash_attn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5100 );
5101 }
5102 let q_dims = self.shape();
5103 let q_dims = q_dims.dims();
5104 let k_dims = k.shape();
5105 let k_dims = k_dims.dims();
5106 let v_dims = v.shape();
5107 let v_dims = v_dims.dims();
5108 assert_eq!(
5109 q_dims.len(),
5110 4,
5111 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5112 );
5113 assert_eq!(
5114 k_dims.len(),
5115 4,
5116 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}"
5117 );
5118 assert_eq!(
5119 v_dims.len(),
5120 4,
5121 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}"
5122 );
5123 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5124 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5125 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5126 assert_eq!(b, bk, "flash_attn: B mismatch q vs k ({b} vs {bk})");
5127 assert_eq!(b, bv, "flash_attn: B mismatch q vs v");
5128 assert_eq!(hkv, hkv_v, "flash_attn: Hkv mismatch k vs v");
5129 assert_eq!(sk, sk_v, "flash_attn: Sk mismatch k vs v");
5130 assert_eq!(d, dk, "flash_attn: head_dim mismatch q vs k");
5131 assert_eq!(d, dv, "flash_attn: head_dim mismatch q vs v");
5132 assert_eq!(
5133 hq % hkv,
5134 0,
5135 "flash_attn: Hq={hq} must be a multiple of Hkv={hkv}"
5136 );
5137 if let Some(a) = alibi_slopes {
5138 let ad = a.shape();
5139 let ad = ad.dims();
5140 assert_eq!(
5141 ad,
5142 &[hq],
5143 "flash_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5144 );
5145 }
5146 let dtype = self.dtype();
5147 let mut inputs = vec![self.id, k.id, v.id];
5148 if let Some(a) = alibi_slopes {
5149 inputs.push(a.id);
5150 }
5151 // Phase 7.6 step 4 (final): emits Op::Fused(FLASH_ATTN, _).
5152 let id = self.graph.write().unwrap().push(Node {
5153 op: Op::Fused(
5154 crate::registry::FusedOps::FLASH_ATTN,
5155 crate::registry::FusedOpParams::FlashAttn {
5156 softmax_scale,
5157 causal,
5158 window_size_left,
5159 window_size_right,
5160 softcap,
5161 k_len: None,
5162 },
5163 ),
5164 inputs,
5165 shape: Shape::from_dims(&[b, hq, sq, d]),
5166 dtype,
5167 });
5168 Self {
5169 graph: self.graph.clone(),
5170 id,
5171 }
5172 }
5173
5174 /// Append an [`Op::Fused`] node carrying
5175 /// [`crate::registry::FusedOpParams::FlashAttn`] over a fixed-**capacity** K/V whose
5176 /// attended length is a **runtime** value (`k_len`) resolved through
5177 /// the per-pass [`fuel_ir::SymEnv`] at realize, decoupled
5178 /// from K's allocated shape.
5179 ///
5180 /// `self` is `q` of shape `[B, Hq, Sq, D]`; `k`/`v` are the capacity
5181 /// buffers `[B, Hkv, max_seq, D]` (GQA: `Hq % Hkv == 0`). Only the
5182 /// first `k_len.resolve(env)` rows along the K/V length axis are
5183 /// attended; the causal mask (when `causal`) is bottom-right-aligned
5184 /// at offset `k_len - Sq` — the standard FlashAttention-2 convention,
5185 /// equal to `cached_len` in autoregressive decode. Returns a tensor
5186 /// with `q`'s shape.
5187 ///
5188 /// This is the flash counterpart of [`Self::write_slice_dyn`]: the
5189 /// decode KV-cache write appends at the runtime offset and flash
5190 /// attends the runtime prefix, so the graph structure stays
5191 /// identical across tokens (Phase D symbolic extents).
5192 ///
5193 /// # Panics
5194 ///
5195 /// Panics if any operand belongs to a different [`Graph`] than the one this
5196 /// builder is building into. Operand identity is graph-scoped and checked by
5197 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5198 /// deliberate and replaces the hang a cross-graph handle used to produce.
5199 /// Build every operand from one graph, or use a `Result`-returning entry
5200 /// point where one exists.
5201 #[allow(clippy::too_many_arguments)]
5202 pub fn flash_attn_dyn(
5203 &self,
5204 k: &NodeHandle,
5205 v: &NodeHandle,
5206 alibi_slopes: Option<&NodeHandle>,
5207 softmax_scale: f32,
5208 causal: bool,
5209 window_size_left: Option<usize>,
5210 window_size_right: Option<usize>,
5211 softcap: Option<f32>,
5212 k_len: fuel_ir::DynScalar,
5213 ) -> NodeHandle {
5214 assert!(
5215 Arc::ptr_eq(&self.graph, &k.graph),
5216 "flash_attn_dyn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5217 );
5218 assert!(
5219 Arc::ptr_eq(&self.graph, &v.graph),
5220 "flash_attn_dyn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5221 );
5222 if let Some(a) = alibi_slopes {
5223 assert!(
5224 Arc::ptr_eq(&self.graph, &a.graph),
5225 "flash_attn_dyn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5226 );
5227 }
5228 let q_dims = self.shape();
5229 let q_dims = q_dims.dims();
5230 let k_dims = k.shape();
5231 let k_dims = k_dims.dims();
5232 let v_dims = v.shape();
5233 let v_dims = v_dims.dims();
5234 assert_eq!(
5235 q_dims.len(),
5236 4,
5237 "flash_attn_dyn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5238 );
5239 assert_eq!(
5240 k_dims.len(),
5241 4,
5242 "flash_attn_dyn: k must be rank 4 [B, Hkv, max_seq, D], got {k_dims:?}"
5243 );
5244 assert_eq!(
5245 v_dims.len(),
5246 4,
5247 "flash_attn_dyn: v must be rank 4 [B, Hkv, max_seq, D], got {v_dims:?}"
5248 );
5249 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5250 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5251 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5252 assert_eq!(b, bk, "flash_attn_dyn: B mismatch q vs k ({b} vs {bk})");
5253 assert_eq!(b, bv, "flash_attn_dyn: B mismatch q vs v");
5254 assert_eq!(hkv, hkv_v, "flash_attn_dyn: Hkv mismatch k vs v");
5255 assert_eq!(
5256 sk, sk_v,
5257 "flash_attn_dyn: capacity (max_seq) mismatch k vs v ({sk} vs {sk_v})"
5258 );
5259 assert_eq!(d, dk, "flash_attn_dyn: head_dim mismatch q vs k");
5260 assert_eq!(d, dv, "flash_attn_dyn: head_dim mismatch q vs v");
5261 assert_eq!(
5262 hq % hkv,
5263 0,
5264 "flash_attn_dyn: Hq={hq} must be a multiple of Hkv={hkv}"
5265 );
5266 // A build-time constant k_len must fit the capacity and cover Sq.
5267 if let fuel_ir::DynScalar::Concrete(kl) = k_len {
5268 assert!(
5269 kl <= sk,
5270 "flash_attn_dyn: k_len ({kl}) exceeds K capacity ({sk})"
5271 );
5272 assert!(
5273 kl >= sq,
5274 "flash_attn_dyn: k_len ({kl}) must be >= Sq ({sq}) for a valid causal prefix"
5275 );
5276 }
5277 if let Some(a) = alibi_slopes {
5278 let ad = a.shape();
5279 let ad = ad.dims();
5280 assert_eq!(
5281 ad,
5282 &[hq],
5283 "flash_attn_dyn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5284 );
5285 }
5286 let dtype = self.dtype();
5287 let mut inputs = vec![self.id, k.id, v.id];
5288 if let Some(a) = alibi_slopes {
5289 inputs.push(a.id);
5290 }
5291 let id = self.graph.write().unwrap().push(Node {
5292 op: Op::Fused(
5293 crate::registry::FusedOps::FLASH_ATTN,
5294 crate::registry::FusedOpParams::FlashAttn {
5295 softmax_scale,
5296 causal,
5297 window_size_left,
5298 window_size_right,
5299 softcap,
5300 k_len: Some(k_len),
5301 },
5302 ),
5303 inputs,
5304 shape: Shape::from_dims(&[b, hq, sq, d]),
5305 dtype,
5306 });
5307 Self {
5308 graph: self.graph.clone(),
5309 id,
5310 }
5311 }
5312
5313 /// Append a `Relu` node `max(0, self)`.
5314 pub fn relu(&self) -> NodeHandle {
5315 self.unary_op(Op::Relu)
5316 }
5317
5318 /// Append a `Sqr` node `self * self`.
5319 pub fn sqr(&self) -> NodeHandle {
5320 self.unary_op(Op::Sqr)
5321 }
5322
5323 /// Append an `Exp` node `e^self`.
5324 pub fn exp(&self) -> NodeHandle {
5325 self.unary_op(Op::Exp)
5326 }
5327
5328 /// Append a `Permute` node rearranging the axes according to `axes`.
5329 /// `out.shape[i] = self.shape[axes[i]]`. The axes vector must be a
5330 /// permutation of `0..rank`. For a rank-3 input with `axes = [2, 0, 1]`,
5331 /// the shape transform is `[a, b, c] → [c, a, b]`.
5332 pub fn permute(&self, axes: &[usize]) -> NodeHandle {
5333 let in_shape = self.shape();
5334 let in_dims = in_shape.dims();
5335 let rank = in_dims.len();
5336 assert_eq!(
5337 axes.len(),
5338 rank,
5339 "permute: axes length {} must equal tensor rank {}",
5340 axes.len(),
5341 rank,
5342 );
5343 // Validate that axes is a permutation of 0..rank.
5344 let mut seen = vec![false; rank];
5345 for &ax in axes {
5346 assert!(
5347 ax < rank,
5348 "permute: axis {ax} out of bounds for rank {rank}"
5349 );
5350 assert!(!seen[ax], "permute: duplicate axis {ax} in axes");
5351 seen[ax] = true;
5352 }
5353 let out_dims: Vec<usize> = axes.iter().map(|&ax| in_dims[ax]).collect();
5354 let dtype = self.dtype();
5355 let id = self.graph.write().unwrap().push(Node {
5356 op: Op::Permute(axes.to_vec()),
5357 inputs: vec![self.id],
5358 shape: Shape::from_dims(&out_dims),
5359 dtype,
5360 });
5361 Self {
5362 graph: self.graph.clone(),
5363 id,
5364 }
5365 }
5366
5367 /// Result-returning sibling of [`Self::permute`]. Surfaces bad
5368 /// axes (wrong length, out-of-bounds entry, or duplicate) as a
5369 /// typed error rather than panicking.
5370 pub fn try_permute(&self, axes: &[usize]) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5371 let in_shape = self.shape();
5372 let rank = in_shape.dims().len();
5373 if axes.len() != rank {
5374 return Err(fuel_ir::Error::Msg(format!(
5375 "permute: axes length {} must equal tensor rank {}",
5376 axes.len(),
5377 rank,
5378 ))
5379 .bt());
5380 }
5381 let mut seen = vec![false; rank];
5382 for &ax in axes {
5383 if ax >= rank {
5384 return Err(fuel_ir::Error::Msg(format!(
5385 "permute: axis {ax} out of bounds for rank {rank}",
5386 ))
5387 .bt());
5388 }
5389 if seen[ax] {
5390 return Err(
5391 fuel_ir::Error::Msg(format!("permute: duplicate axis {ax} in axes",)).bt(),
5392 );
5393 }
5394 seen[ax] = true;
5395 }
5396 let op = Op::Permute(axes.to_vec());
5397 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5398 let id = self.graph.write().unwrap().push(Node {
5399 op,
5400 inputs: vec![self.id],
5401 shape,
5402 dtype,
5403 });
5404 Ok(Self {
5405 graph: self.graph.clone(),
5406 id,
5407 })
5408 }
5409
5410 /// Append a `Transpose` node that swaps the last two dimensions of a
5411 /// tensor of rank ≥ 2. Leading dims are unchanged. For a rank-2
5412 /// tensor this is the ordinary matrix transpose; for higher ranks,
5413 /// every batch slice is transposed independently.
5414 pub fn transpose(&self) -> NodeHandle {
5415 let in_shape = self.shape();
5416 assert!(
5417 in_shape.dims().len() >= 2,
5418 "transpose: input must be rank ≥ 2, got shape {:?}",
5419 in_shape.dims(),
5420 );
5421 let op = Op::Transpose;
5422 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
5423 .expect("transpose: rank validated above");
5424 let id = self.graph.write().unwrap().push(Node {
5425 op,
5426 inputs: vec![self.id],
5427 shape,
5428 dtype,
5429 });
5430 Self {
5431 graph: self.graph.clone(),
5432 id,
5433 }
5434 }
5435
5436 /// Result-returning sibling of [`Self::transpose`]. Surfaces
5437 /// rank < 2 as a typed error rather than panicking.
5438 pub fn try_transpose(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5439 let in_shape = self.shape();
5440 if in_shape.dims().len() < 2 {
5441 return Err(fuel_ir::Error::Msg(format!(
5442 "transpose: input must be rank ≥ 2, got shape {:?}",
5443 in_shape.dims(),
5444 ))
5445 .bt());
5446 }
5447 let op = Op::Transpose;
5448 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5449 let id = self.graph.write().unwrap().push(Node {
5450 op,
5451 inputs: vec![self.id],
5452 shape,
5453 dtype,
5454 });
5455 Ok(Self {
5456 graph: self.graph.clone(),
5457 id,
5458 })
5459 }
5460
5461 // --- additional element-wise binary ops ---
5462
5463 /// Append a `Sub` node `self - other`. Requires matching shapes and dtypes.
5464 ///
5465 /// # Panics
5466 ///
5467 /// Panics if any operand belongs to a different [`Graph`] than the one this
5468 /// builder is building into. Operand identity is graph-scoped and checked by
5469 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5470 /// deliberate and replaces the hang a cross-graph handle used to produce.
5471 /// Build every operand from one graph, or use a `Result`-returning entry
5472 /// point where one exists.
5473 pub fn sub(&self, other: &NodeHandle) -> NodeHandle {
5474 self.binary_op("sub", Op::Sub, other, self.shape())
5475 }
5476
5477 /// Append a `Div` node `self / other`. Requires matching shapes and dtypes.
5478 ///
5479 /// # Panics
5480 ///
5481 /// Panics if any operand belongs to a different [`Graph`] than the one this
5482 /// builder is building into. Operand identity is graph-scoped and checked by
5483 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5484 /// deliberate and replaces the hang a cross-graph handle used to produce.
5485 /// Build every operand from one graph, or use a `Result`-returning entry
5486 /// point where one exists.
5487 pub fn div(&self, other: &NodeHandle) -> NodeHandle {
5488 self.binary_op("div", Op::Div, other, self.shape())
5489 }
5490
5491 // --- additional element-wise unary ops ---
5492
5493 /// Append a `Neg` node `-self`.
5494 pub fn neg(&self) -> NodeHandle {
5495 self.unary_op(Op::Neg)
5496 }
5497
5498 /// Append a `Sqrt` node `sqrt(self)`.
5499 pub fn sqrt(&self) -> NodeHandle {
5500 self.unary_op(Op::Sqrt)
5501 }
5502
5503 /// Append a `Log` node `ln(self)`.
5504 pub fn log(&self) -> NodeHandle {
5505 self.unary_op(Op::Log)
5506 }
5507
5508 /// Append a `Sin` node.
5509 pub fn sin(&self) -> NodeHandle {
5510 self.unary_op(Op::Sin)
5511 }
5512
5513 /// Append a `Cos` node.
5514 pub fn cos(&self) -> NodeHandle {
5515 self.unary_op(Op::Cos)
5516 }
5517
5518 /// Append a `Tanh` node.
5519 pub fn tanh(&self) -> NodeHandle {
5520 self.unary_op(Op::Tanh)
5521 }
5522
5523 /// Append a `Sigmoid` node.
5524 pub fn sigmoid(&self) -> NodeHandle {
5525 self.unary_op(Op::Sigmoid)
5526 }
5527
5528 /// Append a `Silu` node (SiLU/Swish activation: `x · sigmoid(x)`).
5529 pub fn silu(&self) -> NodeHandle {
5530 self.unary_op(Op::Silu)
5531 }
5532
5533 /// Append a `GeluTanh` node (tanh-approximation GELU).
5534 pub fn gelu_tanh(&self) -> NodeHandle {
5535 self.unary_op(Op::GeluTanh)
5536 }
5537
5538 /// Append a `Step` node (Heaviside step: `1` where `x > 0`, else `0`).
5539 pub fn step(&self) -> NodeHandle {
5540 self.unary_op(Op::Step)
5541 }
5542
5543 /// Append a `Recip` node (`1 / self`).
5544 pub fn recip(&self) -> NodeHandle {
5545 self.unary_op(Op::Recip)
5546 }
5547
5548 /// Append an `Abs` node (`|self|`).
5549 pub fn abs(&self) -> NodeHandle {
5550 self.unary_op(Op::Abs)
5551 }
5552
5553 // ---- In-place unary builders (Phase 2 of the in-place ops
5554 // infrastructure) ----
5555 //
5556 // Each emits an `Op::*Inplace` node whose input is `self`. The
5557 // returned `NodeHandle` shares the underlying graph and is the new
5558 // root; subsequent ops should use the returned handle to make the
5559 // mutation-after-read ordering observable to `derive_ordering`.
5560 //
5561 // Phase 4 (the mutation-safety pass) is what makes these safe to
5562 // call on tape-tracked tensors. Until Phase 4 lands, calling these
5563 // on a tensor that's been saved for backward will panic at
5564 // `NodeHandle::backward` time (clear error, no silent gradient
5565 // corruption).
5566
5567 /// Append a `ReluInplace` node — mutates `self`'s storage with
5568 /// `max(0, self)`. See `NodeHandle::relu` for the functional variant.
5569 pub fn relu_inplace(&self) -> NodeHandle {
5570 self.unary_op(Op::ReluInplace)
5571 }
5572
5573 /// Append a `SiluInplace` node — mutates `self`'s storage with
5574 /// `self * sigmoid(self)`. See `NodeHandle::silu` for the functional
5575 /// variant.
5576 pub fn silu_inplace(&self) -> NodeHandle {
5577 self.unary_op(Op::SiluInplace)
5578 }
5579
5580 /// Append a `GeluTanhInplace` node — mutates `self`'s storage with
5581 /// the tanh-approximation GELU. See `NodeHandle::gelu_tanh` for the
5582 /// functional variant.
5583 pub fn gelu_tanh_inplace(&self) -> NodeHandle {
5584 self.unary_op(Op::GeluTanhInplace)
5585 }
5586
5587 /// Append a `TanhInplace` node — mutates `self`'s storage with
5588 /// `tanh(self)`. See `NodeHandle::tanh` for the functional variant.
5589 pub fn tanh_inplace(&self) -> NodeHandle {
5590 self.unary_op(Op::TanhInplace)
5591 }
5592
5593 /// Append a `SigmoidInplace` node — mutates `self`'s storage
5594 /// with `sigmoid(self)`. See `NodeHandle::sigmoid` for the functional
5595 /// variant.
5596 pub fn sigmoid_inplace(&self) -> NodeHandle {
5597 self.unary_op(Op::SigmoidInplace)
5598 }
5599
5600 /// Append a `NegInplace` node — mutates `self`'s storage with
5601 /// `-self`. See `NodeHandle::neg` for the functional variant.
5602 pub fn neg_inplace(&self) -> NodeHandle {
5603 self.unary_op(Op::NegInplace)
5604 }
5605
5606 /// Append an `AbsInplace` node — mutates `self`'s storage with
5607 /// `|self|`. See `NodeHandle::abs` for the functional variant.
5608 pub fn abs_inplace(&self) -> NodeHandle {
5609 self.unary_op(Op::AbsInplace)
5610 }
5611
5612 /// Append a `SqrInplace` node — mutates `self`'s storage with
5613 /// `self²`. See `NodeHandle::sqr` for the functional variant.
5614 pub fn sqr_inplace(&self) -> NodeHandle {
5615 self.unary_op(Op::SqrInplace)
5616 }
5617
5618 /// Append a `SqrtInplace` node — mutates `self`'s storage with
5619 /// `√self`. See `NodeHandle::sqrt` for the functional variant.
5620 pub fn sqrt_inplace(&self) -> NodeHandle {
5621 self.unary_op(Op::SqrtInplace)
5622 }
5623
5624 /// Append a `RsqrtInplace` node — mutates `self`'s storage with
5625 /// `1/√self`. See `NodeHandle::rsqrt` for the functional variant.
5626 pub fn rsqrt_inplace(&self) -> NodeHandle {
5627 self.unary_op(Op::RsqrtInplace)
5628 }
5629
5630 /// Append a `RecipInplace` node — mutates `self`'s storage with
5631 /// `1/self`. See `NodeHandle::recip` for the functional variant.
5632 pub fn recip_inplace(&self) -> NodeHandle {
5633 self.unary_op(Op::RecipInplace)
5634 }
5635
5636 /// Append an `ExpInplace` node — mutates `self`'s storage with
5637 /// `exp(self)`. See `NodeHandle::exp` for the functional variant.
5638 pub fn exp_inplace(&self) -> NodeHandle {
5639 self.unary_op(Op::ExpInplace)
5640 }
5641
5642 /// Append a `LogInplace` node — mutates `self`'s storage with
5643 /// `ln(self)`. See `NodeHandle::log` for the functional variant.
5644 pub fn log_inplace(&self) -> NodeHandle {
5645 self.unary_op(Op::LogInplace)
5646 }
5647
5648 /// Append a `SinInplace` node — mutates `self`'s storage with
5649 /// `sin(self)`. See `NodeHandle::sin` for the functional variant.
5650 pub fn sin_inplace(&self) -> NodeHandle {
5651 self.unary_op(Op::SinInplace)
5652 }
5653
5654 /// Append a `CosInplace` node — mutates `self`'s storage with
5655 /// `cos(self)`. See `NodeHandle::cos` for the functional variant.
5656 pub fn cos_inplace(&self) -> NodeHandle {
5657 self.unary_op(Op::CosInplace)
5658 }
5659
5660 /// Append a `SignInplace` node — mutates `self`'s storage with
5661 /// `sign(self)`. See `NodeHandle::sign` for the functional variant.
5662 pub fn sign_inplace(&self) -> NodeHandle {
5663 self.unary_op(Op::SignInplace)
5664 }
5665
5666 /// Append a `FloorInplace` node — mutates `self`'s storage with
5667 /// `⌊self⌋`. See `NodeHandle::floor` for the functional variant.
5668 pub fn floor_inplace(&self) -> NodeHandle {
5669 self.unary_op(Op::FloorInplace)
5670 }
5671
5672 /// Append a `CeilInplace` node — mutates `self`'s storage with
5673 /// `⌈self⌉`. See `NodeHandle::ceil` for the functional variant.
5674 pub fn ceil_inplace(&self) -> NodeHandle {
5675 self.unary_op(Op::CeilInplace)
5676 }
5677
5678 /// Append a `RoundInplace` node — mutates `self`'s storage with
5679 /// `round(self)`. See `NodeHandle::round` for the functional variant.
5680 pub fn round_inplace(&self) -> NodeHandle {
5681 self.unary_op(Op::RoundInplace)
5682 }
5683
5684 /// Append an `ErfInplace` node — mutates `self`'s storage with
5685 /// `erf(self)`. See `NodeHandle::erf` for the functional variant.
5686 pub fn erf_inplace(&self) -> NodeHandle {
5687 self.unary_op(Op::ErfInplace)
5688 }
5689
5690 /// Append a `GeluInplace` node — mutates `self`'s storage
5691 /// with the exact-GeLU formula. See `NodeHandle::gelu` for the
5692 /// functional variant.
5693 pub fn gelu_inplace(&self) -> NodeHandle {
5694 self.unary_op(Op::GeluInplace)
5695 }
5696
5697 /// Append a `ClampInplace { min, max }` node — mutates `self`'s
5698 /// storage with `clamp(self, min, max)`. See `NodeHandle::clamp` for
5699 /// the functional variant.
5700 pub fn clamp_inplace(&self, min: f64, max: f64) -> NodeHandle {
5701 self.unary_op(Op::ClampInplace { min, max })
5702 }
5703
5704 /// Append a `PowIInplace(exp)` node — mutates `self`'s storage
5705 /// with `self.powi(exp)`. See `NodeHandle::powi` for the functional
5706 /// variant.
5707 pub fn powi_inplace(&self, exp: i32) -> NodeHandle {
5708 self.unary_op(Op::PowIInplace(exp))
5709 }
5710
5711 /// Append an `Op::Fused(INPLACE_AFFINE, ...)` node — mutates
5712 /// `self`'s storage with `self = mul · self + add`. Single-input
5713 /// fused op (no functional `Op::Affine` exists on
5714 /// `fuel-graph::Op`; the non-inplace equivalent is `self
5715 /// .mul_scalar(mul).add_scalar(add)`). Wired to baracuda's
5716 /// `affine_inplace_*` symbol on CUDA when Phase 3 lands.
5717 pub fn affine_inplace(&self, mul: f64, add: f64) -> NodeHandle {
5718 let shape = self.shape();
5719 let dtype = self.dtype();
5720 let id = self.graph.write().unwrap().push(Node {
5721 op: Op::Fused(
5722 crate::registry::FusedOps::INPLACE_AFFINE,
5723 crate::registry::FusedOpParams::InplaceAffine { mul, add },
5724 ),
5725 inputs: vec![self.id],
5726 shape,
5727 dtype,
5728 });
5729 Self {
5730 graph: self.graph.clone(),
5731 id,
5732 }
5733 }
5734
5735 /// Append a `Floor` node (`⌊self⌋`). Output dtype = input dtype.
5736 /// Backward is the zero distribution almost everywhere; gradient
5737 /// is dropped silently.
5738 pub fn floor(&self) -> NodeHandle {
5739 self.unary_op(Op::Floor)
5740 }
5741
5742 /// Append a `Ceil` node (`⌈self⌉`). Output dtype = input dtype.
5743 /// Backward drops gradient (non-differentiable almost everywhere).
5744 pub fn ceil(&self) -> NodeHandle {
5745 self.unary_op(Op::Ceil)
5746 }
5747
5748 /// Append a `Round` node — banker's rounding (round-half-to-even,
5749 /// IEEE 754 roundeven). 0.5 → 0, 1.5 → 2, 2.5 → 2, 3.5 → 4.
5750 /// Output dtype = input dtype. Backward drops gradient.
5751 pub fn round(&self) -> NodeHandle {
5752 self.unary_op(Op::Round)
5753 }
5754
5755 /// Append a `Sign` node (`-1` / `0` / `1`). `sign(0) = 0` by
5756 /// subgradient convention. Output dtype = input dtype. Backward
5757 /// drops gradient.
5758 pub fn sign(&self) -> NodeHandle {
5759 self.unary_op(Op::Sign)
5760 }
5761
5762 /// Append an `Erf` node (Gauss error function). Output dtype =
5763 /// input dtype. Differentiable.
5764 pub fn erf(&self) -> NodeHandle {
5765 self.unary_op(Op::Erf)
5766 }
5767
5768 /// Append a `Gelu` node — exact-erf formulation of GELU
5769 /// (`0.5 * x * (1 + erf(x/√2))`). Distinct from [`Self::gelu_tanh`]
5770 /// (tanh approximation). Output dtype = input dtype.
5771 /// Differentiable.
5772 pub fn gelu(&self) -> NodeHandle {
5773 self.unary_op(Op::Gelu)
5774 }
5775
5776 /// Append a `Pow` node `pow(self, other)` element-wise (real
5777 /// exponent). Both operands must share dtype and shape. Distinct
5778 /// from [`Self::powi`] (scalar `i32` exponent). NaN follows
5779 /// IEEE-754 (`pow(-2, 0.5) = NaN`).
5780 ///
5781 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5782 /// typed error, not a panic.
5783 pub fn pow(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5784 let out_shape = self.shape();
5785 self.try_binary_op("pow", Op::Pow, other, out_shape)
5786 }
5787
5788 /// Append an `Rsqrt` node (`1 / sqrt(self)`). Same dtype as
5789 /// input. Single op rather than `sqrt(x).recip()` — one kernel
5790 /// launch and matches RMSNorm's `x * rsqrt(...)` shape.
5791 /// Differentiable.
5792 pub fn rsqrt(&self) -> NodeHandle {
5793 self.unary_op(Op::Rsqrt)
5794 }
5795
5796 /// Append a `Rem` node `self % other` element-wise (PyTorch
5797 /// convention: `a - floor(a/b) * b`, sign of result matches
5798 /// divisor). Both operands must share dtype and shape.
5799 /// Differentiable.
5800 ///
5801 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5802 /// typed error, not a panic.
5803 pub fn rem(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5804 let out_shape = self.shape();
5805 self.try_binary_op("rem", Op::Rem, other, out_shape)
5806 }
5807
5808 /// Append a `Flip` node — reverses element order along `dim`.
5809 /// Output shape == input shape. Materializing op (real byte
5810 /// shuffle; not a metadata-only view). Differentiable
5811 /// (involutive: backward is another Flip on the same dim).
5812 ///
5813 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5814 pub fn flip(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5815 let in_shape = self.shape();
5816 let rank = in_shape.dims().len();
5817 if dim >= rank {
5818 return Err(fuel_ir::Error::Msg(format!(
5819 "flip: dim {dim} out of bounds for rank {rank}",
5820 ))
5821 .bt());
5822 }
5823 let op = Op::Flip { dim };
5824 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5825 let id = self.graph.write().unwrap().push(Node {
5826 op,
5827 inputs: vec![self.id],
5828 shape,
5829 dtype,
5830 });
5831 Ok(Self {
5832 graph: self.graph.clone(),
5833 id,
5834 })
5835 }
5836
5837 /// Append a `Roll` node — cyclic shift along `dim` by `shift`
5838 /// positions. Positive `shift` moves elements to higher indices
5839 /// (wrapping); negative the opposite. Output shape == input
5840 /// shape. Differentiable (backward is `Roll { dim, -shift }`).
5841 ///
5842 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5843 pub fn roll(&self, dim: usize, shift: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5844 let in_shape = self.shape();
5845 let rank = in_shape.dims().len();
5846 if dim >= rank {
5847 return Err(fuel_ir::Error::Msg(format!(
5848 "roll: dim {dim} out of bounds for rank {rank}",
5849 ))
5850 .bt());
5851 }
5852 let op = Op::Roll { dim, shift };
5853 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5854 let id = self.graph.write().unwrap().push(Node {
5855 op,
5856 inputs: vec![self.id],
5857 shape,
5858 dtype,
5859 });
5860 Ok(Self {
5861 graph: self.graph.clone(),
5862 id,
5863 })
5864 }
5865
5866 /// Append a `CumSum` node — running cumulative sum along `dim`.
5867 /// Output shape == input shape. Differentiable; backward is
5868 /// reverse-cumsum (`Flip → CumSum → Flip`).
5869 ///
5870 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5871 pub fn cumsum(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5872 let in_shape = self.shape();
5873 let rank = in_shape.dims().len();
5874 if dim >= rank {
5875 return Err(fuel_ir::Error::Msg(format!(
5876 "cumsum: dim {dim} out of bounds for rank {rank}",
5877 ))
5878 .bt());
5879 }
5880 let dtype = self.dtype();
5881 let id = self.graph.write().unwrap().push(Node {
5882 op: Op::CumSum { dim },
5883 inputs: vec![self.id],
5884 shape: in_shape,
5885 dtype,
5886 });
5887 Ok(Self {
5888 graph: self.graph.clone(),
5889 id,
5890 })
5891 }
5892
5893 /// Append a `Triu` node — upper-triangular mask along the last two
5894 /// dims. `diagonal = 0` keeps the main diagonal and above; positive
5895 /// values shift the cutoff up (keeping less); negative shift down
5896 /// (keeping more, including subdiagonals).
5897 ///
5898 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
5899 pub fn triu(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5900 let in_shape = self.shape();
5901 let rank = in_shape.dims().len();
5902 if rank < 2 {
5903 return Err(fuel_ir::Error::Msg(format!(
5904 "triu: input must have rank >= 2, got {rank}",
5905 ))
5906 .bt());
5907 }
5908 let dtype = self.dtype();
5909 let id = self.graph.write().unwrap().push(Node {
5910 op: Op::Triu { diagonal },
5911 inputs: vec![self.id],
5912 shape: in_shape,
5913 dtype,
5914 });
5915 Ok(Self {
5916 graph: self.graph.clone(),
5917 id,
5918 })
5919 }
5920
5921 /// Append an [`Op::Scan`] node — a bounded `lax.scan` recurrence.
5922 /// `self` is the `init_carry`. The body must already be built in the same
5923 /// graph, referencing `Op::ScanPlaceholder{Carry,0}` for the per-step
5924 /// carry and `Op::ScanPlaceholder{Elem,i}` for the per-step slice of
5925 /// `xs[i]`; `consts` are referenced by real NodeId. `body_new_carry` /
5926 /// `body_y` are the body's two exit nodes. Always a 2-slot bundle
5927 /// (slot 0 = stacked `ys` `[bound] ++ body_y`, slot 1 = final carry);
5928 /// `emit` selects which slot this call projects. `early_exit` is Phase 2
5929 /// (always `None` here).
5930 ///
5931 /// **Returns `Result`**: a malformed body/carry/bound surfaces as a typed
5932 /// error — never a panic.
5933 pub fn scan(
5934 &self,
5935 xs: &[NodeHandle],
5936 consts: &[NodeHandle],
5937 body_new_carry: &NodeHandle,
5938 body_y: &NodeHandle,
5939 bound: usize,
5940 emit: ScanEmit,
5941 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5942 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
5943 if !same_graph(body_new_carry)
5944 || !same_graph(body_y)
5945 || !xs.iter().all(same_graph)
5946 || !consts.iter().all(same_graph)
5947 {
5948 return Err(fuel_ir::Error::Msg(
5949 "scan: init_carry, xs, consts, and body exits must live on one graph".into(),
5950 )
5951 .bt());
5952 }
5953 if bound == 0 {
5954 return Err(fuel_ir::Error::Msg("scan: bound must be >= 1".into()).bt());
5955 }
5956 let carry_shape = self.shape();
5957 if body_new_carry.shape().dims() != carry_shape.dims() {
5958 return Err(fuel_ir::Error::Msg(format!(
5959 "scan: body_new_carry shape {:?} must equal init_carry shape {:?}",
5960 body_new_carry.shape().dims(),
5961 carry_shape.dims(),
5962 ))
5963 .bt());
5964 }
5965 // Validate body placeholders at graph-build time (single-carry; every
5966 // Elem index < n_xs) so a malformed body is a typed Err here, not a
5967 // later `elem[index]` panic on the unroll / forward-driver path.
5968 {
5969 let g = self.graph.read().unwrap();
5970 crate::scan::validate_scan_body_placeholders(
5971 &g,
5972 &[body_new_carry.id, body_y.id],
5973 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
5974 // construction below); the IR and the unroll are not.
5975 1,
5976 xs.len(),
5977 )?;
5978 }
5979 let carry_dtype = self.dtype();
5980 let y_dtype = body_y.dtype();
5981
5982 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
5983 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
5984 ys_dims.push(bound);
5985 ys_dims.extend_from_slice(body_y.shape().dims());
5986 let ys_shape = Shape::from_dims(&ys_dims);
5987 let specs = vec![
5988 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
5989 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
5990 ];
5991 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs)
5992 .map_err(|e| fuel_ir::Error::Msg(format!("scan: compose_bundle failed: {e}")).bt())?;
5993
5994 let mut inputs: Vec<NodeId> = Vec::with_capacity(2 + xs.len() + consts.len() + 2);
5995 inputs.push(self.id);
5996 inputs.extend(xs.iter().map(|t| t.id));
5997 inputs.extend(consts.iter().map(|t| t.id));
5998 inputs.push(body_new_carry.id);
5999 inputs.push(body_y.id);
6000
6001 let id = {
6002 let mut g = self.graph.write().unwrap();
6003 // Node.shape/dtype are the PRIMARY (slot-0) shape/dtype per the
6004 // multi-output authoring contract.
6005 let id = g.push(Node {
6006 op: Op::Scan {
6007 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6008 // `parse_scan_layout` and `build_scan_step` all handle N
6009 // carries. This BUILDER deliberately still constructs ONE.
6010 //
6011 // Widening it means N+1 output-view specs through
6012 // `compose_bundle` below -- i.e. the bundle arity -- which is
6013 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6014 // is NOT this change. A reader must not read "the builder makes
6015 // one" as "multi-carry does not work".
6016 n_carries: 1,
6017 n_xs: xs.len(),
6018 bound,
6019 emit,
6020 early_exit: None,
6021 },
6022 inputs,
6023 shape: ys_shape,
6024 dtype: y_dtype,
6025 });
6026 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6027 .map_err(|e| {
6028 fuel_ir::Error::Msg(format!("scan: set_output_views failed: {e}")).bt()
6029 })?;
6030 id
6031 };
6032 let producer = Self {
6033 graph: self.graph.clone(),
6034 id,
6035 };
6036 match emit {
6037 ScanEmit::All => producer.view(0),
6038 ScanEmit::Final => producer.view(1),
6039 }
6040 }
6041
6042 /// Append an early-exit [`Op::Scan`] node — the `Result`-returning sibling
6043 /// of [`NodeHandle::scan`] that carries a convergence predicate as the extra
6044 /// trailing input (`early_exit = Some(ScanPredicate)`). `self` is the
6045 /// `init_carry`; `pred_exit` is a scalar-`U8` sub-DAG over the carry
6046 /// (`Op::ScanPlaceholder{Carry,0}` for the pre-step carry, and the shared
6047 /// `body_new_carry` node for the post-step carry) that stops iteration when
6048 /// it fires. The runtime stop count is data-dependent under the static
6049 /// capacity `bound`.
6050 ///
6051 /// **`consts` must include every const referenced by the body OR the
6052 /// predicate** — the clone/unroll machinery shares only `consts`; a
6053 /// predicate const outside `consts` would be re-cloned dataless and fail at
6054 /// realize.
6055 ///
6056 /// **Returns `Result`**: a malformed body/carry/bound, or a non-scalar /
6057 /// non-`U8` / `Elem`-referencing predicate, surfaces as a typed error —
6058 /// never a panic (validated at graph-build time).
6059 #[allow(clippy::too_many_arguments)]
6060 pub fn scan_until(
6061 &self,
6062 xs: &[NodeHandle],
6063 consts: &[NodeHandle],
6064 body_new_carry: &NodeHandle,
6065 body_y: &NodeHandle,
6066 pred_exit: &NodeHandle,
6067 bound: usize,
6068 emit: ScanEmit,
6069 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6070 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6071 if !same_graph(body_new_carry)
6072 || !same_graph(body_y)
6073 || !same_graph(pred_exit)
6074 || !xs.iter().all(same_graph)
6075 || !consts.iter().all(same_graph)
6076 {
6077 return Err(fuel_ir::Error::Msg(
6078 "scan_until: init_carry, xs, consts, body exits, and pred_exit must live on one graph".into(),
6079 ).bt());
6080 }
6081 if bound == 0 {
6082 return Err(fuel_ir::Error::Msg("scan_until: bound must be >= 1".into()).bt());
6083 }
6084 let carry_shape = self.shape();
6085 if body_new_carry.shape().dims() != carry_shape.dims() {
6086 return Err(fuel_ir::Error::Msg(format!(
6087 "scan_until: body_new_carry shape {:?} must equal init_carry shape {:?}",
6088 body_new_carry.shape().dims(),
6089 carry_shape.dims(),
6090 ))
6091 .bt());
6092 }
6093 // Validate body placeholders at graph-build time (single-carry; every
6094 // Elem index < n_xs) so a malformed body is a typed Err here, not a
6095 // later `elem[index]` panic in the forward driver's build_scan_step.
6096 {
6097 let g = self.graph.read().unwrap();
6098 crate::scan::validate_scan_body_placeholders(
6099 &g,
6100 &[body_new_carry.id, body_y.id],
6101 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6102 // construction below); the IR and the unroll are not.
6103 1,
6104 xs.len(),
6105 )?;
6106 }
6107 // Predicate must be a scalar Bool (shape [] or product == 1) — a
6108 // convergence flag, not a per-element mask. Validate at build time.
6109 // GAP-168(c): Bool, not U8. A predicate's natural producer is a
6110 // comparison, and those now yield Bool, so requiring U8 here would make
6111 // the ordinary `carry.ge(&thr)` path unusable as a predicate.
6112 if pred_exit.dtype() != fuel_ir::DType::Bool {
6113 return Err(fuel_ir::Error::Msg(format!(
6114 "scan_until: pred_exit must be Bool (a boolean flag), got {:?}",
6115 pred_exit.dtype(),
6116 ))
6117 .bt());
6118 }
6119 let pred_dims = pred_exit.shape();
6120 let pred_numel: usize = pred_dims.dims().iter().product();
6121 if pred_numel != 1 {
6122 return Err(fuel_ir::Error::Msg(format!(
6123 "scan_until: pred_exit must be a scalar (shape [] or [1]/all-ones), got {:?}",
6124 pred_dims.dims(),
6125 ))
6126 .bt());
6127 }
6128 // Every ScanPlaceholder reachable from pred_exit must be Carry{0} — the
6129 // predicate is over the carry, never a per-step Elem slice.
6130 {
6131 let g = self.graph.read().unwrap();
6132 for &id in &crate::topo_order_multi(&g, &[pred_exit.id]) {
6133 if let Op::ScanPlaceholder { role, index } = &g.node(id).op {
6134 let bad = matches!(role, ScanRole::Elem) || *index != 0;
6135 if bad {
6136 return Err(fuel_ir::Error::Msg(format!(
6137 "scan_until: pred_exit references ScanPlaceholder{{{role:?}, {index}}} — \
6138 the predicate may only read the carry (Carry, index 0)",
6139 )).bt());
6140 }
6141 }
6142 }
6143 }
6144 let carry_dtype = self.dtype();
6145 let y_dtype = body_y.dtype();
6146
6147 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6148 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6149 ys_dims.push(bound);
6150 ys_dims.extend_from_slice(body_y.shape().dims());
6151 let ys_shape = Shape::from_dims(&ys_dims);
6152 let specs = vec![
6153 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6154 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6155 ];
6156 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs).map_err(|e| {
6157 fuel_ir::Error::Msg(format!("scan_until: compose_bundle failed: {e}")).bt()
6158 })?;
6159
6160 let mut inputs: Vec<NodeId> = Vec::with_capacity(3 + xs.len() + consts.len());
6161 inputs.push(self.id);
6162 inputs.extend(xs.iter().map(|t| t.id));
6163 inputs.extend(consts.iter().map(|t| t.id));
6164 inputs.push(body_new_carry.id);
6165 inputs.push(body_y.id);
6166 inputs.push(pred_exit.id); // <-- the C1 trailing predicate
6167
6168 let id = {
6169 let mut g = self.graph.write().unwrap();
6170 let id = g.push(Node {
6171 op: Op::Scan {
6172 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6173 // `parse_scan_layout` and `build_scan_step` all handle N
6174 // carries. This BUILDER deliberately still constructs ONE.
6175 //
6176 // Widening it means N+1 output-view specs through
6177 // `compose_bundle` below -- i.e. the bundle arity -- which is
6178 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6179 // is NOT this change. A reader must not read "the builder makes
6180 // one" as "multi-carry does not work".
6181 n_carries: 1,
6182 n_xs: xs.len(),
6183 bound,
6184 emit,
6185 early_exit: Some(ScanPredicate),
6186 },
6187 inputs,
6188 shape: ys_shape,
6189 dtype: y_dtype,
6190 });
6191 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6192 .map_err(|e| {
6193 fuel_ir::Error::Msg(format!("scan_until: set_output_views failed: {e}")).bt()
6194 })?;
6195 id
6196 };
6197 let producer = Self {
6198 graph: self.graph.clone(),
6199 id,
6200 };
6201 match emit {
6202 ScanEmit::All => producer.view(0),
6203 ScanEmit::Final => producer.view(1),
6204 }
6205 }
6206
6207 /// Append a `Tril` node — lower-triangular mask along the last two
6208 /// dims. `diagonal = 0` keeps the main diagonal and below.
6209 /// `tril(diagonal = 0)` is the canonical causal-attention mask.
6210 ///
6211 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6212 pub fn tril(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6213 let in_shape = self.shape();
6214 let rank = in_shape.dims().len();
6215 if rank < 2 {
6216 return Err(fuel_ir::Error::Msg(format!(
6217 "tril: input must have rank >= 2, got {rank}",
6218 ))
6219 .bt());
6220 }
6221 let dtype = self.dtype();
6222 let id = self.graph.write().unwrap().push(Node {
6223 op: Op::Tril { diagonal },
6224 inputs: vec![self.id],
6225 shape: in_shape,
6226 dtype,
6227 });
6228 Ok(Self {
6229 graph: self.graph.clone(),
6230 id,
6231 })
6232 }
6233
6234 /// Append a `LogSoftmaxLastDim` node. Output shape == input shape.
6235 /// Numerically stable (max-subtracting formula) — preferred over
6236 /// `log(softmax(x))` for NLL / cross-entropy loss.
6237 ///
6238 /// **Returns `Result`**: rank < 1 surfaces as a typed error.
6239 pub fn log_softmax_last_dim(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6240 let in_shape = self.shape();
6241 if in_shape.dims().is_empty() {
6242 return Err(fuel_ir::Error::Msg(
6243 "log_softmax_last_dim: input must have rank >= 1".to_string(),
6244 )
6245 .bt());
6246 }
6247 let dtype = self.dtype();
6248 let id = self.graph.write().unwrap().push(Node {
6249 op: Op::LogSoftmaxLastDim,
6250 inputs: vec![self.id],
6251 shape: in_shape,
6252 dtype,
6253 });
6254 Ok(Self {
6255 graph: self.graph.clone(),
6256 id,
6257 })
6258 }
6259
6260 /// Append a `MaskedFill` node. `mask` must be `Bool` (GAP-168(c)) and have
6261 /// the same shape as `self`. Every position where `mask` is true gets `value`;
6262 /// every position where `mask == 0` passes `self` through. `value`
6263 /// is a scalar of `self`'s dtype.
6264 ///
6265 /// **Returns `Result`**: shape or dtype mismatches surface as typed
6266 /// errors.
6267 pub fn masked_fill(
6268 &self,
6269 mask: &NodeHandle,
6270 value: Scalar,
6271 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6272 self.require_same_graph(mask, "masked_fill", "mask")?;
6273 if self.shape().dims() != mask.shape().dims() {
6274 return Err(fuel_ir::Error::Msg(format!(
6275 "masked_fill: x.shape={:?} != mask.shape={:?}",
6276 self.shape().dims(),
6277 mask.shape().dims(),
6278 ))
6279 .bt());
6280 }
6281 if mask.dtype() != DType::Bool {
6282 return Err(fuel_ir::Error::Msg(format!(
6283 "masked_fill: mask dtype must be Bool, got {:?} — cast a numeric \
6284 mask to Bool explicitly (GAP-168(c))",
6285 mask.dtype(),
6286 ))
6287 .bt());
6288 }
6289 // GAP-002 (D5) / GAP-075 (fix B): classify EVERY dtype explicitly — no
6290 // wildcard default. The guard is SEMANTIC: masked_fill needs a
6291 // representable fill value AND a zero (the backward fills with zero), so
6292 // it rejects the packed formats (F4/F6*, no scalar fill) and the
6293 // block-scales (F8E8M0/F8E6M2, no zero), and permits the ordinary
6294 // numeric dtypes. Rejecting on the guard's own terms also keeps the
6295 // `Scalar::zero` Err branch in the MaskedFill `backward` arm provably
6296 // unreachable in a well-formed graph.
6297 //
6298 // Under the OLD denylist (`matches!(reject-set)`, else allow) a FUTURE
6299 // dtype fell through to "permitted" SILENTLY. With new dtypes scheduled
6300 // (GAP-097: e5m2, complex, sub-byte int, …) that would silently accept
6301 // masked_fill on formats whose fill semantics are unsettled. An
6302 // exhaustive match makes a new dtype a COMPILE ERROR here, forcing the
6303 // person who adds it to decide its permission consciously — the compiler
6304 // is the real guard; the tests below protect the existing classification.
6305 //
6306 // NOTE: "permitted" is a graph-build PERMISSION (is masked_fill
6307 // semantically well-defined?), NOT a promise a backend can allocate/run
6308 // the dtype. An unimplemented storage still declines loudly downstream
6309 // (typed `UnsupportedDTypeForOp` at allocation), which is the sound
6310 // composition — a semantically-true guard upstream, a loud capability
6311 // decline downstream.
6312 match self.dtype() {
6313 DType::F4 | DType::F6E2M3 | DType::F6E3M2 | DType::F8E8M0 | DType::F8E6M2 => {
6314 return Err(
6315 fuel_ir::Error::UnsupportedDTypeForOp(self.dtype(), "masked_fill").bt(),
6316 );
6317 }
6318 DType::U8
6319 | DType::I8
6320 | DType::U32
6321 | DType::I16
6322 | DType::I32
6323 | DType::I64
6324 | DType::BF16
6325 | DType::F16
6326 | DType::F32
6327 | DType::F64
6328 | DType::F8E4M3
6329 // GAP-097: F8E5M2 is PERMITTED, on the guard's own semantic terms.
6330 //
6331 // The reject set above is not "exotic dtypes" — it is two distinct
6332 // NON-VALUE categories: the block-scales (F8E8M0/F8E6M2) ride as
6333 // sibling operands and are not element value dtypes at all, and the
6334 // block-scoped elements (F4/F6*) have no standalone byte layout, so
6335 // a single element is not addressable without its block. Neither has
6336 // a well-defined fill-one-element operation, which is what this op
6337 // needs. F8E5M2 is a value dtype in exactly the way F8E4M3 (already
6338 // permitted, directly above) is: sign + exponent + mantissa, a
6339 // standalone byte layout, a representable zero for the backward, and
6340 // a representable fill value. So permitting it CONTINUES the
6341 // existing classification; rejecting would be the exception.
6342 //
6343 // Weighed and rejected as grounds for the opposite call: F8E5M2
6344 // currently has NO host or CUDA storage (fuel-cpu-backend and
6345 // fuel-cuda-backend both decline it), so this permits a graph the
6346 // backends cannot yet allocate — GAP(GAP-161) tracks that storage
6347 // decline and its expiry. That is the NOTE above working as
6348 // designed — permission is semantic, allocation is a capability, and
6349 // they are different questions. Writing REJECT here would encode the
6350 // claim "F8E5M2 has no representable fill value", which is FALSE and
6351 // would outlive the storage gap that motivated it.
6352 | DType::F8E5M2
6353 // GAP-168(c): Bool is a value dtype with a representable fill value
6354 // (true/false) and a zero for the backward (false) — permitted on
6355 // this guard's own semantic terms, exactly as the FP8 value dtypes
6356 // are. (This is the FILLED tensor's dtype; the MASK dtype is checked
6357 // separately above.)
6358 | DType::Bool => {}
6359 }
6360 if value.dtype() != self.dtype() {
6361 return Err(fuel_ir::Error::Msg(format!(
6362 "masked_fill: value dtype {:?} != x dtype {:?}",
6363 value.dtype(),
6364 self.dtype(),
6365 ))
6366 .bt());
6367 }
6368 let op = Op::MaskedFill { value };
6369 let (shape, dtype) = crate::shape::primitive_shape(
6370 &op,
6371 &[self.shape(), mask.shape()],
6372 &[self.dtype(), mask.dtype()],
6373 )
6374 .expect("masked_fill: shapes/dtypes validated above");
6375 let id = self.graph.write().unwrap().push(Node {
6376 op,
6377 inputs: vec![self.id, mask.id],
6378 shape,
6379 dtype,
6380 });
6381 Ok(Self {
6382 graph: self.graph.clone(),
6383 id,
6384 })
6385 }
6386
6387 /// Append a `Pad` node — multi-dim padding. `padding[i] = (before, after)`
6388 /// for axis `i`; `padding.len()` must equal `self.rank()`.
6389 /// Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
6390 /// `value` is the fill constant for [`PadMode::Constant`]
6391 /// (ignored for other modes).
6392 ///
6393 /// Only Constant mode is wired through the executor in the v1
6394 /// cut; the other modes produce a clean error at realize time.
6395 /// Differentiable for Constant (backward slices the gradient
6396 /// along each padded axis to restore the input shape).
6397 ///
6398 /// **Returns `Result`**: rank mismatch surfaces as a typed error.
6399 pub fn pad(
6400 &self,
6401 padding: Vec<(usize, usize)>,
6402 mode: PadMode,
6403 value: f64,
6404 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6405 let in_shape = self.shape();
6406 let rank = in_shape.dims().len();
6407 if padding.len() != rank {
6408 return Err(fuel_ir::Error::Msg(format!(
6409 "pad: padding.len() ({}) must equal tensor rank ({rank})",
6410 padding.len(),
6411 ))
6412 .bt());
6413 }
6414 let op = Op::Pad {
6415 padding,
6416 mode,
6417 value,
6418 };
6419 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6420 let id = self.graph.write().unwrap().push(Node {
6421 op,
6422 inputs: vec![self.id],
6423 shape,
6424 dtype,
6425 });
6426 Ok(Self {
6427 graph: self.graph.clone(),
6428 id,
6429 })
6430 }
6431
6432 /// Append an `Equal` node (`self == other`) producing a `Bool` mask.
6433 /// Both operands must share dtype and shape; output dtype is `Bool`
6434 /// (`1` where equal, `0` otherwise). NaN follows IEEE-754
6435 /// (`NaN == NaN` is false). Non-differentiable.
6436 ///
6437 /// # Panics
6438 ///
6439 /// Panics if any operand belongs to a different [`Graph`] than the one this
6440 /// builder is building into. Operand identity is graph-scoped and checked by
6441 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6442 /// deliberate and replaces the hang a cross-graph handle used to produce.
6443 /// Build every operand from one graph, or use a `Result`-returning entry
6444 /// point where one exists.
6445 pub fn eq(&self, other: &NodeHandle) -> NodeHandle {
6446 self.binary_compare_op("eq", Op::Equal, other)
6447 }
6448
6449 /// Append a `Ne` node (`self != other`) producing a `Bool` mask.
6450 /// Same shape/dtype contract as [`Self::eq`]. NaN follows
6451 /// IEEE-754 (`NaN != NaN` is true → `1`). Non-differentiable.
6452 ///
6453 /// # Panics
6454 ///
6455 /// Panics if any operand belongs to a different [`Graph`] than the one this
6456 /// builder is building into. Operand identity is graph-scoped and checked by
6457 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6458 /// deliberate and replaces the hang a cross-graph handle used to produce.
6459 /// Build every operand from one graph, or use a `Result`-returning entry
6460 /// point where one exists.
6461 pub fn ne(&self, other: &NodeHandle) -> NodeHandle {
6462 self.binary_compare_op("ne", Op::Ne, other)
6463 }
6464
6465 /// Append an `Lt` node (`self < other`) producing a `Bool` mask.
6466 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6467 /// is always `0` (IEEE-754 unordered). Non-differentiable.
6468 ///
6469 /// # Panics
6470 ///
6471 /// Panics if any operand belongs to a different [`Graph`] than the one this
6472 /// builder is building into. Operand identity is graph-scoped and checked by
6473 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6474 /// deliberate and replaces the hang a cross-graph handle used to produce.
6475 /// Build every operand from one graph, or use a `Result`-returning entry
6476 /// point where one exists.
6477 pub fn lt(&self, other: &NodeHandle) -> NodeHandle {
6478 self.binary_compare_op("lt", Op::Lt, other)
6479 }
6480
6481 /// Append an `Le` node (`self <= other`) producing a `Bool` mask.
6482 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6483 /// is always `0`. Non-differentiable.
6484 ///
6485 /// # Panics
6486 ///
6487 /// Panics if any operand belongs to a different [`Graph`] than the one this
6488 /// builder is building into. Operand identity is graph-scoped and checked by
6489 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6490 /// deliberate and replaces the hang a cross-graph handle used to produce.
6491 /// Build every operand from one graph, or use a `Result`-returning entry
6492 /// point where one exists.
6493 pub fn le(&self, other: &NodeHandle) -> NodeHandle {
6494 self.binary_compare_op("le", Op::Le, other)
6495 }
6496
6497 /// Append a `Gt` node (`self > other`) producing a `Bool` mask.
6498 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6499 /// is always `0`. Non-differentiable.
6500 ///
6501 /// # Panics
6502 ///
6503 /// Panics if any operand belongs to a different [`Graph`] than the one this
6504 /// builder is building into. Operand identity is graph-scoped and checked by
6505 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6506 /// deliberate and replaces the hang a cross-graph handle used to produce.
6507 /// Build every operand from one graph, or use a `Result`-returning entry
6508 /// point where one exists.
6509 pub fn gt(&self, other: &NodeHandle) -> NodeHandle {
6510 self.binary_compare_op("gt", Op::Gt, other)
6511 }
6512
6513 /// Append a `Ge` node (`self >= other`) producing a `Bool` mask.
6514 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6515 /// is always `0`. Non-differentiable.
6516 ///
6517 /// # Panics
6518 ///
6519 /// Panics if any operand belongs to a different [`Graph`] than the one this
6520 /// builder is building into. Operand identity is graph-scoped and checked by
6521 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6522 /// deliberate and replaces the hang a cross-graph handle used to produce.
6523 /// Build every operand from one graph, or use a `Result`-returning entry
6524 /// point where one exists.
6525 pub fn ge(&self, other: &NodeHandle) -> NodeHandle {
6526 self.binary_compare_op("ge", Op::Ge, other)
6527 }
6528
6529 /// Ternary select: `result[i] = if self[i] { a[i] } else { b[i] }`.
6530 /// Receiver is the `cond` mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
6531 /// must share dtype with each other and shape with `self`. Output
6532 /// dtype matches `a`/`b`. Returning a new tensor where each slot is
6533 /// picked from `a` (cond=1) or `b` (cond=0).
6534 ///
6535 /// Named `where_cond` because `where` is a Rust reserved keyword.
6536 /// Common spelling in Candle/PyTorch families.
6537 ///
6538 /// Differentiable through `a` and `b` only; gradient through the
6539 /// cond mask is `None` (registered in
6540 /// [`crate::grad::WhereRule`]).
6541 ///
6542 /// # Panics
6543 ///
6544 /// Panics if any operand belongs to a different [`Graph`] than the one this
6545 /// builder is building into. Operand identity is graph-scoped and checked by
6546 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6547 /// deliberate and replaces the hang a cross-graph handle used to produce.
6548 /// Build every operand from one graph, or use a `Result`-returning entry
6549 /// point where one exists.
6550 pub fn where_cond(&self, a: &NodeHandle, b: &NodeHandle) -> NodeHandle {
6551 assert!(
6552 Arc::ptr_eq(&self.graph, &a.graph) && Arc::ptr_eq(&self.graph, &b.graph),
6553 "where_cond: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
6554 );
6555 assert_eq!(
6556 self.dtype(),
6557 DType::Bool,
6558 "where_cond: cond must be Bool (GAP-168(c)), got {:?} — cast a numeric \
6559 mask to Bool explicitly",
6560 self.dtype(),
6561 );
6562 assert_eq!(
6563 a.dtype(),
6564 b.dtype(),
6565 "where_cond: a/b dtype mismatch: a={:?}, b={:?}",
6566 a.dtype(),
6567 b.dtype(),
6568 );
6569 assert_eq!(
6570 self.shape().dims(),
6571 a.shape().dims(),
6572 "where_cond: cond/a shape mismatch: cond={:?}, a={:?}",
6573 self.shape().dims(),
6574 a.shape().dims(),
6575 );
6576 assert_eq!(
6577 self.shape().dims(),
6578 b.shape().dims(),
6579 "where_cond: cond/b shape mismatch: cond={:?}, b={:?}",
6580 self.shape().dims(),
6581 b.shape().dims(),
6582 );
6583 let (shape, dtype) = crate::shape::primitive_shape(
6584 &Op::Where,
6585 &[self.shape(), a.shape(), b.shape()],
6586 &[self.dtype(), a.dtype(), b.dtype()],
6587 )
6588 .expect("where_cond: shapes/dtypes validated above");
6589 let id = self.graph.write().unwrap().push(Node {
6590 op: Op::Where,
6591 inputs: vec![self.id, a.id, b.id],
6592 shape,
6593 dtype,
6594 });
6595 Self {
6596 graph: self.graph.clone(),
6597 id,
6598 }
6599 }
6600
6601 // --- dtype and broadcasting ---
6602
6603 /// Append a `Cast` node converting this tensor's element type to
6604 /// `target`. Shape is preserved. An identity cast (`target` equals the
6605 /// current dtype) is a no-op that the optimizer elides (see
6606 /// `opt::optimize`'s identity-`Cast` rule) — kept here rather than
6607 /// special-cased at construction so every identity cast, however it
6608 /// arises (decompose, autograd, user), is removed in one place.
6609 pub fn cast(&self, target: DType) -> NodeHandle {
6610 let op = Op::Cast(target);
6611 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6612 .expect("cast: single input, dtype change always infers");
6613 let id = self.graph.write().unwrap().push(Node {
6614 op,
6615 inputs: vec![self.id],
6616 shape,
6617 dtype,
6618 });
6619 Self {
6620 graph: self.graph.clone(),
6621 id,
6622 }
6623 }
6624
6625 /// Append a `BroadcastTo` node that expands `self` to the given target
6626 /// shape using NumPy broadcasting rules (right-align, pad with 1s,
6627 /// expand size-1 dims). The new tensor has the target shape and the
6628 /// same dtype as `self`.
6629 pub fn broadcast_to(&self, target: impl Into<Shape>) -> NodeHandle {
6630 let target = target.into();
6631 let src_dims = self.shape();
6632 // Validate broadcast compatibility up front so users hear about
6633 // bad target shapes at build time, not realize time.
6634 check_broadcast_compatible(src_dims.dims(), target.dims());
6635 let op = Op::BroadcastTo(target);
6636 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6637 .expect("broadcast_to: compatibility validated above");
6638 let id = self.graph.write().unwrap().push(Node {
6639 op,
6640 inputs: vec![self.id],
6641 shape,
6642 dtype,
6643 });
6644 Self {
6645 graph: self.graph.clone(),
6646 id,
6647 }
6648 }
6649
6650 /// Result-returning sibling of [`Self::broadcast_to`]. Surfaces
6651 /// shape incompatibility as a typed error rather than panicking.
6652 pub fn try_broadcast_to(
6653 &self,
6654 target: impl Into<Shape>,
6655 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6656 let target = target.into();
6657 let src_dims = self.shape();
6658 try_check_broadcast_compatible(src_dims.dims(), target.dims())?;
6659 let op = Op::BroadcastTo(target);
6660 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6661 let id = self.graph.write().unwrap().push(Node {
6662 op,
6663 inputs: vec![self.id],
6664 shape,
6665 dtype,
6666 });
6667 Ok(Self {
6668 graph: self.graph.clone(),
6669 id,
6670 })
6671 }
6672
6673 /// Append an `Unsqueeze` node that inserts a size-1 dimension at
6674 /// position `dim`. `dim` must be in `0..=rank` (where `dim == rank`
6675 /// appends to the end). Pure metadata — the output shares bytes
6676 /// with `self`, with a new size-1 axis layered into the Layout
6677 /// side-table. Strictly more efficient than `reshape` for the
6678 /// size-1-insertion case because non-contiguous (e.g. transposed
6679 /// or broadcast) inputs flow through without auto-Contiguize.
6680 pub fn unsqueeze(&self, dim: usize) -> NodeHandle {
6681 let in_shape = self.shape();
6682 let rank = in_shape.dims().len();
6683 assert!(
6684 dim <= rank,
6685 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6686 );
6687 let op = Op::Unsqueeze { dim };
6688 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6689 .expect("unsqueeze: dim validated above");
6690 let id = self.graph.write().unwrap().push(Node {
6691 op,
6692 inputs: vec![self.id],
6693 shape,
6694 dtype,
6695 });
6696 Self {
6697 graph: self.graph.clone(),
6698 id,
6699 }
6700 }
6701
6702 /// Result-returning sibling of [`Self::unsqueeze`]. Surfaces
6703 /// `dim > rank` as a typed error rather than panicking.
6704 pub fn try_unsqueeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6705 let in_shape = self.shape();
6706 let rank = in_shape.dims().len();
6707 if dim > rank {
6708 return Err(fuel_ir::Error::Msg(format!(
6709 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6710 ))
6711 .bt());
6712 }
6713 let op = Op::Unsqueeze { dim };
6714 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6715 let id = self.graph.write().unwrap().push(Node {
6716 op,
6717 inputs: vec![self.id],
6718 shape,
6719 dtype,
6720 });
6721 Ok(Self {
6722 graph: self.graph.clone(),
6723 id,
6724 })
6725 }
6726
6727 /// Append a `Squeeze` node that drops the size-1 dimension at
6728 /// position `dim` (range `0..rank`). Inverse of [`Self::unsqueeze`].
6729 /// Metadata-only view: the output shares bytes with `self`, with
6730 /// the named dim pruned from the Layout side-table.
6731 ///
6732 /// **Returns `Result`** rather than panicking — production paths
6733 /// can recover from a bad `dim` instead of crashing. Bad `dim`
6734 /// (out of bounds OR `shape[dim] != 1`) surfaces as a typed error.
6735 pub fn squeeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6736 let in_shape = self.shape();
6737 let rank = in_shape.dims().len();
6738 if dim >= rank {
6739 return Err(fuel_ir::Error::Msg(format!(
6740 "squeeze: dim {dim} out of bounds for rank {rank} (must be < rank)",
6741 ))
6742 .bt());
6743 }
6744 if in_shape.dims()[dim] != 1 {
6745 return Err(fuel_ir::Error::Msg(format!(
6746 "squeeze: dim {dim} has size {}, expected 1",
6747 in_shape.dims()[dim],
6748 ))
6749 .bt());
6750 }
6751 let op = Op::Squeeze { dim };
6752 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6753 let id = self.graph.write().unwrap().push(Node {
6754 op,
6755 inputs: vec![self.id],
6756 shape,
6757 dtype,
6758 });
6759 Ok(Self {
6760 graph: self.graph.clone(),
6761 id,
6762 })
6763 }
6764
6765 /// Append an `Op::Contiguize` node that materializes a
6766 /// contiguous copy of `self`. Output shape and dtype match the
6767 /// input; only the layout changes to contiguous + zero-offset.
6768 /// Zero-copy when the input is already contiguous + zero-offset
6769 /// (the executor adopts the input Storage Arc unchanged).
6770 ///
6771 /// First-class IR node so the optimizer (Phase 2.2) can insert
6772 /// layout-fixups before kernels that don't advertise
6773 /// `crate::KernelCaps::strided_input` without overloading
6774 /// [`Self::reshape`]'s "change shape" semantics.
6775 pub fn contiguize(&self) -> NodeHandle {
6776 let shape = self.shape().clone();
6777 let dtype = self.dtype();
6778 let id = self.graph.write().unwrap().push(Node {
6779 op: Op::Contiguize,
6780 inputs: vec![self.id],
6781 shape,
6782 dtype,
6783 });
6784 Self {
6785 graph: self.graph.clone(),
6786 id,
6787 }
6788 }
6789
6790 /// Append a `Reshape` node producing `self`'s data under a new shape.
6791 /// The new shape must have the same total element count as the
6792 /// current shape.
6793 pub fn reshape(&self, target: impl Into<Shape>) -> NodeHandle {
6794 let target = target.into();
6795 assert_eq!(
6796 self.shape().elem_count(),
6797 target.elem_count(),
6798 "reshape: element count mismatch: from {} to {}",
6799 self.shape().elem_count(),
6800 target.elem_count(),
6801 );
6802 let op = Op::Reshape(target);
6803 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6804 .expect("reshape: element count validated above");
6805 let id = self.graph.write().unwrap().push(Node {
6806 op,
6807 inputs: vec![self.id],
6808 shape,
6809 dtype,
6810 });
6811 Self {
6812 graph: self.graph.clone(),
6813 id,
6814 }
6815 }
6816
6817 /// Result-returning sibling of [`Self::reshape`]. Surfaces
6818 /// element-count mismatch as a typed error rather than panicking.
6819 pub fn try_reshape(
6820 &self,
6821 target: impl Into<Shape>,
6822 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6823 let target = target.into();
6824 let from = self.shape().elem_count();
6825 let to = target.elem_count();
6826 if from != to {
6827 return Err(fuel_ir::Error::Msg(format!(
6828 "reshape: element count mismatch: from {from} to {to}",
6829 ))
6830 .bt());
6831 }
6832 let op = Op::Reshape(target);
6833 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6834 let id = self.graph.write().unwrap().push(Node {
6835 op,
6836 inputs: vec![self.id],
6837 shape,
6838 dtype,
6839 });
6840 Ok(Self {
6841 graph: self.graph.clone(),
6842 id,
6843 })
6844 }
6845
6846 /// Append a `ReduceSumTo` node that sum-reduces `self` to a smaller
6847 /// shape. The target must be reachable from `self.shape()` via
6848 /// reduction of dims (i.e. `self.shape()` could be produced from
6849 /// `target` by broadcasting).
6850 pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> NodeHandle {
6851 let target = target.into();
6852 // Symmetric check: self must be broadcast-compatible FROM the
6853 // smaller target. That is, the target must be broadcast-ready to
6854 // self.shape().
6855 check_broadcast_compatible(target.dims(), self.shape().dims());
6856 let op = Op::ReduceSumTo(target);
6857 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6858 .expect("reduce_sum_to: compatibility validated above");
6859 let id = self.graph.write().unwrap().push(Node {
6860 op,
6861 inputs: vec![self.id],
6862 shape,
6863 dtype,
6864 });
6865 Self {
6866 graph: self.graph.clone(),
6867 id,
6868 }
6869 }
6870
6871 /// Append a `ReduceMaxTo` node that max-reduces `self` to a smaller
6872 /// shape — the max-symmetric counterpart of [`Self::reduce_sum_to`].
6873 /// The target must be reachable from `self.shape()` via reduction
6874 /// of dims (i.e. `self.shape()` could be produced from `target` by
6875 /// broadcasting).
6876 pub fn reduce_max_to(&self, target: impl Into<Shape>) -> NodeHandle {
6877 let target = target.into();
6878 check_broadcast_compatible(target.dims(), self.shape().dims());
6879 let op = Op::ReduceMaxTo(target);
6880 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6881 .expect("reduce_max_to: compatibility validated above");
6882 let id = self.graph.write().unwrap().push(Node {
6883 op,
6884 inputs: vec![self.id],
6885 shape,
6886 dtype,
6887 });
6888 Self {
6889 graph: self.graph.clone(),
6890 id,
6891 }
6892 }
6893
6894 // --- reductions to a scalar ---
6895
6896 /// Append a `SumAll` node reducing every element to a scalar (rank-0).
6897 pub fn sum_all(&self) -> NodeHandle {
6898 self.scalar_reduction(Op::SumAll)
6899 }
6900
6901 /// Append a `MaxAll` node producing the max element as a scalar.
6902 pub fn max_all(&self) -> NodeHandle {
6903 self.scalar_reduction(Op::MaxAll)
6904 }
6905
6906 /// Append a `MinAll` node producing the min element as a scalar.
6907 pub fn min_all(&self) -> NodeHandle {
6908 self.scalar_reduction(Op::MinAll)
6909 }
6910
6911 /// Append a `MeanAll` node producing the arithmetic mean as a scalar.
6912 pub fn mean_all(&self) -> NodeHandle {
6913 self.scalar_reduction(Op::MeanAll)
6914 }
6915
6916 // --- reductions along one dimension ---
6917
6918 /// Append a `SumDim(dim)` node. Reduces along `dim`; output rank is
6919 /// `input rank - 1` (the reduced dim is removed).
6920 pub fn sum_dim(&self, dim: usize) -> NodeHandle {
6921 self.axis_reduction("sum_dim", Op::SumDim(dim), dim)
6922 }
6923
6924 /// Append a `MaxDim(dim)` node.
6925 pub fn max_dim(&self, dim: usize) -> NodeHandle {
6926 self.axis_reduction("max_dim", Op::MaxDim(dim), dim)
6927 }
6928
6929 /// Append a `MinDim(dim)` node.
6930 pub fn min_dim(&self, dim: usize) -> NodeHandle {
6931 self.axis_reduction("min_dim", Op::MinDim(dim), dim)
6932 }
6933
6934 /// Append a `MeanDim(dim)` node.
6935 pub fn mean_dim(&self, dim: usize) -> NodeHandle {
6936 self.axis_reduction("mean_dim", Op::MeanDim(dim), dim)
6937 }
6938
6939 /// Append an `ArgMaxDim(dim)` node. Produces a U32 tensor with the
6940 /// reduced dim removed, whose values are the index of the maximum
6941 /// along that dim. Non-differentiable — trying to run `backward()`
6942 /// through an ArgMax node will panic.
6943 pub fn argmax_dim(&self, dim: usize) -> NodeHandle {
6944 self.index_reduction("argmax_dim", Op::ArgMaxDim(dim), dim)
6945 }
6946
6947 /// Append an `ArgMinDim(dim)` node. Same semantics as `argmax_dim`
6948 /// but for the minimum.
6949 pub fn argmin_dim(&self, dim: usize) -> NodeHandle {
6950 self.index_reduction("argmin_dim", Op::ArgMinDim(dim), dim)
6951 }
6952
6953 /// Internal helper for index-producing reductions. Validates the
6954 /// dim, builds the reduced shape, and stamps the output with
6955 /// `DType::U32` regardless of the input dtype.
6956 fn index_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
6957 let in_shape = self.shape();
6958 assert!(
6959 dim < in_shape.dims().len(),
6960 "{name}: dim {dim} out of bounds for shape {:?}",
6961 in_shape.dims(),
6962 );
6963 // primitive_shape carries both the rank-reduced shape and the U32
6964 // index dtype for ArgMaxDim/ArgMinDim (the single source of truth).
6965 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6966 .expect("index_reduction: dim validated above");
6967 let id = self.graph.write().unwrap().push(Node {
6968 op,
6969 inputs: vec![self.id],
6970 shape,
6971 dtype,
6972 });
6973 Self {
6974 graph: self.graph.clone(),
6975 id,
6976 }
6977 }
6978
6979 // --- compositions ---
6980
6981 /// Append a `SoftmaxLastDim` node. Shape is preserved.
6982 ///
6983 /// Phase 7.6 step 3: emits `Op::Fused(FusedOps::SOFTMAX_LAST_DIM,
6984 /// FusedOpParams::SoftmaxLastDim)` — the registry-extended arm.
6985 /// The legacy `Op::SoftmaxLastDim` variant remains in the enum
6986 /// during the migration; step 5 drops it once nothing emits it.
6987 pub fn softmax_last_dim(&self) -> NodeHandle {
6988 assert!(
6989 !self.shape().dims().is_empty(),
6990 "softmax_last_dim: input must be rank >= 1",
6991 );
6992 self.unary_op(Op::Fused(
6993 crate::registry::FusedOps::SOFTMAX_LAST_DIM,
6994 crate::registry::FusedOpParams::SoftmaxLastDim,
6995 ))
6996 }
6997
6998 /// Append a `CausalConv1d` node — depthwise 1-D causal convolution
6999 /// + bias + optional fused SiLU. Three inputs:
7000 /// - `self` (x): `[batch, channels, seq + kernel - 1]` F32
7001 /// (caller pre-pads with `kernel - 1` zeros on the left for the
7002 /// causal mask — matches Mamba-2's prefill convention).
7003 /// - `weight`: `[channels, 1, kernel]` F32 (depthwise — one filter
7004 /// per channel; `groups == channels`).
7005 /// - `bias`: `[channels]` F32 (required — matches baracuda's
7006 /// `causal_conv1d_*_run` signature; pass zeros if you don't want
7007 /// a bias).
7008 ///
7009 /// Output: `[batch, channels, seq]` F32 where `seq = x.dims[2] -
7010 /// (kernel - 1)`.
7011 ///
7012 /// Emits `Op::Fused(FusedOps::CAUSAL_CONV1D,
7013 /// FusedOpParams::CausalConv1d { use_silu })`. See
7014 /// `fuel-graph/src/registry/causal_conv1d.rs` for the registry
7015 /// entry. No primitive decomposition exists (fuel-graph has no
7016 /// `Op::Conv1D`); backends without a native kernel fall through
7017 /// to the executor's cpu_fallback path.
7018 ///
7019 /// # Panics
7020 ///
7021 /// Panics if any operand belongs to a different [`Graph`] than the one this
7022 /// builder is building into. Operand identity is graph-scoped and checked by
7023 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7024 /// deliberate and replaces the hang a cross-graph handle used to produce.
7025 /// Build every operand from one graph, or use a `Result`-returning entry
7026 /// point where one exists.
7027 pub fn causal_conv1d(
7028 &self,
7029 weight: &NodeHandle,
7030 bias: &NodeHandle,
7031 use_silu: bool,
7032 ) -> NodeHandle {
7033 assert!(
7034 Arc::ptr_eq(&self.graph, &weight.graph) && Arc::ptr_eq(&self.graph, &bias.graph),
7035 "causal_conv1d: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7036 );
7037 let dtype = self.dtype();
7038 assert!(
7039 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7040 "causal_conv1d: x must be F32/F64/BF16/F16, got {dtype:?}",
7041 );
7042 assert_eq!(
7043 weight.dtype(),
7044 dtype,
7045 "causal_conv1d: weight dtype {:?} must match x dtype {dtype:?}",
7046 weight.dtype(),
7047 );
7048 assert_eq!(
7049 bias.dtype(),
7050 dtype,
7051 "causal_conv1d: bias dtype {:?} must match x dtype {dtype:?}",
7052 bias.dtype(),
7053 );
7054 let x_dims = self.shape();
7055 let x_dims = x_dims.dims();
7056 let w_dims = weight.shape();
7057 let w_dims = w_dims.dims();
7058 let b_dims = bias.shape();
7059 let b_dims = b_dims.dims();
7060 assert_eq!(
7061 x_dims.len(),
7062 3,
7063 "causal_conv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
7064 );
7065 assert_eq!(
7066 w_dims.len(),
7067 3,
7068 "causal_conv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
7069 );
7070 assert_eq!(
7071 b_dims.len(),
7072 1,
7073 "causal_conv1d: bias must be rank 1 [channels], got {b_dims:?}",
7074 );
7075 let batch = x_dims[0];
7076 let channels = x_dims[1];
7077 let x_seq = x_dims[2];
7078 let kernel = w_dims[2];
7079 assert_eq!(
7080 w_dims[0], channels,
7081 "causal_conv1d: weight's first dim {} must equal channels {channels}",
7082 w_dims[0],
7083 );
7084 assert_eq!(
7085 w_dims[1], 1,
7086 "causal_conv1d: weight's middle dim must be 1 (depthwise), got {}",
7087 w_dims[1],
7088 );
7089 assert_eq!(
7090 b_dims[0], channels,
7091 "causal_conv1d: bias length {} must equal channels {channels}",
7092 b_dims[0],
7093 );
7094 assert!(
7095 x_seq >= kernel - 1,
7096 "causal_conv1d: x time dim {x_seq} must be ≥ kernel - 1 = {} \
7097 (caller must pre-pad with {} zeros)",
7098 kernel - 1,
7099 kernel - 1,
7100 );
7101 let out_seq = x_seq - (kernel - 1);
7102 let id = self.graph.write().unwrap().push(Node {
7103 op: Op::Fused(
7104 crate::registry::FusedOps::CAUSAL_CONV1D,
7105 crate::registry::FusedOpParams::CausalConv1d { use_silu },
7106 ),
7107 inputs: vec![self.id, weight.id, bias.id],
7108 shape: Shape::from_dims(&[batch, channels, out_seq]),
7109 dtype,
7110 });
7111 Self {
7112 graph: self.graph.clone(),
7113 id,
7114 }
7115 }
7116
7117 /// Append an `Nf4Matmul` node — bitsandbytes-style 4-bit
7118 /// NormalFloat quantized matrix multiply. Three inputs:
7119 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7120 /// - `w_packed`: `[N, K/2]` U8 (two 4-bit codes per byte)
7121 /// - `absmax`: `[N, K/block_size]` F32 (per-output-row, per-block)
7122 ///
7123 /// Output: `[..., M, N]` matching activations' dtype.
7124 ///
7125 /// `block_size` is the NF4 quantization block size (typically 64
7126 /// in bitsandbytes). `K` must be even AND a multiple of
7127 /// `block_size`.
7128 ///
7129 /// Emits `Op::Fused(FusedOps::NF4_MATMUL, FusedOpParams::Nf4Matmul
7130 /// { block_size })`. No primitive decomposition (the dequant +
7131 /// matmul roundtrip is exactly what NF4's fused dequant-in-kernel
7132 /// design avoids); backends without a native kernel fall through
7133 /// to the executor's cpu_fallback path.
7134 ///
7135 /// # Panics
7136 ///
7137 /// Panics if any operand belongs to a different [`Graph`] than the one this
7138 /// builder is building into. Operand identity is graph-scoped and checked by
7139 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7140 /// deliberate and replaces the hang a cross-graph handle used to produce.
7141 /// Build every operand from one graph, or use a `Result`-returning entry
7142 /// point where one exists.
7143 pub fn nf4_matmul(
7144 &self,
7145 w_packed: &NodeHandle,
7146 absmax: &NodeHandle,
7147 block_size: usize,
7148 ) -> NodeHandle {
7149 assert!(
7150 Arc::ptr_eq(&self.graph, &w_packed.graph) && Arc::ptr_eq(&self.graph, &absmax.graph),
7151 "nf4_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7152 );
7153 let act_dtype = self.dtype();
7154 assert!(
7155 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7156 "nf4_matmul v1: activations must be F32/F16/BF16, got {:?}",
7157 act_dtype,
7158 );
7159 assert_eq!(
7160 w_packed.dtype(),
7161 DType::U8,
7162 "nf4_matmul: w_packed must be U8 (two 4-bit codes per byte), got {:?}",
7163 w_packed.dtype(),
7164 );
7165 assert_eq!(
7166 absmax.dtype(),
7167 DType::F32,
7168 "nf4_matmul: absmax must be F32, got {:?}",
7169 absmax.dtype(),
7170 );
7171 let a_dims = self.shape();
7172 let a_dims = a_dims.dims();
7173 let w_dims = w_packed.shape();
7174 let w_dims = w_dims.dims();
7175 let abs_dims = absmax.shape();
7176 let abs_dims = abs_dims.dims();
7177 assert!(
7178 a_dims.len() >= 2,
7179 "nf4_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7180 );
7181 assert_eq!(
7182 w_dims.len(),
7183 2,
7184 "nf4_matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
7185 );
7186 assert_eq!(
7187 abs_dims.len(),
7188 2,
7189 "nf4_matmul: absmax must be rank 2 [n, k/block_size], got {abs_dims:?}",
7190 );
7191 let _m = a_dims[a_dims.len() - 2];
7192 let k = a_dims[a_dims.len() - 1];
7193 let n = w_dims[0];
7194 assert!(
7195 k.is_multiple_of(2),
7196 "nf4_matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
7197 );
7198 assert!(
7199 block_size > 0 && k.is_multiple_of(block_size),
7200 "nf4_matmul: k={k} must be a positive multiple of block_size={block_size}",
7201 );
7202 assert_eq!(
7203 w_dims[1],
7204 k / 2,
7205 "nf4_matmul: w_packed second dim {} must equal k/2 = {}",
7206 w_dims[1],
7207 k / 2,
7208 );
7209 assert_eq!(
7210 abs_dims,
7211 &[n, k / block_size][..],
7212 "nf4_matmul: absmax {abs_dims:?} must be [n={n}, k/block_size={}]",
7213 k / block_size,
7214 );
7215 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7216 out_dims.push(n);
7217 let id = self.graph.write().unwrap().push(Node {
7218 op: Op::Fused(
7219 crate::registry::FusedOps::NF4_MATMUL,
7220 crate::registry::FusedOpParams::Nf4Matmul { block_size },
7221 ),
7222 inputs: vec![self.id, w_packed.id, absmax.id],
7223 shape: Shape::from_dims(&out_dims),
7224 dtype: act_dtype,
7225 });
7226 Self {
7227 graph: self.graph.clone(),
7228 id,
7229 }
7230 }
7231
7232 /// Append an `AwqMatmul` node — AWQ (mit-han-lab) asymmetric int4
7233 /// weight-only matrix multiply. Four inputs:
7234 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7235 /// - `qweight`: `[N, K/8]` U32 (eight int4 codes packed per word)
7236 /// - `qzeros`: `[K/group_size, N/8]` U32 (eight int4 zero-point
7237 /// codes packed per word)
7238 /// - `scales`: `[K/group_size, N]` F32 (per-group, per-output-
7239 /// channel scale)
7240 ///
7241 /// Output: `[..., M, N]` matching activations' dtype.
7242 ///
7243 /// `group_size` must be positive and evenly divide `K`. `K` must be a
7244 /// multiple of 8 (`qweight`'s packing); `N` must be a multiple of 8
7245 /// (`qzeros`' packing). `split_k_iters` is a CUDA launch-tuning
7246 /// parameter carried through unused by the (current, decompose-only)
7247 /// execution path — see [`crate::registry::awq_matmul`]'s module doc
7248 /// for what is and isn't wired/verified yet, including the
7249 /// packing-order caveat.
7250 ///
7251 /// Emits `Op::Fused(FusedOps::AWQ_MATMUL, FusedOpParams::AwqMatmul
7252 /// { group_size, split_k_iters })`.
7253 ///
7254 /// # Panics
7255 ///
7256 /// Panics if any operand belongs to a different [`Graph`] than the one
7257 /// this builder is building into, or if any shape/dtype precondition
7258 /// above doesn't hold — same discipline as [`Self::nf4_matmul`].
7259 #[allow(clippy::too_many_arguments)]
7260 pub fn awq_matmul(
7261 &self,
7262 qweight: &NodeHandle,
7263 qzeros: &NodeHandle,
7264 scales: &NodeHandle,
7265 group_size: usize,
7266 split_k_iters: i32,
7267 ) -> NodeHandle {
7268 assert!(
7269 Arc::ptr_eq(&self.graph, &qweight.graph)
7270 && Arc::ptr_eq(&self.graph, &qzeros.graph)
7271 && Arc::ptr_eq(&self.graph, &scales.graph),
7272 "awq_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7273 );
7274 let act_dtype = self.dtype();
7275 assert!(
7276 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7277 "awq_matmul v1: activations must be F32/F16/BF16, got {:?}",
7278 act_dtype,
7279 );
7280 assert_eq!(
7281 qweight.dtype(),
7282 DType::U32,
7283 "awq_matmul: qweight must be U32 (eight 4-bit codes per word), got {:?}",
7284 qweight.dtype(),
7285 );
7286 assert_eq!(
7287 qzeros.dtype(),
7288 DType::U32,
7289 "awq_matmul: qzeros must be U32 (eight 4-bit codes per word), got {:?}",
7290 qzeros.dtype(),
7291 );
7292 assert_eq!(
7293 scales.dtype(),
7294 DType::F32,
7295 "awq_matmul: scales must be F32, got {:?}",
7296 scales.dtype(),
7297 );
7298 let a_dims = self.shape();
7299 let a_dims = a_dims.dims();
7300 let w_dims = qweight.shape();
7301 let w_dims = w_dims.dims();
7302 let z_dims = qzeros.shape();
7303 let z_dims = z_dims.dims();
7304 let s_dims = scales.shape();
7305 let s_dims = s_dims.dims();
7306 assert!(
7307 a_dims.len() >= 2,
7308 "awq_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7309 );
7310 assert_eq!(
7311 w_dims.len(),
7312 2,
7313 "awq_matmul: qweight must be rank 2 [N, K/8], got {w_dims:?}",
7314 );
7315 assert_eq!(
7316 z_dims.len(),
7317 2,
7318 "awq_matmul: qzeros must be rank 2 [K/group_size, N/8], got {z_dims:?}",
7319 );
7320 assert_eq!(
7321 s_dims.len(),
7322 2,
7323 "awq_matmul: scales must be rank 2 [K/group_size, N], got {s_dims:?}",
7324 );
7325 let _m = a_dims[a_dims.len() - 2];
7326 let k = a_dims[a_dims.len() - 1];
7327 let n = w_dims[0];
7328 assert!(
7329 k.is_multiple_of(8),
7330 "awq_matmul: k={k} must be a multiple of 8 (qweight packs 8 codes per word along k)",
7331 );
7332 assert!(
7333 n.is_multiple_of(8),
7334 "awq_matmul: n={n} must be a multiple of 8 (qzeros packs 8 codes per word along n)",
7335 );
7336 assert!(
7337 group_size > 0 && k.is_multiple_of(group_size),
7338 "awq_matmul: k={k} must be a positive multiple of group_size={group_size}",
7339 );
7340 assert_eq!(
7341 w_dims[1],
7342 k / 8,
7343 "awq_matmul: qweight second dim {} must equal k/8 = {}",
7344 w_dims[1],
7345 k / 8,
7346 );
7347 let n_groups = k / group_size;
7348 assert_eq!(
7349 z_dims,
7350 &[n_groups, n / 8][..],
7351 "awq_matmul: qzeros {z_dims:?} must be [k/group_size={n_groups}, n/8={}]",
7352 n / 8,
7353 );
7354 assert_eq!(
7355 s_dims,
7356 &[n_groups, n][..],
7357 "awq_matmul: scales {s_dims:?} must be [k/group_size={n_groups}, n={n}]",
7358 );
7359 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7360 out_dims.push(n);
7361 let id = self.graph.write().unwrap().push(Node {
7362 op: Op::Fused(
7363 crate::registry::FusedOps::AWQ_MATMUL,
7364 crate::registry::FusedOpParams::AwqMatmul {
7365 group_size,
7366 split_k_iters,
7367 },
7368 ),
7369 inputs: vec![self.id, qweight.id, qzeros.id, scales.id],
7370 shape: Shape::from_dims(&out_dims),
7371 dtype: act_dtype,
7372 });
7373 Self {
7374 graph: self.graph.clone(),
7375 id,
7376 }
7377 }
7378
7379 /// Append an `SsdChunkScan` node — Mamba-2's State-Space
7380 /// Duality chunked scan (forward). Five inputs:
7381 /// - `self` (x): `[batch, seqlen, heads, head_dim]` F32
7382 /// - `dt`: `[batch, seqlen, heads]` F32
7383 /// - `a`: `[heads]` F32 (per-head scalar log A)
7384 /// - `b`: `[batch, seqlen, heads, state_dim]` F32
7385 /// - `c`: `[batch, seqlen, heads, state_dim]` F32
7386 ///
7387 /// Output: `y: [batch, seqlen, heads, head_dim]` F32 (same as x).
7388 ///
7389 /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
7390 /// It controls GPU parallelism granularity but the mathematical
7391 /// result is identical to a sequential scan; the CPU kernel runs
7392 /// sequential regardless. Validation: `chunk_size > 0` and
7393 /// `seqlen % chunk_size == 0`.
7394 ///
7395 /// Emits `Op::Fused(FusedOps::SSD_CHUNK_SCAN,
7396 /// FusedOpParams::SsdChunkScan { chunk_size })`. No primitive
7397 /// decomposition; backends without a native kernel fall through
7398 /// to the executor's cpu_fallback path.
7399 /// Internal: build the bundled SsdChunkScan producer node and
7400 /// return its NodeId. Callers project per-slot via
7401 /// [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7402 fn ssd_chunk_scan_producer(
7403 &self,
7404 dt: &NodeHandle,
7405 a: &NodeHandle,
7406 b: &NodeHandle,
7407 c: &NodeHandle,
7408 chunk_size: usize,
7409 ) -> NodeHandle {
7410 assert!(
7411 Arc::ptr_eq(&self.graph, &dt.graph)
7412 && Arc::ptr_eq(&self.graph, &a.graph)
7413 && Arc::ptr_eq(&self.graph, &b.graph)
7414 && Arc::ptr_eq(&self.graph, &c.graph),
7415 "ssd_chunk_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7416 );
7417 let dtype = self.dtype();
7418 assert!(
7419 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7420 "ssd_chunk_scan: x must be F32/F64/BF16/F16, got {dtype:?}",
7421 );
7422 for (name, t) in [("dt", dt), ("a", a), ("b", b), ("c", c)] {
7423 assert_eq!(
7424 t.dtype(),
7425 dtype,
7426 "ssd_chunk_scan: {name} dtype {:?} must match x dtype {dtype:?}",
7427 t.dtype(),
7428 );
7429 }
7430 let x_dims = self.shape();
7431 let x_dims = x_dims.dims();
7432 let dt_dims = dt.shape();
7433 let dt_dims = dt_dims.dims();
7434 let a_dims = a.shape();
7435 let a_dims = a_dims.dims();
7436 let b_dims = b.shape();
7437 let b_dims = b_dims.dims();
7438 let c_dims = c.shape();
7439 let c_dims = c_dims.dims();
7440 assert_eq!(
7441 x_dims.len(),
7442 4,
7443 "ssd_chunk_scan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
7444 );
7445 let batch = x_dims[0];
7446 let seqlen = x_dims[1];
7447 let heads = x_dims[2];
7448 let head_dim = x_dims[3];
7449 assert_eq!(
7450 dt_dims,
7451 &[batch, seqlen, heads][..],
7452 "ssd_chunk_scan: dt {dt_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}]",
7453 );
7454 assert_eq!(
7455 a_dims,
7456 &[heads][..],
7457 "ssd_chunk_scan: a {a_dims:?} must be [heads={heads}]",
7458 );
7459 assert_eq!(
7460 b_dims.len(),
7461 4,
7462 "ssd_chunk_scan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
7463 );
7464 let state_dim = b_dims[3];
7465 assert_eq!(
7466 b_dims,
7467 &[batch, seqlen, heads, state_dim][..],
7468 "ssd_chunk_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}, state_dim={state_dim}]",
7469 );
7470 assert_eq!(
7471 c_dims,
7472 &[batch, seqlen, heads, state_dim][..],
7473 "ssd_chunk_scan: c {c_dims:?} must match b shape",
7474 );
7475 let params = crate::registry::FusedOpParams::SsdChunkScan { chunk_size };
7476 let input_shapes = [
7477 Shape::from_dims(x_dims),
7478 Shape::from_dims(dt_dims),
7479 Shape::from_dims(a_dims),
7480 Shape::from_dims(b_dims),
7481 Shape::from_dims(c_dims),
7482 ];
7483 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7484 let entry = crate::registry::default_registry()
7485 .entry(crate::registry::FusedOps::SSD_CHUNK_SCAN)
7486 .expect("SSD_CHUNK_SCAN registered");
7487 let specs =
7488 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7489 let (_total_bytes, views) =
7490 fuel_ir::storage::compose_bundle(&specs).expect("SsdChunkScan compose_bundle");
7491 let mut g = self.graph.write().unwrap();
7492 let id = g.push(Node {
7493 op: Op::Fused(crate::registry::FusedOps::SSD_CHUNK_SCAN, params),
7494 inputs: vec![self.id, dt.id, a.id, b.id, c.id],
7495 shape: Shape::from_dims(&[batch, seqlen, heads, head_dim]),
7496 dtype,
7497 });
7498 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7499 .expect("SsdChunkScan set_output_views");
7500 drop(g);
7501 Self {
7502 graph: self.graph.clone(),
7503 id,
7504 }
7505 }
7506
7507 /// Single-output SsdChunkScan: returns the `y` slot of the
7508 /// bundled producer (View(0)). See
7509 /// [`Self::ssd_chunk_scan_bundled`] for the multi-output variant.
7510 ///
7511 /// # Panics
7512 ///
7513 /// Panics if any operand belongs to a different [`Graph`] than the one this
7514 /// builder is building into. Operand identity is graph-scoped and checked by
7515 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7516 /// deliberate and replaces the hang a cross-graph handle used to produce.
7517 /// Build every operand from one graph, or use a `Result`-returning entry
7518 /// point where one exists.
7519 pub fn ssd_chunk_scan(
7520 &self,
7521 dt: &NodeHandle,
7522 a: &NodeHandle,
7523 b: &NodeHandle,
7524 c: &NodeHandle,
7525 chunk_size: usize,
7526 ) -> NodeHandle {
7527 self.assert_same_graph(dt, "ssd_chunk_scan", "dt");
7528 self.assert_same_graph(a, "ssd_chunk_scan", "a");
7529 self.assert_same_graph(b, "ssd_chunk_scan", "b");
7530 self.assert_same_graph(c, "ssd_chunk_scan", "c");
7531 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7532 producer
7533 .view(0)
7534 .expect("SsdChunkScan view(0) must succeed (just registered slots)")
7535 }
7536
7537 /// Append a `SelectiveScan` node — Mamba-1's selective
7538 /// state-space scan (forward). Five inputs:
7539 /// - `self` (u): `[batch, seqlen, dim]` F32
7540 /// - `delta`: `[batch, seqlen, dim]` F32
7541 /// - `a`: `[dim, dstate]` F32
7542 /// - `b`: `[batch, seqlen, dstate]` F32
7543 /// - `c`: `[batch, seqlen, dstate]` F32
7544 ///
7545 /// Output: `y: [batch, seqlen, dim]` F32.
7546 ///
7547 /// `delta_softplus` toggles the softplus(delta) activation before
7548 /// use (matches baracuda's `selective_scan_*_run` flag). The v1
7549 /// op surface skips the optional `d_skip`, `z`, `delta_bias`
7550 /// inputs and the `last_state` second output — see
7551 /// `fuel-graph/src/registry/selective_scan.rs` for the rationale.
7552 ///
7553 /// Emits `Op::Fused(FusedOps::SELECTIVE_SCAN,
7554 /// FusedOpParams::SelectiveScan { delta_softplus })`. No
7555 /// primitive decomposition exists (the scan is a sequential
7556 /// recurrence); backends without a native kernel fall through to
7557 /// the executor's cpu_fallback path.
7558 /// Internal: build the bundled SelectiveScan producer node and
7559 /// return its NodeId (wrapped in a `NodeHandle`). Callers project
7560 /// per-slot via [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7561 fn selective_scan_producer(
7562 &self,
7563 delta: &NodeHandle,
7564 a: &NodeHandle,
7565 b: &NodeHandle,
7566 c: &NodeHandle,
7567 delta_softplus: bool,
7568 ) -> NodeHandle {
7569 assert!(
7570 Arc::ptr_eq(&self.graph, &delta.graph)
7571 && Arc::ptr_eq(&self.graph, &a.graph)
7572 && Arc::ptr_eq(&self.graph, &b.graph)
7573 && Arc::ptr_eq(&self.graph, &c.graph),
7574 "selective_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7575 );
7576 let dtype = self.dtype();
7577 assert!(
7578 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7579 "selective_scan: u must be F32/F64/BF16/F16, got {dtype:?}",
7580 );
7581 for (name, t) in [("delta", delta), ("a", a), ("b", b), ("c", c)] {
7582 assert_eq!(
7583 t.dtype(),
7584 dtype,
7585 "selective_scan: {name} dtype {:?} must match u dtype {dtype:?}",
7586 t.dtype(),
7587 );
7588 }
7589 let u_dims = self.shape();
7590 let u_dims = u_dims.dims();
7591 let delta_dims = delta.shape();
7592 let delta_dims = delta_dims.dims();
7593 let a_dims = a.shape();
7594 let a_dims = a_dims.dims();
7595 let b_dims = b.shape();
7596 let b_dims = b_dims.dims();
7597 let c_dims = c.shape();
7598 let c_dims = c_dims.dims();
7599 assert_eq!(
7600 u_dims.len(),
7601 3,
7602 "selective_scan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
7603 );
7604 assert_eq!(
7605 delta_dims, u_dims,
7606 "selective_scan: delta {delta_dims:?} must match u {u_dims:?}",
7607 );
7608 assert_eq!(
7609 a_dims.len(),
7610 2,
7611 "selective_scan: a must be rank 2 [dim, dstate], got {a_dims:?}",
7612 );
7613 let batch = u_dims[0];
7614 let seqlen = u_dims[1];
7615 let dim = u_dims[2];
7616 let dstate = a_dims[1];
7617 assert_eq!(
7618 a_dims[0], dim,
7619 "selective_scan: a's first dim {} must equal dim {dim}",
7620 a_dims[0],
7621 );
7622 assert_eq!(
7623 b_dims,
7624 &[batch, seqlen, dstate][..],
7625 "selective_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7626 );
7627 assert_eq!(
7628 c_dims,
7629 &[batch, seqlen, dstate][..],
7630 "selective_scan: c {c_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7631 );
7632 let params = crate::registry::FusedOpParams::SelectiveScan { delta_softplus };
7633 let input_shapes = [
7634 Shape::from_dims(u_dims),
7635 Shape::from_dims(delta_dims),
7636 Shape::from_dims(a_dims),
7637 Shape::from_dims(b_dims),
7638 Shape::from_dims(c_dims),
7639 ];
7640 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7641 let entry = crate::registry::default_registry()
7642 .entry(crate::registry::FusedOps::SELECTIVE_SCAN)
7643 .expect("SELECTIVE_SCAN registered");
7644 let specs =
7645 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7646 let (_total_bytes, views) =
7647 fuel_ir::storage::compose_bundle(&specs).expect("SelectiveScan compose_bundle");
7648 let mut g = self.graph.write().unwrap();
7649 let id = g.push(Node {
7650 op: Op::Fused(crate::registry::FusedOps::SELECTIVE_SCAN, params),
7651 inputs: vec![self.id, delta.id, a.id, b.id, c.id],
7652 shape: Shape::from_dims(&[batch, seqlen, dim]),
7653 dtype,
7654 });
7655 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7656 .expect("SelectiveScan set_output_views");
7657 drop(g);
7658 Self {
7659 graph: self.graph.clone(),
7660 id,
7661 }
7662 }
7663
7664 /// Single-output SelectiveScan: returns the `y` slot of the
7665 /// bundled producer, with the View(0) projection emitted so
7666 /// callers can downstream-realize / copy / etc. transparently.
7667 /// See [`Self::selective_scan_bundled`] for the multi-output
7668 /// variant that also exposes `last_state` for autoregressive
7669 /// resumption.
7670 ///
7671 /// # Panics
7672 ///
7673 /// Panics if any operand belongs to a different [`Graph`] than the one this
7674 /// builder is building into. Operand identity is graph-scoped and checked by
7675 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7676 /// deliberate and replaces the hang a cross-graph handle used to produce.
7677 /// Build every operand from one graph, or use a `Result`-returning entry
7678 /// point where one exists.
7679 pub fn selective_scan(
7680 &self,
7681 delta: &NodeHandle,
7682 a: &NodeHandle,
7683 b: &NodeHandle,
7684 c: &NodeHandle,
7685 delta_softplus: bool,
7686 ) -> NodeHandle {
7687 self.assert_same_graph(delta, "selective_scan", "delta");
7688 self.assert_same_graph(a, "selective_scan", "a");
7689 self.assert_same_graph(b, "selective_scan", "b");
7690 self.assert_same_graph(c, "selective_scan", "c");
7691 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7692 producer
7693 .view(0)
7694 .expect("SelectiveScan view(0) must succeed (just registered slots)")
7695 }
7696
7697 /// Multi-output variant of [`Self::selective_scan`]. Returns
7698 /// `(y, last_state)` — both Op::View tensors projected from the
7699 /// shared bundled producer. `y` matches the existing
7700 /// single-output `selective_scan` shape; `last_state` is the
7701 /// final hidden state `[batch, dim, dstate]` for autoregressive
7702 /// resumption.
7703 pub fn selective_scan_bundled(
7704 &self,
7705 delta: &NodeHandle,
7706 a: &NodeHandle,
7707 b: &NodeHandle,
7708 c: &NodeHandle,
7709 delta_softplus: bool,
7710 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7711 self.require_same_graph(delta, "selective_scan_bundled", "delta")?;
7712 self.require_same_graph(a, "selective_scan_bundled", "a")?;
7713 self.require_same_graph(b, "selective_scan_bundled", "b")?;
7714 self.require_same_graph(c, "selective_scan_bundled", "c")?;
7715 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7716 let y = producer.view(0)?;
7717 let last_state = producer.view(1)?;
7718 Ok((y, last_state))
7719 }
7720
7721 /// Multi-output variant of [`Self::ssd_chunk_scan`]. Returns
7722 /// `(y, last_state)`.
7723 pub fn ssd_chunk_scan_bundled(
7724 &self,
7725 dt: &NodeHandle,
7726 a: &NodeHandle,
7727 b: &NodeHandle,
7728 c: &NodeHandle,
7729 chunk_size: usize,
7730 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7731 self.require_same_graph(dt, "ssd_chunk_scan_bundled", "dt")?;
7732 self.require_same_graph(a, "ssd_chunk_scan_bundled", "a")?;
7733 self.require_same_graph(b, "ssd_chunk_scan_bundled", "b")?;
7734 self.require_same_graph(c, "ssd_chunk_scan_bundled", "c")?;
7735 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7736 let y = producer.view(0)?;
7737 let last_state = producer.view(1)?;
7738 Ok((y, last_state))
7739 }
7740
7741 /// Append an [`Op::NonZeroIndices`] producer node — the keystone
7742 /// primitive for **data-dependent dynamic shapes**. Returns the
7743 /// bundled producer `NodeHandle` (a `[capacity]` U32 tensor); callers
7744 /// usually want [`Self::nonzero_indices_bundled`] to also get the
7745 /// runtime count slot.
7746 ///
7747 /// `capacity = self.elem_count()` is the static worst-case bound
7748 /// (every element nonzero). `count_sym` is the [`SymId`] the executor
7749 /// binds to the realized nonzero count in the per-pass `SymEnv`; the
7750 /// caller allocates it from their `SymGen` and threads it into any
7751 /// downstream op that consumes the count as a dynamic extent /
7752 /// `DynScalar::Sym` (the KV-cache `cached_len` pattern, generalized to
7753 /// a data-determined count).
7754 pub fn nonzero_indices_producer(&self, count_sym: SymId) -> NodeHandle {
7755 let capacity = self.shape().elem_count();
7756 let indices_shape = Shape::from_dims(&[capacity]);
7757 let count_shape = Shape::from_dims(&[1]);
7758 let specs = vec![
7759 fuel_ir::storage::OutputViewSpec {
7760 dtype: DType::U32,
7761 shape: indices_shape.clone(),
7762 layout: Layout::contiguous(indices_shape.clone()),
7763 name: Some("indices"),
7764 },
7765 fuel_ir::storage::OutputViewSpec {
7766 dtype: DType::U32,
7767 shape: count_shape.clone(),
7768 layout: Layout::contiguous(count_shape),
7769 name: Some("count"),
7770 },
7771 ];
7772 let (_total_bytes, views) =
7773 fuel_ir::storage::compose_bundle(&specs).expect("NonZeroIndices compose_bundle");
7774 let mut g = self.graph.write().unwrap();
7775 let id = g.push(Node {
7776 op: Op::NonZeroIndices { count_sym },
7777 inputs: vec![self.id],
7778 shape: indices_shape,
7779 dtype: DType::U32,
7780 });
7781 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7782 .expect("NonZeroIndices set_output_views");
7783 drop(g);
7784 Self {
7785 graph: self.graph.clone(),
7786 id,
7787 }
7788 }
7789
7790 /// Multi-output [`Op::NonZeroIndices`]: returns `(indices, count)` —
7791 /// both `Op::View` projections of the shared bundled producer.
7792 /// `indices` is `[capacity]` U32 (first `count` entries valid, in
7793 /// ascending flat order); `count` is `[1]` U32, the runtime nonzero
7794 /// count. The executor also publishes `count`'s value into the
7795 /// per-pass `SymEnv` under the producer's `count_sym`.
7796 pub fn nonzero_indices_bundled(
7797 &self,
7798 count_sym: SymId,
7799 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7800 let producer = self.nonzero_indices_producer(count_sym);
7801 let indices = producer.view(0)?;
7802 let count = producer.view(1)?;
7803 Ok((indices, count))
7804 }
7805
7806 /// Append a `FusedSoftmaxCrossEntropy` node. Two inputs:
7807 /// - `self` (logits): `[..., V]` F32 / F64 / BF16 / F16
7808 /// - `targets`: `[...]` I64 (class indices; matches PyTorch /
7809 /// baracuda convention)
7810 ///
7811 /// Output dtype is always F32 (the FSCE declared dtype — losses
7812 /// accumulate in F64 and narrow to F32, matching PyTorch and the
7813 /// baracuda kernel) regardless of the logits dtype. Output shape
7814 /// depends on `reduction`:
7815 /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
7816 /// - `Reduction::None` → same as `targets.shape`
7817 ///
7818 /// `ignore_index` rows are dropped from the loss accumulator and
7819 /// the Mean denominator. The conventional sentinel is `-100`.
7820 ///
7821 /// Emits `Op::Fused(FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7822 /// FusedOpParams::FusedSoftmaxCrossEntropy { reduction, ignore_index })`.
7823 /// See `fuel-graph/src/registry/fused_softmax_cross_entropy.rs` for
7824 /// the registry entry and decompose chain.
7825 ///
7826 /// # Panics
7827 ///
7828 /// Panics if any operand belongs to a different [`Graph`] than the one this
7829 /// builder is building into. Operand identity is graph-scoped and checked by
7830 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7831 /// deliberate and replaces the hang a cross-graph handle used to produce.
7832 /// Build every operand from one graph, or use a `Result`-returning entry
7833 /// point where one exists.
7834 pub fn fused_softmax_cross_entropy(
7835 &self,
7836 targets: &NodeHandle,
7837 reduction: crate::registry::Reduction,
7838 ignore_index: i64,
7839 ) -> NodeHandle {
7840 assert!(
7841 Arc::ptr_eq(&self.graph, &targets.graph),
7842 "fused_softmax_cross_entropy: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7843 );
7844 assert!(
7845 matches!(
7846 self.dtype(),
7847 DType::F32 | DType::F64 | DType::BF16 | DType::F16,
7848 ),
7849 "fused_softmax_cross_entropy: logits must be F32/F64/BF16/F16, got {:?}",
7850 self.dtype(),
7851 );
7852 assert_eq!(
7853 targets.dtype(),
7854 DType::I64,
7855 "fused_softmax_cross_entropy: targets must be I64, got {:?}",
7856 targets.dtype(),
7857 );
7858 let logits_dims = self.shape();
7859 let logits_dims = logits_dims.dims();
7860 assert!(
7861 !logits_dims.is_empty(),
7862 "fused_softmax_cross_entropy: logits must have rank ≥ 1",
7863 );
7864 let target_dims = targets.shape();
7865 let target_dims = target_dims.dims();
7866 assert_eq!(
7867 target_dims,
7868 &logits_dims[..logits_dims.len() - 1],
7869 "fused_softmax_cross_entropy: targets shape {target_dims:?} must equal \
7870 logits shape {logits_dims:?} minus the last dim",
7871 );
7872 let out_shape = match reduction {
7873 crate::registry::Reduction::Mean | crate::registry::Reduction::Sum => {
7874 Shape::from_dims(&[])
7875 }
7876 crate::registry::Reduction::None => Shape::from_dims(target_dims),
7877 };
7878 let id = self.graph.write().unwrap().push(Node {
7879 op: Op::Fused(
7880 crate::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7881 crate::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
7882 reduction,
7883 ignore_index,
7884 },
7885 ),
7886 inputs: vec![self.id, targets.id],
7887 shape: out_shape,
7888 dtype: DType::F32,
7889 });
7890 Self {
7891 graph: self.graph.clone(),
7892 id,
7893 }
7894 }
7895
7896 /// Append a `LayerNormLastDim` node with the given epsilon. Shape is
7897 /// preserved.
7898 ///
7899 /// Phase 7.6 step 4 (continued): emits
7900 /// `Op::Fused(FusedOps::LAYER_NORM_LAST_DIM, FusedOpParams::LayerNormLastDim { eps })`
7901 /// through the registry-extended arm. The legacy
7902 /// `Op::LayerNormLastDim { eps }` variant remains in the enum
7903 /// during migration; step 5 drops it once nothing emits it.
7904 pub fn layer_norm_last_dim(&self, eps: f64) -> NodeHandle {
7905 let dims = self.shape();
7906 let d = dims.dims();
7907 assert!(
7908 !d.is_empty() && *d.last().unwrap() > 0,
7909 "layer_norm_last_dim: input must have a non-zero last dim, got {d:?}",
7910 );
7911 self.unary_op(Op::Fused(
7912 crate::registry::FusedOps::LAYER_NORM_LAST_DIM,
7913 crate::registry::FusedOpParams::LayerNormLastDim { eps },
7914 ))
7915 }
7916
7917 /// Apply rotary position embeddings (RoPE) to `self`. The input is
7918 /// expected to have shape `[..., seq, d]` where `seq` is the
7919 /// sequence length and `d` is the per-head feature dim (which must
7920 /// be even). `base` is the frequency base — 10000.0 for LLaMA.
7921 /// `start_pos` lets callers apply RoPE at a non-zero offset, which
7922 /// is what KV-cached inference does when the query for position
7923 /// `n + k` is processed against a cache that already holds
7924 /// positions `0..n+k`.
7925 ///
7926 /// Uses the half-split layout (the one LLaMA and HuggingFace use):
7927 /// pair feature `i` with feature `i + d/2`. Under that layout the
7928 /// rotation reduces to the identity `x' = x·cos + rotate_half(x)·sin`
7929 /// where `rotate_half(x)` concatenates `[-x[d/2:], x[:d/2]]` along
7930 /// the last dim.
7931 ///
7932 /// Implemented as a composition of existing graph primitives —
7933 /// `Slice`, `Neg`, `Concat`, `Reshape`, `BroadcastTo`, `Mul`, `Add`
7934 /// — plus two precomputed `Const` tensors for the cos/sin frequency
7935 /// tables. Every primitive already has a working backward rule, so
7936 /// gradients flow through RoPE without any new backward machinery.
7937 ///
7938 /// Only `f32` is supported today. Extending to other float dtypes
7939 /// is mechanical: build the frequency tables in the target dtype.
7940 pub fn rope(&self, base: f64, start_pos: usize) -> NodeHandle {
7941 let (seq, d) = {
7942 let dims = self.shape();
7943 let v = dims.dims();
7944 let rank = v.len();
7945 assert!(rank >= 2, "rope: input must have rank ≥ 2");
7946 (v[rank - 2], v[rank - 1])
7947 };
7948 let (cos, sin) = build_rope_tables(base, start_pos, seq, d);
7949 // Phase 7.5 G2: const_*_like derives the device from self's
7950 // graph internally — RoPE tables go on the same device as self.
7951 // ⚠️ GAP-003 category 2, in production: the proof EXISTS but is NOT
7952 // LOCAL -- `build_rope_tables` owns the length guarantee and its
7953 // signature `-> (Vec<f32>, Vec<f32>)` does not carry it. So the message
7954 // claims NO proof; it names where the guarantee lives. `rope` returns
7955 // `NodeHandle` and already asserts on rank, so giving it an error
7956 // channel is a signature change -- a different obligation. See #157.
7957 let cos_t = self
7958 .const_f32_like(cos, Shape::from_dims(&[seq, d]))
7959 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7960 let sin_t = self
7961 .const_f32_like(sin, Shape::from_dims(&[seq, d]))
7962 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7963 self.rope_with_tables(&cos_t, &sin_t)
7964 }
7965
7966 /// Apply RoPE using caller-supplied `cos` and `sin` tables. Each
7967 /// table has shape `[seq, head_dim]` and matches the layout
7968 /// [`build_rope_tables`] produces. This is the hot-path entry
7969 /// point: in a transformer forward pass every attention layer
7970 /// applies RoPE to Q and K with the *same* `(start_pos, seq,
7971 /// head_dim)`, so the caller can build the tables once and share
7972 /// the const nodes across all layers rather than re-duplicating
7973 /// them inside each `.rope()` call. The classic [`Self::rope`] entry
7974 /// point funnels through this after building the tables itself.
7975 ///
7976 /// # Panics
7977 ///
7978 /// Panics if any operand belongs to a different [`Graph`] than the one this
7979 /// builder is building into. Operand identity is graph-scoped and checked by
7980 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7981 /// deliberate and replaces the hang a cross-graph handle used to produce.
7982 /// Build every operand from one graph, or use a `Result`-returning entry
7983 /// point where one exists.
7984 pub fn rope_with_tables(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
7985 self.assert_same_graph(cos, "rope_with_tables", "cos");
7986 self.assert_same_graph(sin, "rope_with_tables", "sin");
7987 assert_eq!(
7988 self.dtype(),
7989 DType::F32,
7990 "rope: only f32 is supported today (cast explicitly for other dtypes)",
7991 );
7992 let in_shape = self.shape();
7993 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
7994 let rank = dims_vec.len();
7995 assert!(
7996 rank >= 2,
7997 "rope: input must have rank ≥ 2, got {dims_vec:?}"
7998 );
7999 let seq = dims_vec[rank - 2];
8000 let d = dims_vec[rank - 1];
8001 assert!(d.is_multiple_of(2), "rope: feature dim {d} must be even",);
8002 let cos_shape = cos.shape();
8003 let sin_shape = sin.shape();
8004 assert_eq!(
8005 cos_shape.dims(),
8006 &[seq, d],
8007 "rope_with_tables: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
8008 cos_shape.dims(),
8009 );
8010 assert_eq!(
8011 sin_shape.dims(),
8012 &[seq, d],
8013 "rope_with_tables: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
8014 sin_shape.dims(),
8015 );
8016 let _ = rank;
8017 // Emit a single fused Rope node. The decomposed version
8018 // (slice+neg+concat+broadcast+mul+add) produces ~72 dispatches
8019 // on GPU backends because concat-along-last-dim has a per-row
8020 // host loop. Fused path dispatches once.
8021 //
8022 // Phase 7.6 step 4 (continued): emits
8023 // `Op::Fused(FusedOps::ROPE, FusedOpParams::Rope)` through the
8024 // registry-extended arm. The legacy `Op::Rope` variant remains
8025 // in the enum during migration; step 5 drops it once nothing
8026 // emits it.
8027 let out_shape = in_shape.clone();
8028 let dtype = self.dtype();
8029 let id = self.graph.write().unwrap().push(Node {
8030 op: Op::Fused(
8031 crate::registry::FusedOps::ROPE,
8032 crate::registry::FusedOpParams::Rope,
8033 ),
8034 inputs: vec![self.id, cos.id, sin.id],
8035 shape: out_shape,
8036 dtype,
8037 });
8038 Self {
8039 graph: self.graph.clone(),
8040 id,
8041 }
8042 }
8043
8044 /// The pre-fused decomposition of `rope_with_tables`. Retained so
8045 /// backends without a native `Op::Rope` kernel can synthesize from
8046 /// primitives, and so correctness tests can cross-check the fused
8047 /// path against the primitive path.
8048 ///
8049 /// # Panics
8050 ///
8051 /// Panics if any operand belongs to a different [`Graph`] than the one this
8052 /// builder is building into. Operand identity is graph-scoped and checked by
8053 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8054 /// deliberate and replaces the hang a cross-graph handle used to produce.
8055 /// Build every operand from one graph, or use a `Result`-returning entry
8056 /// point where one exists.
8057 #[doc(hidden)]
8058 pub fn rope_with_tables_decomposed(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8059 self.assert_same_graph(cos, "rope_with_tables_decomposed", "cos");
8060 self.assert_same_graph(sin, "rope_with_tables_decomposed", "sin");
8061 let in_shape = self.shape();
8062 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8063 let rank = dims_vec.len();
8064 let seq = dims_vec[rank - 2];
8065 let d = dims_vec[rank - 1];
8066 let half = d / 2;
8067
8068 let mut broadcast_shape: Vec<usize> = vec![1_usize; rank];
8069 broadcast_shape[rank - 2] = seq;
8070 broadcast_shape[rank - 1] = d;
8071 let cos_reshaped = cos.reshape(Shape::from_dims(&broadcast_shape));
8072 let sin_reshaped = sin.reshape(Shape::from_dims(&broadcast_shape));
8073 let cos_bcast = cos_reshaped.broadcast_to(in_shape.clone());
8074 let sin_bcast = sin_reshaped.broadcast_to(in_shape);
8075
8076 let first_half = self.slice(rank - 1, 0, half);
8077 let second_half = self.slice(rank - 1, half, half);
8078 let neg_second = second_half.neg();
8079 let rotated_half = neg_second.concat(&first_half, rank - 1);
8080
8081 let left = self.mul(&cos_bcast);
8082 let right = rotated_half.mul(&sin_bcast);
8083 left.add(&right)
8084 }
8085
8086 /// Root-Mean-Square Normalization along the last dim, without
8087 /// affine parameters. `y = x / sqrt(mean(x², last) + eps)`.
8088 ///
8089 /// This is the normalization layer used by LLaMA-family models.
8090 /// Unlike LayerNorm, RmsNorm does not subtract the mean — it only
8091 /// divides by the root-mean-square, which is both cheaper and
8092 /// empirically just as effective in transformer blocks.
8093 ///
8094 /// Emits a fused RmsNormLastDim node. Backends that have a native
8095 /// implementation dispatch it as one kernel; ones that don't get a
8096 /// CPU fallback via the reference implementation.
8097 ///
8098 /// Phase 7.6 step 4 (continued): emits
8099 /// `Op::Fused(FusedOps::RMS_NORM_LAST_DIM, FusedOpParams::RmsNormLastDim { eps })`
8100 /// through the registry-extended arm. The legacy
8101 /// `Op::RmsNormLastDim { eps }` variant remains in the enum during
8102 /// migration; step 5 drops it once nothing emits it.
8103 ///
8104 /// Use [`rms_norm_last_dim_decomposed`](Self::rms_norm_last_dim_decomposed)
8105 /// instead if you need to differentiate through this op —
8106 /// backward through the fused op is not yet implemented.
8107 pub fn rms_norm_last_dim(&self, eps: f64) -> NodeHandle {
8108 let x_dims_vec: Vec<usize> = self.shape().dims().to_vec();
8109 assert!(
8110 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8111 "rms_norm_last_dim: input must have non-zero last dim, got {x_dims_vec:?}",
8112 );
8113 self.unary_op(Op::Fused(
8114 crate::registry::FusedOps::RMS_NORM_LAST_DIM,
8115 crate::registry::FusedOpParams::RmsNormLastDim { eps },
8116 ))
8117 }
8118
8119 /// Decomposed version — emits the (sqr → mean_dim → reshape →
8120 /// add_scalar → sqrt → broadcast_to → div) primitive chain. Has
8121 /// working backward rules through its primitive subgraph. Use
8122 /// this when you need to differentiate through RMSNorm; use
8123 /// [`rms_norm_last_dim`](Self::rms_norm_last_dim) for inference.
8124 pub fn rms_norm_last_dim_decomposed(&self, eps: f64) -> NodeHandle {
8125 let x_shape = self.shape();
8126 let x_dims_vec: Vec<usize> = x_shape.dims().to_vec();
8127 assert!(
8128 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8129 "rms_norm_last_dim_decomposed: input must have non-zero last dim, got {x_dims_vec:?}",
8130 );
8131 let last = x_dims_vec.len() - 1;
8132 let mean_sq = self.sqr().mean_dim(last);
8133 let mut keepdim_dims = x_dims_vec.clone();
8134 keepdim_dims[last] = 1;
8135 let mean_sq_kd = mean_sq.reshape(Shape::from_dims(&keepdim_dims));
8136 let denom = mean_sq_kd.add_scalar(eps).sqrt();
8137 let denom_bcast = denom.broadcast_to(x_shape);
8138 self.div(&denom_bcast)
8139 }
8140
8141 // --- indexing ---
8142
8143 /// Append an `IndexSelect` node that picks slices from `self` along
8144 /// `dim` using a 1-D `u32` index tensor. The output has the same
8145 /// shape as `self` except dimension `dim` is replaced by
8146 /// `indices.shape()[0]`.
8147 ///
8148 /// # Panics
8149 ///
8150 /// Panics if any operand belongs to a different [`Graph`] than the one this
8151 /// builder is building into. Operand identity is graph-scoped and checked by
8152 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8153 /// deliberate and replaces the hang a cross-graph handle used to produce.
8154 /// Build every operand from one graph, or use a `Result`-returning entry
8155 /// point where one exists.
8156 pub fn index_select(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8157 assert!(
8158 Arc::ptr_eq(&self.graph, &indices.graph),
8159 "index_select: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8160 );
8161 assert_eq!(
8162 indices.dtype(),
8163 DType::U32,
8164 "index_select: index tensor must be U32, got {:?}",
8165 indices.dtype(),
8166 );
8167 let idx_dims = indices.shape();
8168 assert_eq!(
8169 idx_dims.dims().len(),
8170 1,
8171 "index_select: index tensor must be rank 1, got {:?}",
8172 idx_dims.dims(),
8173 );
8174 let data_dims = self.shape();
8175 assert!(
8176 dim < data_dims.dims().len(),
8177 "index_select: dim {dim} out of bounds for data shape {:?}",
8178 data_dims.dims(),
8179 );
8180 let op = Op::IndexSelect { dim };
8181 let (shape, dtype) = crate::shape::primitive_shape(
8182 &op,
8183 &[data_dims, idx_dims],
8184 &[self.dtype(), indices.dtype()],
8185 )
8186 .expect("index_select: shapes/dims validated above");
8187 let id = self.graph.write().unwrap().push(Node {
8188 op,
8189 inputs: vec![self.id, indices.id],
8190 shape,
8191 dtype,
8192 });
8193 Self {
8194 graph: self.graph.clone(),
8195 id,
8196 }
8197 }
8198
8199 /// Append a `Gather` node that performs an N-dimensional gather along
8200 /// `dim`. The `indices` tensor must be `U32` with the same rank as
8201 /// `self`. Output shape equals `indices.shape()`.
8202 ///
8203 /// # Panics
8204 ///
8205 /// Panics if any operand belongs to a different [`Graph`] than the one this
8206 /// builder is building into. Operand identity is graph-scoped and checked by
8207 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8208 /// deliberate and replaces the hang a cross-graph handle used to produce.
8209 /// Build every operand from one graph, or use a `Result`-returning entry
8210 /// point where one exists.
8211 pub fn gather(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8212 assert!(
8213 Arc::ptr_eq(&self.graph, &indices.graph),
8214 "gather: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8215 );
8216 assert_eq!(
8217 indices.dtype(),
8218 DType::U32,
8219 "gather: index tensor must be U32, got {:?}",
8220 indices.dtype(),
8221 );
8222 let data_rank = self.shape().dims().len();
8223 let idx_rank = indices.shape().dims().len();
8224 assert_eq!(
8225 data_rank, idx_rank,
8226 "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
8227 );
8228 assert!(
8229 dim < data_rank,
8230 "gather: dim {dim} out of bounds for rank {data_rank}",
8231 );
8232 let op = Op::Gather { dim };
8233 let (shape, dtype) = crate::shape::primitive_shape(
8234 &op,
8235 &[self.shape(), indices.shape()],
8236 &[self.dtype(), indices.dtype()],
8237 )
8238 .expect("gather: shapes/dims validated above");
8239 let id = self.graph.write().unwrap().push(Node {
8240 op,
8241 inputs: vec![self.id, indices.id],
8242 shape,
8243 dtype,
8244 });
8245 Self {
8246 graph: self.graph.clone(),
8247 id,
8248 }
8249 }
8250
8251 /// Append a `Concat` node joining `self` and `other` along `dim`.
8252 ///
8253 /// # Panics
8254 ///
8255 /// Panics if any operand belongs to a different [`Graph`] than the one this
8256 /// builder is building into. Operand identity is graph-scoped and checked by
8257 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8258 /// deliberate and replaces the hang a cross-graph handle used to produce.
8259 /// Build every operand from one graph, or use a `Result`-returning entry
8260 /// point where one exists.
8261 pub fn concat(&self, other: &NodeHandle, dim: usize) -> NodeHandle {
8262 assert!(
8263 Arc::ptr_eq(&self.graph, &other.graph),
8264 "concat: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8265 );
8266 assert_eq!(
8267 self.dtype(),
8268 other.dtype(),
8269 "concat: dtype mismatch {:?} vs {:?}",
8270 self.dtype(),
8271 other.dtype(),
8272 );
8273 let a = self.shape();
8274 let b = other.shape();
8275 let ad = a.dims();
8276 let bd = b.dims();
8277 assert_eq!(ad.len(), bd.len(), "concat: rank mismatch");
8278 assert!(dim < ad.len(), "concat: dim out of bounds");
8279 for i in 0..ad.len() {
8280 if i != dim {
8281 assert_eq!(
8282 ad[i], bd[i],
8283 "concat: non-dim shapes must match (dim {i}: {} vs {})",
8284 ad[i], bd[i],
8285 );
8286 }
8287 }
8288 let op = Op::Concat { dim };
8289 let (shape, dtype) =
8290 crate::shape::primitive_shape(&op, &[a, b], &[self.dtype(), other.dtype()])
8291 .expect("concat: shapes/dtypes validated above");
8292 let id = self.graph.write().unwrap().push(Node {
8293 op,
8294 inputs: vec![self.id, other.id],
8295 shape,
8296 dtype,
8297 });
8298 Self {
8299 graph: self.graph.clone(),
8300 id,
8301 }
8302 }
8303
8304 /// Append a `Slice` (narrow) node taking elements `[start, start+len)`
8305 /// along `dim`. The output has the same rank; only `dim` shrinks.
8306 pub fn slice(&self, dim: usize, start: usize, len: usize) -> NodeHandle {
8307 let in_shape = self.shape();
8308 let in_dims = in_shape.dims();
8309 assert!(dim < in_dims.len(), "slice: dim out of bounds");
8310 assert!(
8311 start + len <= in_dims[dim],
8312 "slice: [start={start}, len={len}) exceeds dim size {}",
8313 in_dims[dim],
8314 );
8315 let op = Op::Slice { dim, start, len };
8316 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8317 .expect("slice: dim/start/len validated above");
8318 let id = self.graph.write().unwrap().push(Node {
8319 op,
8320 inputs: vec![self.id],
8321 shape,
8322 dtype,
8323 });
8324 Self {
8325 graph: self.graph.clone(),
8326 id,
8327 }
8328 }
8329
8330 /// Append an `AddScalar` node: `y[i] = x[i] + c`. Convenient for
8331 /// avoiding a full-shape const node when you just want to bias a
8332 /// tensor by a constant.
8333 pub fn add_scalar(&self, c: f64) -> NodeHandle {
8334 self.unary_op(Op::AddScalar(c))
8335 }
8336
8337 /// Append a `MulScalar` node: `y[i] = x[i] * c`.
8338 pub fn mul_scalar(&self, c: f64) -> NodeHandle {
8339 self.unary_op(Op::MulScalar(c))
8340 }
8341
8342 /// Append a `PowI` node raising each element to an integer power.
8343 pub fn powi(&self, n: i32) -> NodeHandle {
8344 self.unary_op(Op::PowI(n))
8345 }
8346
8347 /// Append a `Clamp` node restricting each element to `[min, max]`.
8348 pub fn clamp(&self, min: f64, max: f64) -> NodeHandle {
8349 assert!(min <= max, "clamp: min ({min}) must be <= max ({max})",);
8350 self.unary_op(Op::Clamp { min, max })
8351 }
8352
8353 /// Append a `Maximum` node `max(self, other)` element-wise. Matching
8354 /// shapes required.
8355 ///
8356 /// # Panics
8357 ///
8358 /// Panics if any operand belongs to a different [`Graph`] than the one this
8359 /// builder is building into. Operand identity is graph-scoped and checked by
8360 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8361 /// deliberate and replaces the hang a cross-graph handle used to produce.
8362 /// Build every operand from one graph, or use a `Result`-returning entry
8363 /// point where one exists.
8364 pub fn maximum(&self, other: &NodeHandle) -> NodeHandle {
8365 self.binary_op("maximum", Op::Maximum, other, self.shape())
8366 }
8367
8368 /// Append a `Minimum` node `min(self, other)` element-wise.
8369 ///
8370 /// # Panics
8371 ///
8372 /// Panics if any operand belongs to a different [`Graph`] than the one this
8373 /// builder is building into. Operand identity is graph-scoped and checked by
8374 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8375 /// deliberate and replaces the hang a cross-graph handle used to produce.
8376 /// Build every operand from one graph, or use a `Result`-returning entry
8377 /// point where one exists.
8378 pub fn minimum(&self, other: &NodeHandle) -> NodeHandle {
8379 self.binary_op("minimum", Op::Minimum, other, self.shape())
8380 }
8381
8382 /// The IEEE-754 NaN-**suppressing** maximum — the KISS-OPS §6.15-0001
8383 /// `fmax_ieee` op, DISTINCT from [`maximum`](Self::maximum) (which is
8384 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8385 /// the other; if both are NaN, returns NaN; otherwise the larger.
8386 ///
8387 /// Built by RESOLUTION through the spec-pinned §6.13 decomposition
8388 /// (KISS-OPS-6.15-0001), used VERBATIM — Fuel does not substitute `maximum`
8389 /// for it (that substitution is the §6.15 violation). Because the
8390 /// decomposition is spec-authored, its edge behaviour — including ±0 ordering
8391 /// under `cmp_ge` (`cmp_ge(-0.0, +0.0)` is true, so this returns `-0.0` for
8392 /// that pair) — is the SPEC's to define and a KISS conformance vector's to
8393 /// catch. Fuel resolves; it does not re-derive. (GAP-048.)
8394 pub fn fmax_ieee(&self, other: &NodeHandle) -> NodeHandle {
8395 // select(a != a, b, select(b != b, a, select(a >= b, a, b)))
8396 let a = self;
8397 let b = other;
8398 let plain = a.ge(b).where_cond(a, b); // a >= b ? a : b
8399 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8400 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8401 }
8402
8403 /// The IEEE-754 NaN-**suppressing** minimum — the KISS-OPS §6.15-0001
8404 /// `fmin_ieee` op, DISTINCT from [`minimum`](Self::minimum) (which is
8405 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8406 /// the other; if both are NaN, returns NaN; otherwise the smaller.
8407 ///
8408 /// Built by RESOLUTION through the spec-pinned KISS-OPS §6.13 decomposition
8409 /// (KISS-OPS-6.15-0001), used VERBATIM — the `cmp_le` mirror of
8410 /// [`fmax_ieee`](Self::fmax_ieee)'s `cmp_ge` form. Fuel resolves; it does not
8411 /// substitute `minimum` (that substitution is the §6.15 violation) and does
8412 /// not re-derive: the decomposition is KISS's, so its ±0 edge behaviour is the
8413 /// spec's to define and a KISS conformance vector's to catch. (GAP-048.)
8414 pub fn fmin_ieee(&self, other: &NodeHandle) -> NodeHandle {
8415 // select(a != a, b, select(b != b, a, select(a <= b, a, b)))
8416 let a = self;
8417 let b = other;
8418 let plain = a.le(b).where_cond(a, b); // a <= b ? a : b
8419 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8420 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8421 }
8422
8423 /// Round toward zero — the KISS-OPS §6.3 `trunc` floor op (GAP-300).
8424 ///
8425 /// ⚠️ Unlike [`fmax_ieee`](Self::fmax_ieee)/[`fmin_ieee`](Self::fmin_ieee),
8426 /// which resolve through KISS's OWN §6.13 decompositions, `trunc` is a §6.3
8427 /// *floor* op: KISS-OPS-6.3-0003 forbids the standard from carrying a
8428 /// reference decomposition for a floor op, so THIS expansion is FUEL's, blessed
8429 /// by no spec clause. It IS now checked by KISS vectors: `ops-rounding.json`
8430 /// (vendored at KISS `0af5d3b6`) carries 18 `f32` `trunc` cells (signed zero, halves
8431 /// and ties, 2^23, max finite, ±inf, subnormals), all of which pass through the lazy
8432 /// `Tensor` (`fuel-tensor/tests/kiss_nan_conformance.rs`); `f64` and NaN inputs are
8433 /// not in that file. Beyond it, correctness is Fuel's liability — see GAP-300, whose born-reds assert
8434 /// on `to_bits()` (a value compare `0.0 == -0.0` passes vacuously).
8435 ///
8436 /// `trunc(q) = if q >= 0 { floor(q) } else { ceil(q) }`. Float dtypes only;
8437 /// integer dtypes are already whole, so `trunc` is identity for them (returned
8438 /// unchanged — never a panic on a non-float operand).
8439 ///
8440 /// REJECTED-FOR-NOW alternative: `copysign(floor(abs(q)), q)` is cleaner (no
8441 /// dtype-matched zero; ±0/NaN/inf fall out of the IEEE primitives). Fuel has no
8442 /// `copysign` op today (absent from `Op` and the builder API), so it is not
8443 /// buildable — adopt it IF `copysign` ever lands.
8444 pub fn trunc(&self) -> NodeHandle {
8445 let q = self;
8446 // A scalar zero of q's dtype, broadcast to q's shape — comparisons require
8447 // matching shapes (no implicit broadcast in `binary_compare_op`).
8448 let zero = match q.dtype() {
8449 DType::F32 => q
8450 .const_f32_like(vec![0.0f32], &[1])
8451 .expect("trunc: a 1-element vec with shape [1]")
8452 .broadcast_to(q.shape()),
8453 DType::F64 => q
8454 .const_f64_like(vec![0.0f64], &[1])
8455 .expect("trunc: a 1-element vec with shape [1]")
8456 .broadcast_to(q.shape()),
8457 DType::BF16 => q
8458 .const_bf16_like(vec![half::bf16::from_f32(0.0)], &[1])
8459 .expect("trunc: a 1-element vec with shape [1]")
8460 .broadcast_to(q.shape()),
8461 DType::F16 => q
8462 .const_f16_like(vec![half::f16::from_f32(0.0)], &[1])
8463 .expect("trunc: a 1-element vec with shape [1]")
8464 .broadcast_to(q.shape()),
8465 // Integer/other dtypes are already whole: trunc is identity.
8466 _ => return q.clone(),
8467 };
8468 // q >= 0 ? floor(q) : ceil(q). Note: at ±0 BOTH branches yield the same
8469 // signed zero (`floor(-0.0) == ceil(-0.0) == -0.0`), so trunc's ±0 result
8470 // is robust to a tie-bias in `ge` — but the born-red still checks the bits.
8471 q.ge(&zero).where_cond(&q.floor(), &q.ceil())
8472 }
8473
8474 /// Truncated remainder — the KISS-OPS §6.15-0003 `rem_trunc` op, DISTINCT from
8475 /// [`rem`](Self::rem) (which is FLOORED / PyTorch, sign of the *divisor*).
8476 /// `rem_trunc` takes the sign of the *dividend* (C99 `fmod` / Rust `%`).
8477 ///
8478 /// Built by RESOLUTION through KISS's spec-pinned §6.13 decomposition
8479 /// (KISS-OPS-6.15-0003) — `a - trunc(a / b) * b` — used VERBATIM. Fuel does not
8480 /// substitute `rem` (that substitution is the §6.15 violation); the two diverge
8481 /// whenever the operands have opposite signs (e.g. `-7 rem_trunc 3 = -1`, where
8482 /// `rem` (floored) = `2`). The `trunc` leaf is Fuel's own expansion (GAP-300).
8483 pub fn rem_trunc(&self, other: &NodeHandle) -> NodeHandle {
8484 // a - trunc(a / b) * b
8485 let a = self;
8486 let b = other;
8487 let t = a.div(b).trunc();
8488 a.sub(&t.mul(b))
8489 }
8490
8491 /// Element-wise addition with automatic broadcasting. Unlike `add`,
8492 /// which requires matching shapes, `broadcast_add` computes the
8493 /// broadcast shape of the two operands, inserts explicit
8494 /// `BroadcastTo` nodes as needed, and then emits a regular `Add`.
8495 /// Useful for bias addition (`[batch, hidden] + [hidden]`) without
8496 /// the caller writing the broadcast out explicitly.
8497 ///
8498 /// # Panics
8499 ///
8500 /// Panics if any operand belongs to a different [`Graph`] than the one this
8501 /// builder is building into. Operand identity is graph-scoped and checked by
8502 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8503 /// deliberate and replaces the hang a cross-graph handle used to produce.
8504 /// Build every operand from one graph, or use a `Result`-returning entry
8505 /// point where one exists.
8506 pub fn broadcast_add(&self, other: &NodeHandle) -> NodeHandle {
8507 let (a, b) = self.auto_broadcast_pair("broadcast_add", other);
8508 a.add(&b)
8509 }
8510
8511 /// Element-wise subtraction with automatic broadcasting.
8512 ///
8513 /// # Panics
8514 ///
8515 /// Panics if any operand belongs to a different [`Graph`] than the one this
8516 /// builder is building into. Operand identity is graph-scoped and checked by
8517 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8518 /// deliberate and replaces the hang a cross-graph handle used to produce.
8519 /// Build every operand from one graph, or use a `Result`-returning entry
8520 /// point where one exists.
8521 pub fn broadcast_sub(&self, other: &NodeHandle) -> NodeHandle {
8522 let (a, b) = self.auto_broadcast_pair("broadcast_sub", other);
8523 a.sub(&b)
8524 }
8525
8526 /// Element-wise multiplication with automatic broadcasting.
8527 ///
8528 /// # Panics
8529 ///
8530 /// Panics if any operand belongs to a different [`Graph`] than the one this
8531 /// builder is building into. Operand identity is graph-scoped and checked by
8532 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8533 /// deliberate and replaces the hang a cross-graph handle used to produce.
8534 /// Build every operand from one graph, or use a `Result`-returning entry
8535 /// point where one exists.
8536 pub fn broadcast_mul(&self, other: &NodeHandle) -> NodeHandle {
8537 let (a, b) = self.auto_broadcast_pair("broadcast_mul", other);
8538 a.mul(&b)
8539 }
8540
8541 /// Element-wise division with automatic broadcasting.
8542 ///
8543 /// # Panics
8544 ///
8545 /// Panics if any operand belongs to a different [`Graph`] than the one this
8546 /// builder is building into. Operand identity is graph-scoped and checked by
8547 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8548 /// deliberate and replaces the hang a cross-graph handle used to produce.
8549 /// Build every operand from one graph, or use a `Result`-returning entry
8550 /// point where one exists.
8551 pub fn broadcast_div(&self, other: &NodeHandle) -> NodeHandle {
8552 let (a, b) = self.auto_broadcast_pair("broadcast_div", other);
8553 a.div(&b)
8554 }
8555
8556 /// Build both operands broadcast to their common shape. Used by the
8557 /// `broadcast_*` wrappers above. Inserts explicit `BroadcastTo` nodes
8558 /// on whichever side needs them — either or both may pass through
8559 /// unchanged if already at the target shape.
8560 fn auto_broadcast_pair(
8561 &self,
8562 op: &'static str,
8563 other: &NodeHandle,
8564 ) -> (NodeHandle, NodeHandle) {
8565 assert!(
8566 Arc::ptr_eq(&self.graph, &other.graph),
8567 "{op}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8568 each `from_*` constructor mints a NEW graph, so build the second operand with \
8569 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8570 self.graph_id(),
8571 other.graph_id(),
8572 );
8573 assert_eq!(
8574 self.dtype(),
8575 other.dtype(),
8576 "{op}: dtype mismatch {:?} vs {:?}",
8577 self.dtype(),
8578 other.dtype(),
8579 );
8580 let a_shape = self.shape();
8581 let b_shape = other.shape();
8582 let target_dims = compute_broadcast_shape(a_shape.dims(), b_shape.dims());
8583 let target = Shape::from_dims(&target_dims);
8584 let a = if a_shape.dims() == target.dims() {
8585 self.clone()
8586 } else {
8587 self.broadcast_to(target.clone())
8588 };
8589 let b = if b_shape.dims() == target.dims() {
8590 other.clone()
8591 } else {
8592 other.broadcast_to(target)
8593 };
8594 (a, b)
8595 }
8596
8597 /// Append an `IndexAdd` node — the functional inverse of
8598 /// `IndexSelect`. Returns `base` with `src` added at positions given
8599 /// by `indices` along `dim`.
8600 ///
8601 /// # Panics
8602 ///
8603 /// Panics if any operand belongs to a different [`Graph`] than the one this
8604 /// builder is building into. Operand identity is graph-scoped and checked by
8605 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8606 /// deliberate and replaces the hang a cross-graph handle used to produce.
8607 /// Build every operand from one graph, or use a `Result`-returning entry
8608 /// point where one exists.
8609 pub fn index_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8610 assert!(
8611 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8612 "index_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8613 );
8614 assert_eq!(indices.dtype(), DType::U32, "index_add: index must be U32");
8615 assert_eq!(
8616 self.dtype(),
8617 src.dtype(),
8618 "index_add: base and src dtypes must match"
8619 );
8620 let base_dims = self.shape();
8621 let src_dims = src.shape();
8622 assert_eq!(
8623 base_dims.dims().len(),
8624 src_dims.dims().len(),
8625 "index_add: base and src must have the same rank",
8626 );
8627 assert_eq!(
8628 indices.shape().dims().len(),
8629 1,
8630 "index_add: index must be rank 1",
8631 );
8632 assert_eq!(
8633 src_dims.dims()[dim],
8634 indices.shape().dims()[0],
8635 "index_add: src dim {dim} ({}) must match index length ({})",
8636 src_dims.dims()[dim],
8637 indices.shape().dims()[0],
8638 );
8639 let dtype = self.dtype();
8640 let out_shape = base_dims;
8641 let id = self.graph.write().unwrap().push(Node {
8642 op: Op::IndexAdd { dim },
8643 inputs: vec![self.id, indices.id, src.id],
8644 shape: out_shape,
8645 dtype,
8646 });
8647 Self {
8648 graph: self.graph.clone(),
8649 id,
8650 }
8651 }
8652
8653 /// Append a `ScatterAdd` node — the functional inverse of `Gather`.
8654 /// Returns `base` with values from `src` accumulated at positions
8655 /// given by `indices` (with `indices[p]` substituted at `dim`).
8656 ///
8657 /// # Panics
8658 ///
8659 /// Panics if any operand belongs to a different [`Graph`] than the one this
8660 /// builder is building into. Operand identity is graph-scoped and checked by
8661 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8662 /// deliberate and replaces the hang a cross-graph handle used to produce.
8663 /// Build every operand from one graph, or use a `Result`-returning entry
8664 /// point where one exists.
8665 pub fn scatter_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8666 assert!(
8667 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8668 "scatter_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8669 );
8670 assert_eq!(
8671 indices.dtype(),
8672 DType::U32,
8673 "scatter_add: index must be U32"
8674 );
8675 assert_eq!(
8676 self.dtype(),
8677 src.dtype(),
8678 "scatter_add: base and src dtypes must match"
8679 );
8680 assert_eq!(
8681 indices.shape().dims(),
8682 src.shape().dims(),
8683 "scatter_add: index and src must have the same shape",
8684 );
8685 let dtype = self.dtype();
8686 let out_shape = self.shape();
8687 let id = self.graph.write().unwrap().push(Node {
8688 op: Op::ScatterAdd { dim },
8689 inputs: vec![self.id, indices.id, src.id],
8690 shape: out_shape,
8691 dtype,
8692 });
8693 Self {
8694 graph: self.graph.clone(),
8695 id,
8696 }
8697 }
8698
8699 // --- internal helpers for the new builders ---
8700
8701 fn scalar_reduction(&self, op: Op) -> NodeHandle {
8702 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
8703 .expect("scalar_reduction: single input always infers a rank-0 shape");
8704 let id = self.graph.write().unwrap().push(Node {
8705 op,
8706 inputs: vec![self.id],
8707 shape,
8708 dtype,
8709 });
8710 Self {
8711 graph: self.graph.clone(),
8712 id,
8713 }
8714 }
8715
8716 fn axis_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
8717 let in_shape = self.shape();
8718 assert!(
8719 dim < in_shape.dims().len(),
8720 "{name}: dim {dim} out of bounds for shape {:?}",
8721 in_shape.dims(),
8722 );
8723 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8724 .expect("axis_reduction: dim validated above");
8725 let id = self.graph.write().unwrap().push(Node {
8726 op,
8727 inputs: vec![self.id],
8728 shape,
8729 dtype,
8730 });
8731 Self {
8732 graph: self.graph.clone(),
8733 id,
8734 }
8735 }
8736
8737 // Internal helpers. Both shape-validate and append.
8738
8739 /// Build-time graph-affinity check for a `Result`-returning builder.
8740 ///
8741 /// Node ids index ONE graph's arena, so an operand from a different graph
8742 /// records an id pointing at an unrelated node — a malformed dependency
8743 /// graph whose failure mode is a **realize-time hang**, not a panic or an
8744 /// error. Checking here converts a silent deadlock into a typed build-time
8745 /// error naming both graphs, per "validate at graph-build time".
8746 fn require_same_graph(
8747 &self,
8748 other: &NodeHandle,
8749 op: &str,
8750 role: &str,
8751 ) -> std::result::Result<(), fuel_ir::Error> {
8752 if !Arc::ptr_eq(&self.graph, &other.graph) {
8753 return Err(fuel_ir::Error::Msg(format!(
8754 "{op}: operands must live on the same graph — self is on graph #{}, \
8755 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8756 build the other operand with `from_*_on(self.graph(), ..)` or \
8757 `const_*_like`",
8758 self.graph_id(),
8759 other.graph_id(),
8760 ))
8761 .bt());
8762 }
8763 Ok(())
8764 }
8765
8766 /// Panicking sibling of [`Self::require_same_graph`] for the builders that
8767 /// return `NodeHandle` rather than `Result` — same convention as `matmul`,
8768 /// `qmatmul`, `conv2d` and `paged_attn`. A panic at the build site is far
8769 /// better than the hang it replaces: it names the operand and both graphs.
8770 fn assert_same_graph(&self, other: &NodeHandle, op: &str, role: &str) {
8771 assert!(
8772 Arc::ptr_eq(&self.graph, &other.graph),
8773 "{op}: operands must live on the same graph — self is on graph #{}, \
8774 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8775 build the other operand with `from_*_on(self.graph(), ..)` or \
8776 `const_*_like`",
8777 self.graph_id(),
8778 other.graph_id(),
8779 );
8780 }
8781
8782 fn binary_op(
8783 &self,
8784 name: &'static str,
8785 op: Op,
8786 other: &NodeHandle,
8787 out_shape: Shape,
8788 ) -> NodeHandle {
8789 assert!(
8790 Arc::ptr_eq(&self.graph, &other.graph),
8791 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8792 each `from_*` constructor mints a NEW graph, so build the second operand with \
8793 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8794 self.graph_id(),
8795 other.graph_id(),
8796 );
8797 assert_eq!(
8798 self.dtype(),
8799 other.dtype(),
8800 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8801 self.dtype(),
8802 other.dtype(),
8803 );
8804 assert_eq!(
8805 self.shape().dims(),
8806 other.shape().dims(),
8807 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8808 self.shape().dims(),
8809 other.shape().dims(),
8810 );
8811 let dtype = self.dtype();
8812 let id = self.graph.write().unwrap().push(Node {
8813 op,
8814 inputs: vec![self.id, other.id],
8815 shape: out_shape,
8816 dtype,
8817 });
8818 Self {
8819 graph: self.graph.clone(),
8820 id,
8821 }
8822 }
8823
8824 /// Result-returning sibling of [`Self::binary_op`]. Validates the
8825 /// graph/dtype/shape preconditions and returns `Err` rather than
8826 /// panicking — the production-correct shape new builders should
8827 /// use. Existing panicking sites are kept for back-compat; new
8828 /// ops should call this directly.
8829 fn try_binary_op(
8830 &self,
8831 name: &'static str,
8832 op: Op,
8833 other: &NodeHandle,
8834 out_shape: Shape,
8835 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
8836 if !Arc::ptr_eq(&self.graph, &other.graph) {
8837 return Err(fuel_ir::Error::Msg(format!(
8838 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8839 each `from_*` constructor mints a NEW graph, so build the second operand with \
8840 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8841 self.graph_id(),
8842 other.graph_id(),
8843 )).bt());
8844 }
8845 if self.dtype() != other.dtype() {
8846 return Err(fuel_ir::Error::Msg(format!(
8847 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8848 self.dtype(),
8849 other.dtype(),
8850 ))
8851 .bt());
8852 }
8853 if self.shape().dims() != other.shape().dims() {
8854 return Err(fuel_ir::Error::Msg(format!(
8855 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8856 self.shape().dims(),
8857 other.shape().dims(),
8858 ))
8859 .bt());
8860 }
8861 let dtype = self.dtype();
8862 let id = self.graph.write().unwrap().push(Node {
8863 op,
8864 inputs: vec![self.id, other.id],
8865 shape: out_shape,
8866 dtype,
8867 });
8868 Ok(Self {
8869 graph: self.graph.clone(),
8870 id,
8871 })
8872 }
8873
8874 fn unary_op(&self, op: Op) -> NodeHandle {
8875 let shape = self.shape();
8876 let dtype = self.dtype();
8877 let id = self.graph.write().unwrap().push(Node {
8878 op,
8879 inputs: vec![self.id],
8880 shape,
8881 dtype,
8882 });
8883 Self {
8884 graph: self.graph.clone(),
8885 id,
8886 }
8887 }
8888
8889 /// Binary builder for ops whose inputs share dtype/shape but whose
8890 /// output is a `U8` mask (`Op::Equal` and the rest of the
8891 /// comparison family). Differs from [`Self::binary_op`] only in the
8892 /// node's output dtype: always `DType::U8` regardless of input
8893 /// dtype.
8894 fn binary_compare_op(&self, name: &'static str, op: Op, other: &NodeHandle) -> NodeHandle {
8895 assert!(
8896 Arc::ptr_eq(&self.graph, &other.graph),
8897 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8898 each `from_*` constructor mints a NEW graph, so build the second operand with \
8899 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8900 self.graph_id(),
8901 other.graph_id(),
8902 );
8903 assert_eq!(
8904 self.dtype(),
8905 other.dtype(),
8906 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8907 self.dtype(),
8908 other.dtype(),
8909 );
8910 assert_eq!(
8911 self.shape().dims(),
8912 other.shape().dims(),
8913 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8914 self.shape().dims(),
8915 other.shape().dims(),
8916 );
8917 let shape = self.shape();
8918 let id = self.graph.write().unwrap().push(Node {
8919 op,
8920 inputs: vec![self.id, other.id],
8921 shape,
8922 // GAP-168(c): comparisons yield a `Bool` mask. This BUILDER path is
8923 // the one eq/ne/lt/le/gt/ge take; it must agree with the
8924 // `primitive_shape` comparison arm (fuel-graph/src/shape.rs), which
8925 // is the OTHER site that decides this dtype (reached on re-lowering).
8926 dtype: DType::Bool,
8927 });
8928 Self {
8929 graph: self.graph.clone(),
8930 id,
8931 }
8932 }
8933
8934 /// Build the backward graph from `self`, treating `self` as the output
8935 /// whose gradient drives the rest of the computation.
8936 ///
8937 /// Walks the forward graph in reverse topological order, applies the
8938 /// per-op gradient rule to each node, and emits new graph nodes for
8939 /// the gradient with respect to every node reachable from `self`. The
8940 /// returned [`GradMap`] lets you look up the gradient tensor for any
8941 /// forward tensor from the same graph.
8942 ///
8943 /// The initial upstream gradient is a ones tensor of the same shape
8944 /// and dtype as `self` — the conventional `dL/dL = 1` seed for
8945 /// backprop. For a scalar loss this is `[1.0]`; for a non-scalar
8946 /// output it is "each element of the output contributes with weight 1
8947 /// to the total derivative."
8948 ///
8949 /// ## Supported ops in the MVP
8950 ///
8951 /// `Const`, `Add`, `Mul`, `MatMul`, `Transpose`, `Sqr`, `Exp` all have
8952 /// gradient rules implemented. `Relu` panics — its gradient needs a
8953 /// `Step`/`Where`/`Sign` op that is not yet in the catalog and will
8954 /// land in a follow-up once an indicator-valued op is defined.
8955 ///
8956 /// ## Ownership and the forward graph
8957 ///
8958 /// Backward extends the same graph that held the forward pass. The
8959 /// gradient nodes live alongside the forward nodes in one arena. After
8960 /// `backward()`, realizing a gradient tensor re-executes whatever part
8961 /// of the forward pass the gradient depends on — the executor walks
8962 /// the combined graph as one.
8963 pub fn backward(&self) -> GradMap {
8964 let graph_handle = self.graph.clone();
8965
8966 // C3 pre-pass (Op::Scan Phase 2): lower every reachable Op::Scan to
8967 // primitives + decompose the SSM fused recipes BEFORE the topo order is
8968 // taken, so the reverse walk sees only differentiable primitives. On a
8969 // scan-free graph it is a near-no-op — two topo scans (Pass 1's SSM
8970 // collect + Pass 2's first iteration, which finds no scans and breaks),
8971 // no rewiring. The (possibly remapped) root replaces self.id below.
8972 let root = lower_scans_for_backward(&graph_handle, self.id);
8973
8974 // Compute topological order of reachable nodes, then reverse it
8975 // so we walk from the root (output) toward the leaves (inputs).
8976 let mut order = topo_order(&graph_handle.read().unwrap(), root);
8977 order.reverse();
8978
8979 // Initial upstream gradient for the root: ones tensor of matching
8980 // shape and dtype. For a scalar loss this is [1.0]; for vector
8981 // outputs it seeds each element with weight 1.
8982 let (root_shape, root_dtype) = {
8983 let g = graph_handle.read().unwrap();
8984 let n = g.node(root);
8985 (n.shape.clone(), n.dtype)
8986 };
8987 let ones_id = build_ones(&graph_handle, root_shape, root_dtype);
8988
8989 let mut upstream: HashMap<NodeId, NodeId> = HashMap::new();
8990 upstream.insert(root, ones_id);
8991
8992 for id in order {
8993 let up_id = match upstream.get(&id).copied() {
8994 Some(v) => v,
8995 None => continue, // unreachable from the root, no gradient to propagate
8996 };
8997 // Snapshot the op and its input IDs so we can drop the read
8998 // borrow before taking a mutable borrow to append new nodes.
8999 let (op, inputs) = {
9000 let g = graph_handle.read().unwrap();
9001 let node = g.node(id);
9002 (node.op.clone(), node.inputs.clone())
9003 };
9004
9005 // Symbolic-autograd dispatch (Phase 6d Track 2). If a
9006 // `GradientRule` is registered for this op, use it. Ops
9007 // that haven't migrated yet fall through to the legacy
9008 // inline `match` below.
9009 if let Some(grads) =
9010 crate::grad::dispatch_gradient(&graph_handle, &op, &inputs, id, up_id)
9011 {
9012 debug_assert_eq!(
9013 grads.len(),
9014 inputs.len(),
9015 "GradientRule for {:?} returned {} gradients but op has {} inputs",
9016 op.short_name(),
9017 grads.len(),
9018 inputs.len(),
9019 );
9020 for (input_id, grad) in inputs.iter().zip(grads.iter()) {
9021 if let Some(g) = grad {
9022 accumulate_grad(&mut upstream, *input_id, *g, &graph_handle);
9023 }
9024 }
9025 continue;
9026 }
9027
9028 match op {
9029 Op::Const => {
9030 // Leaf. The upstream value has already been stored and
9031 // is what `GradMap::get` will return for this input.
9032 }
9033 Op::Iota { .. } => {
9034 // Leaf, non-differentiable: a constant position
9035 // generator with no inputs — no gradient to propagate.
9036 }
9037 Op::NonZeroIndices { .. } => {
9038 // Produces discrete indices + a runtime count; both
9039 // are integer/non-differentiable. No gradient flows to
9040 // the input. (A differentiated graph that reaches this
9041 // op surfaces as a usage error in the grad-emitting
9042 // pass, matching the ArgMaxDim/ArgMinDim precedent.)
9043 }
9044 Op::Add => {
9045 // d(a + b)/da = 1, d(a + b)/db = 1.
9046 // Upstream flows unchanged into both inputs.
9047 accumulate_grad(&mut upstream, inputs[0], up_id, &graph_handle);
9048 accumulate_grad(&mut upstream, inputs[1], up_id, &graph_handle);
9049 }
9050 Op::Mul => {
9051 // d(a * b)/da = b, d(a * b)/db = a.
9052 // Upstream * b goes to a; upstream * a goes to b.
9053 let a = inputs[0];
9054 let b = inputs[1];
9055 let a_shape = node_shape(&graph_handle, a);
9056 let b_shape = node_shape(&graph_handle, b);
9057 let dtype = node_dtype(&graph_handle, a);
9058 let grad_a = push_node(&graph_handle, Op::Mul, vec![up_id, b], a_shape, dtype);
9059 let grad_b = push_node(&graph_handle, Op::Mul, vec![up_id, a], b_shape, dtype);
9060 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9061 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9062 }
9063 Op::MatMul => {
9064 // Forward: Y = A @ B, A: [m, k], B: [k, n], Y: [m, n]
9065 // Backward: dA = dY @ B^T, dB = A^T @ dY.
9066 let a = inputs[0];
9067 let b = inputs[1];
9068 let a_shape = node_shape(&graph_handle, a);
9069 let b_shape = node_shape(&graph_handle, b);
9070 let dtype = node_dtype(&graph_handle, a);
9071 // B^T: shape [n, k]
9072 let b_t_shape = transposed_shape(&b_shape);
9073 let b_t = push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
9074 // dA = upstream @ B^T, shape [m, k] = a_shape
9075 let grad_a = push_node(
9076 &graph_handle,
9077 Op::MatMul,
9078 vec![up_id, b_t],
9079 a_shape.clone(),
9080 dtype,
9081 );
9082 // A^T: shape [k, m]
9083 let a_t_shape = transposed_shape(&a_shape);
9084 let a_t = push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
9085 // dB = A^T @ upstream, shape [k, n] = b_shape
9086 let grad_b =
9087 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
9088 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9089 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9090 }
9091 Op::Transpose => {
9092 // d(x^T)/dx is a transpose on the way back.
9093 let x = inputs[0];
9094 let x_shape = node_shape(&graph_handle, x);
9095 let dtype = node_dtype(&graph_handle, x);
9096 let grad_x =
9097 push_node(&graph_handle, Op::Transpose, vec![up_id], x_shape, dtype);
9098 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9099 }
9100 Op::Permute(ref axes) => {
9101 // Backward: apply the inverse permutation to upstream.
9102 // If forward permutes with `axes` (out[i] = in[axes[i]]),
9103 // the inverse `inv` satisfies `inv[axes[i]] = i`.
9104 let x = inputs[0];
9105 let x_shape = node_shape(&graph_handle, x);
9106 let dtype = node_dtype(&graph_handle, x);
9107 let mut inv = vec![0_usize; axes.len()];
9108 for (i, &ax) in axes.iter().enumerate() {
9109 inv[ax] = i;
9110 }
9111 let grad_x =
9112 push_node(&graph_handle, Op::Permute(inv), vec![up_id], x_shape, dtype);
9113 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9114 }
9115 Op::Sqr => {
9116 // d(x^2)/dx = 2x. Expressed as `x + x` to avoid
9117 // needing a scalar constant broadcast — both sums
9118 // have the same shape as x, the existing Add op
9119 // handles them natively.
9120 let x = inputs[0];
9121 let x_shape = node_shape(&graph_handle, x);
9122 let dtype = node_dtype(&graph_handle, x);
9123 let two_x =
9124 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
9125 let grad_x =
9126 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
9127 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9128 }
9129 Op::Exp => {
9130 // d(e^x)/dx = e^x, which is the forward output — i.e.
9131 // this node `id`. Reuse it directly instead of
9132 // recomputing.
9133 let x = inputs[0];
9134 let out_shape = node_shape(&graph_handle, id);
9135 let dtype = node_dtype(&graph_handle, id);
9136 let grad_x =
9137 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
9138 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9139 }
9140 Op::Sub => {
9141 // d(a - b)/da = 1, d(a - b)/db = -1.
9142 let a = inputs[0];
9143 let b = inputs[1];
9144 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9145 let b_shape = node_shape(&graph_handle, b);
9146 let dtype = node_dtype(&graph_handle, b);
9147 let neg_up = push_node(&graph_handle, Op::Neg, vec![up_id], b_shape, dtype);
9148 accumulate_grad(&mut upstream, b, neg_up, &graph_handle);
9149 }
9150 Op::Div => {
9151 // y = a / b
9152 // dy/da = 1/b → grad_a = upstream / b
9153 // dy/db = -a/b² → grad_b = -(upstream * a / (b*b))
9154 let a = inputs[0];
9155 let b = inputs[1];
9156 let a_shape = node_shape(&graph_handle, a);
9157 let b_shape = node_shape(&graph_handle, b);
9158 let dtype = node_dtype(&graph_handle, a);
9159 // grad_a
9160 let grad_a = push_node(
9161 &graph_handle,
9162 Op::Div,
9163 vec![up_id, b],
9164 a_shape.clone(),
9165 dtype,
9166 );
9167 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9168 // grad_b: -(upstream * a / (b*b))
9169 let b_sq = push_node(&graph_handle, Op::Sqr, vec![b], b_shape.clone(), dtype);
9170 let up_times_a =
9171 push_node(&graph_handle, Op::Mul, vec![up_id, a], a_shape, dtype);
9172 let quotient = push_node(
9173 &graph_handle,
9174 Op::Div,
9175 vec![up_times_a, b_sq],
9176 b_shape.clone(),
9177 dtype,
9178 );
9179 let grad_b = push_node(&graph_handle, Op::Neg, vec![quotient], b_shape, dtype);
9180 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9181 }
9182 Op::Neg => {
9183 // d(-x)/dx = -1. grad_x = -upstream.
9184 let x = inputs[0];
9185 let x_shape = node_shape(&graph_handle, x);
9186 let dtype = node_dtype(&graph_handle, x);
9187 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
9188 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9189 }
9190 Op::Sqrt => {
9191 // y = sqrt(x), dy/dx = 1/(2*sqrt(x)) = 1/(2y).
9192 // grad_x = upstream / (y + y). Reuse the forward node.
9193 let x = inputs[0];
9194 let x_shape = node_shape(&graph_handle, x);
9195 let dtype = node_dtype(&graph_handle, x);
9196 let two_y =
9197 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
9198 let grad_x =
9199 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
9200 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9201 }
9202 Op::Log => {
9203 // d(ln(x))/dx = 1/x. grad_x = upstream / x.
9204 let x = inputs[0];
9205 let x_shape = node_shape(&graph_handle, x);
9206 let dtype = node_dtype(&graph_handle, x);
9207 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
9208 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9209 }
9210 Op::Sin => {
9211 // d(sin(x))/dx = cos(x). grad_x = upstream * cos(x).
9212 let x = inputs[0];
9213 let x_shape = node_shape(&graph_handle, x);
9214 let dtype = node_dtype(&graph_handle, x);
9215 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
9216 let grad_x =
9217 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
9218 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9219 }
9220 Op::Cos => {
9221 // d(cos(x))/dx = -sin(x). grad_x = -(upstream * sin(x)).
9222 let x = inputs[0];
9223 let x_shape = node_shape(&graph_handle, x);
9224 let dtype = node_dtype(&graph_handle, x);
9225 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
9226 let up_sin = push_node(
9227 &graph_handle,
9228 Op::Mul,
9229 vec![up_id, sin_x],
9230 x_shape.clone(),
9231 dtype,
9232 );
9233 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
9234 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9235 }
9236 Op::Tanh => {
9237 // y = tanh(x), dy/dx = 1 - y². grad_x = upstream * (1 - y*y).
9238 // Build: ones_of_y_shape - y*y, then multiply by upstream.
9239 let x = inputs[0];
9240 let y_shape = node_shape(&graph_handle, id);
9241 let dtype = node_dtype(&graph_handle, id);
9242 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
9243 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9244 let one_minus_sq = push_node(
9245 &graph_handle,
9246 Op::Sub,
9247 vec![ones, y_sq],
9248 y_shape.clone(),
9249 dtype,
9250 );
9251 let grad_x = push_node(
9252 &graph_handle,
9253 Op::Mul,
9254 vec![up_id, one_minus_sq],
9255 y_shape,
9256 dtype,
9257 );
9258 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9259 }
9260 Op::Sigmoid => {
9261 // y = sigmoid(x), dy/dx = y * (1 - y).
9262 // grad_x = upstream * y * (1 - y).
9263 let x = inputs[0];
9264 let y_shape = node_shape(&graph_handle, id);
9265 let dtype = node_dtype(&graph_handle, id);
9266 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9267 let one_minus_y = push_node(
9268 &graph_handle,
9269 Op::Sub,
9270 vec![ones, id],
9271 y_shape.clone(),
9272 dtype,
9273 );
9274 let y_times_1my = push_node(
9275 &graph_handle,
9276 Op::Mul,
9277 vec![id, one_minus_y],
9278 y_shape.clone(),
9279 dtype,
9280 );
9281 let grad_x = push_node(
9282 &graph_handle,
9283 Op::Mul,
9284 vec![up_id, y_times_1my],
9285 y_shape,
9286 dtype,
9287 );
9288 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9289 }
9290 Op::Silu => {
9291 // y = x * sigmoid(x)
9292 // dy/dx = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
9293 // = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
9294 //
9295 // Simpler: let s = sigmoid(x). dy/dx = s + y * (1 - s),
9296 // where y = x * s is the forward output (this node).
9297 // grad_x = upstream * (s + y * (1 - s)).
9298 let x = inputs[0];
9299 let x_shape = node_shape(&graph_handle, x);
9300 let dtype = node_dtype(&graph_handle, x);
9301 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
9302 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
9303 let one_minus_s = push_node(
9304 &graph_handle,
9305 Op::Sub,
9306 vec![ones, s],
9307 x_shape.clone(),
9308 dtype,
9309 );
9310 let y_times_1ms = push_node(
9311 &graph_handle,
9312 Op::Mul,
9313 vec![id, one_minus_s],
9314 x_shape.clone(),
9315 dtype,
9316 );
9317 let inner = push_node(
9318 &graph_handle,
9319 Op::Add,
9320 vec![s, y_times_1ms],
9321 x_shape.clone(),
9322 dtype,
9323 );
9324 let grad_x =
9325 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
9326 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9327 }
9328 Op::GeluTanh => {
9329 // GELU's tanh-approximation backward is non-trivial.
9330 // For the MVP, compute it numerically stable via
9331 // central differences — no, that's wrong for
9332 // backward. The proper rule differentiates
9333 // `0.5 x (1 + tanh(c * (x + 0.044715 x³)))` by chain
9334 // rule. That requires several new intermediate
9335 // nodes. Implemented below:
9336 //
9337 // Let u = c * (x + 0.044715 x³), t = tanh(u).
9338 // y = 0.5 x (1 + t)
9339 // du/dx = c * (1 + 3 * 0.044715 * x²)
9340 // = c + 3 c * 0.044715 * x²
9341 // dt/dx = (1 - t²) * du/dx
9342 // dy/dx = 0.5 * (1 + t) + 0.5 * x * dt/dx
9343 //
9344 // This is enough ops that it deserves a dedicated
9345 // backward node. For the MVP, panic — users who need
9346 // GELU backward should use Silu, which we just
9347 // implemented properly.
9348 panic!(
9349 "backward: GeluTanh gradient is not yet supported. \
9350 Use Silu for differentiable training; GeluTanh is \
9351 currently inference-only."
9352 );
9353 }
9354 Op::Relu => {
9355 // d(relu(x))/dx = step(x). grad_x = upstream * step(x).
9356 let x = inputs[0];
9357 let x_shape = node_shape(&graph_handle, x);
9358 let dtype = node_dtype(&graph_handle, x);
9359 let step_x =
9360 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
9361 let grad_x =
9362 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
9363 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9364 }
9365 Op::Step => {
9366 // d(step(x))/dx is 0 almost everywhere (and a Dirac
9367 // delta at 0 which has no finite representation). The
9368 // standard move is to treat the derivative as 0 and
9369 // stop propagation — Step's backward is silently a
9370 // no-op. Callers that need a smooth surrogate should
9371 // use Sigmoid or Tanh instead.
9372 }
9373 Op::Recip => {
9374 // y = 1/x, dy/dx = -1/x² = -y².
9375 // grad_x = -upstream * y * y. Reuse forward output (id)
9376 // so we don't recompute the reciprocal.
9377 let x = inputs[0];
9378 let x_shape = node_shape(&graph_handle, x);
9379 let dtype = node_dtype(&graph_handle, x);
9380 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9381 let up_y_sq = push_node(
9382 &graph_handle,
9383 Op::Mul,
9384 vec![up_id, y_sq],
9385 x_shape.clone(),
9386 dtype,
9387 );
9388 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
9389 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9390 }
9391 Op::Abs => {
9392 // y = |x|, dy/dx = sign(x), with sign(0)=0 by
9393 // subgradient convention. Simplified to a direct
9394 // `Op::Sign` use after Op::Sign landed in PR B2;
9395 // the previous form synthesized `step(x) - step(-x)`
9396 // (5 backward nodes) but Sign expresses the same
9397 // function in 1 node, so the chain shrinks to
9398 // `Mul(upstream, Sign(x))` — 2 nodes total.
9399 let x = inputs[0];
9400 let x_shape = node_shape(&graph_handle, x);
9401 let dtype = node_dtype(&graph_handle, x);
9402 let sign_x =
9403 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
9404 let grad_x =
9405 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
9406 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9407 }
9408 Op::Where => {
9409 // Handled by `WhereRule` via `dispatch_gradient`;
9410 // this arm only exists for exhaustiveness.
9411 }
9412 Op::Floor | Op::Ceil | Op::Round | Op::Sign => {
9413 // d(floor(x))/dx, d(ceil(x))/dx, d(round(x))/dx,
9414 // d(sign(x))/dx are all 0 almost everywhere (with
9415 // a Dirac train at integer / half-integer / zero
9416 // that has no finite representation). Treat the
9417 // derivative as 0 and stop propagation — mirrors
9418 // `Op::Step`'s backward.
9419 }
9420 Op::Erf => {
9421 // y = erf(x). dy/dx = (2/√π) * exp(-x²).
9422 // grad_x = upstream * (2/√π) * exp(-x²).
9423 // Decomposes to: Sqr(x) → Neg → Exp → MulScalar(2/√π)
9424 // → Mul(upstream, .).
9425 // 2/√π = 1.1283791670955125738961589031...
9426 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
9427 let x = inputs[0];
9428 let x_shape = node_shape(&graph_handle, x);
9429 let dtype = node_dtype(&graph_handle, x);
9430 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9431 let neg_x_sq =
9432 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
9433 let exp_neg_x_sq = push_node(
9434 &graph_handle,
9435 Op::Exp,
9436 vec![neg_x_sq],
9437 x_shape.clone(),
9438 dtype,
9439 );
9440 let scaled = push_node(
9441 &graph_handle,
9442 Op::MulScalar(TWO_OVER_SQRT_PI),
9443 vec![exp_neg_x_sq],
9444 x_shape.clone(),
9445 dtype,
9446 );
9447 let grad_x =
9448 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9449 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9450 }
9451 Op::Flip { dim } => {
9452 // y = flip(x, dim). Backward is another Flip on
9453 // the same dim — Flip is its own inverse
9454 // (involutive). One backward node, exact gradient.
9455 let x = inputs[0];
9456 let x_shape = node_shape(&graph_handle, x);
9457 let dtype = node_dtype(&graph_handle, x);
9458 let grad_x =
9459 push_node(&graph_handle, Op::Flip { dim }, vec![up_id], x_shape, dtype);
9460 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9461 }
9462 Op::Pad {
9463 padding,
9464 mode,
9465 value: _,
9466 } => {
9467 // Backward delegates to Op::PadBackward — a single
9468 // node that handles all three modes uniformly via
9469 // its kernel. Constant: slice the unpadded region.
9470 // Reflect/Replicate: accumulate gradient at the
9471 // mirrored / replicated positions.
9472 let padding = padding.clone();
9473 let x = inputs[0];
9474 let x_shape = node_shape(&graph_handle, x);
9475 let dtype = node_dtype(&graph_handle, x);
9476 let grad_x = push_node(
9477 &graph_handle,
9478 Op::PadBackward {
9479 in_shape: x_shape.clone(),
9480 padding,
9481 mode,
9482 },
9483 vec![up_id],
9484 x_shape,
9485 dtype,
9486 );
9487 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9488 }
9489 Op::PadBackward { .. } => {
9490 // Backward helper — typically a leaf in autograd
9491 // (the upstream gradient itself never gets a
9492 // higher-order backward in v1). No-op arm for
9493 // exhaustiveness; if higher-order autograd needs
9494 // PadBackward's backward, that's its own scope.
9495 }
9496 Op::CumSum { dim } => {
9497 // y[..., i, ...] = sum_{k=0..=i} x[..., k, ...]
9498 // dL/dx[..., i, ...] = sum_{k=i..n} dL/dy[..., k, ...]
9499 // i.e. reverse cumsum. Express via Flip → CumSum → Flip.
9500 let x = inputs[0];
9501 let x_shape = node_shape(&graph_handle, x);
9502 let dtype = node_dtype(&graph_handle, x);
9503 let flip1 = push_node(
9504 &graph_handle,
9505 Op::Flip { dim },
9506 vec![up_id],
9507 x_shape.clone(),
9508 dtype,
9509 );
9510 let cs = push_node(
9511 &graph_handle,
9512 Op::CumSum { dim },
9513 vec![flip1],
9514 x_shape.clone(),
9515 dtype,
9516 );
9517 let grad_x =
9518 push_node(&graph_handle, Op::Flip { dim }, vec![cs], x_shape, dtype);
9519 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9520 }
9521 Op::Roll { dim, shift } => {
9522 // y = roll(x, dim, shift). Backward is the opposite
9523 // shift along the same dim. One backward node.
9524 let x = inputs[0];
9525 let x_shape = node_shape(&graph_handle, x);
9526 let dtype = node_dtype(&graph_handle, x);
9527 let grad_x = push_node(
9528 &graph_handle,
9529 Op::Roll { dim, shift: -shift },
9530 vec![up_id],
9531 x_shape,
9532 dtype,
9533 );
9534 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9535 }
9536 Op::Triu { diagonal } => {
9537 // y = triu(x, diagonal). Mask is a binary indicator
9538 // — gradient passes through kept positions and is
9539 // zero on the masked half. Same op on the upstream.
9540 let x = inputs[0];
9541 let x_shape = node_shape(&graph_handle, x);
9542 let dtype = node_dtype(&graph_handle, x);
9543 let grad_x = push_node(
9544 &graph_handle,
9545 Op::Triu { diagonal },
9546 vec![up_id],
9547 x_shape,
9548 dtype,
9549 );
9550 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9551 }
9552 Op::Tril { diagonal } => {
9553 // Mirror of Op::Triu — same mask gradient.
9554 let x = inputs[0];
9555 let x_shape = node_shape(&graph_handle, x);
9556 let dtype = node_dtype(&graph_handle, x);
9557 let grad_x = push_node(
9558 &graph_handle,
9559 Op::Tril { diagonal },
9560 vec![up_id],
9561 x_shape,
9562 dtype,
9563 );
9564 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9565 }
9566 Op::LogSoftmaxLastDim => {
9567 // grad_x = upstream - exp(y) * sum(upstream, last_dim, keepdim).
9568 // Folded into Op::LogSoftmaxLastDimBackward — takes
9569 // (forward_output, upstream), avoids re-evaluating
9570 // the softmax outside the kernel.
9571 let x = inputs[0];
9572 let x_shape = node_shape(&graph_handle, x);
9573 let dtype = node_dtype(&graph_handle, x);
9574 let grad_x = push_node(
9575 &graph_handle,
9576 Op::LogSoftmaxLastDimBackward,
9577 vec![id, up_id],
9578 x_shape,
9579 dtype,
9580 );
9581 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9582 }
9583 Op::LogSoftmaxLastDimBackward => {
9584 // Backward helper — no higher-order autograd in v1.
9585 }
9586 Op::MaskedFill { value: _ } => {
9587 // y = mask ? value : x. dy/dx = (mask == 0).
9588 // grad_x = MaskedFill(upstream, mask, value=0_of_dtype).
9589 // The mask is integer-only; no gradient flows to it.
9590 let x = inputs[0];
9591 let mask = inputs[1];
9592 let x_shape = node_shape(&graph_handle, x);
9593 let dtype = node_dtype(&graph_handle, x);
9594 let zero = match fuel_ir::Scalar::zero(dtype) {
9595 Ok(z) => z,
9596 Err(_) => {
9597 // A packed/scale dtype has no zero scalar. MaskedFill
9598 // on such a dtype is a build-time bug (a future D5
9599 // graph-build guard forbids it), so this is
9600 // unreachable in a well-formed graph. debug_assert
9601 // catches it in debug; release skips this gradient
9602 // rather than panicking (never-panic invariant).
9603 debug_assert!(false, "MaskedFill backward on non-real dtype {dtype:?}");
9604 continue;
9605 }
9606 };
9607 let grad_x = push_node(
9608 &graph_handle,
9609 Op::MaskedFill { value: zero },
9610 vec![up_id, mask],
9611 x_shape,
9612 dtype,
9613 );
9614 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9615 // No gradient to mask: it's discrete.
9616 }
9617 Op::Rem => {
9618 // y = a - floor(a/b) * b (PyTorch convention).
9619 // d/da = 1 (the floor term is treated as a constant
9620 // w.r.t. a almost everywhere; the actual
9621 // derivative has a Dirac component at
9622 // integer a/b ratios that we drop, matching
9623 // PyTorch's autograd convention).
9624 // d/db = -floor(a/b)
9625 // grad_a = upstream
9626 // grad_b = upstream * (-floor(a/b))
9627 let a = inputs[0];
9628 let b = inputs[1];
9629 let a_shape = node_shape(&graph_handle, a);
9630 let dtype = node_dtype(&graph_handle, a);
9631 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9632 let div_ab =
9633 push_node(&graph_handle, Op::Div, vec![a, b], a_shape.clone(), dtype);
9634 let floor_div = push_node(
9635 &graph_handle,
9636 Op::Floor,
9637 vec![div_ab],
9638 a_shape.clone(),
9639 dtype,
9640 );
9641 let neg_floor = push_node(
9642 &graph_handle,
9643 Op::Neg,
9644 vec![floor_div],
9645 a_shape.clone(),
9646 dtype,
9647 );
9648 let grad_b = push_node(
9649 &graph_handle,
9650 Op::Mul,
9651 vec![up_id, neg_floor],
9652 a_shape,
9653 dtype,
9654 );
9655 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9656 }
9657 Op::Rsqrt => {
9658 // y = x^(-1/2). dy/dx = -0.5 * x^(-3/2).
9659 // Identity: y² = 1/x, so x^(-3/2) = y/x = y * y² = y³.
9660 // grad_x = -0.5 * upstream * y³.
9661 // Reuses the forward output id for y; never touches
9662 // x directly (avoids the divide-by-zero singularity
9663 // that the obvious `-0.5 * upstream * y / x` form
9664 // would have).
9665 let x = inputs[0];
9666 let x_shape = node_shape(&graph_handle, x);
9667 let dtype = node_dtype(&graph_handle, x);
9668 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9669 let y_cu = push_node(
9670 &graph_handle,
9671 Op::Mul,
9672 vec![id, y_sq],
9673 x_shape.clone(),
9674 dtype,
9675 );
9676 let scaled = push_node(
9677 &graph_handle,
9678 Op::MulScalar(-0.5),
9679 vec![y_cu],
9680 x_shape.clone(),
9681 dtype,
9682 );
9683 let grad_x =
9684 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9685 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9686 }
9687 Op::Pow => {
9688 // y = pow(a, b).
9689 // d/da = b * pow(a, b-1)
9690 // d/db = y * ln(a)
9691 // grad_a = upstream * b * pow(a, b-1)
9692 // grad_b = upstream * y * ln(a)
9693 // The forward output `id` IS y; we reuse it.
9694 let a = inputs[0];
9695 let b = inputs[1];
9696 let a_shape = node_shape(&graph_handle, a);
9697 let dtype = node_dtype(&graph_handle, a);
9698 // d/da branch: pow(a, b - 1)
9699 let b_minus_one = push_node(
9700 &graph_handle,
9701 Op::AddScalar(-1.0),
9702 vec![b],
9703 a_shape.clone(),
9704 dtype,
9705 );
9706 let pow_a_bm1 = push_node(
9707 &graph_handle,
9708 Op::Pow,
9709 vec![a, b_minus_one],
9710 a_shape.clone(),
9711 dtype,
9712 );
9713 let b_times_pow = push_node(
9714 &graph_handle,
9715 Op::Mul,
9716 vec![b, pow_a_bm1],
9717 a_shape.clone(),
9718 dtype,
9719 );
9720 let grad_a = push_node(
9721 &graph_handle,
9722 Op::Mul,
9723 vec![up_id, b_times_pow],
9724 a_shape.clone(),
9725 dtype,
9726 );
9727 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9728 // d/db branch: y * ln(a)
9729 let log_a = push_node(&graph_handle, Op::Log, vec![a], a_shape.clone(), dtype);
9730 let y_log_a = push_node(
9731 &graph_handle,
9732 Op::Mul,
9733 vec![id, log_a],
9734 a_shape.clone(),
9735 dtype,
9736 );
9737 let grad_b =
9738 push_node(&graph_handle, Op::Mul, vec![up_id, y_log_a], a_shape, dtype);
9739 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9740 }
9741 Op::Gelu => {
9742 // y = 0.5 * x * (1 + erf(x/√2)).
9743 // dy/dx = Φ(x) + x · φ(x)
9744 // = 0.5 * (1 + erf(x/√2))
9745 // + x * (1/√(2π)) * exp(-x²/2)
9746 // where Φ is the standard-normal CDF (= y/x for x≠0;
9747 // we recompute it explicitly so the backward stays
9748 // safe at x=0) and φ is the PDF.
9749 //
9750 // Chain (12 nodes):
9751 // x_over_sqrt2 = MulScalar(1/√2)(x)
9752 // erf_arg = Erf(x_over_sqrt2)
9753 // plus_one = AddScalar(1.0)(erf_arg)
9754 // cdf_term = MulScalar(0.5)(plus_one)
9755 // x_sq = Sqr(x)
9756 // half_x_sq = MulScalar(0.5)(x_sq)
9757 // neg_half_x_sq= Neg(half_x_sq)
9758 // exp_term = Exp(neg_half_x_sq)
9759 // phi = MulScalar(1/√(2π))(exp_term)
9760 // pdf_term = Mul(x, phi)
9761 // d_gelu = Add(cdf_term, pdf_term)
9762 // grad_x = Mul(upstream, d_gelu)
9763 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
9764 // 1/√(2π) = 0.39894228040143267793994605993...
9765 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
9766 let x = inputs[0];
9767 let x_shape = node_shape(&graph_handle, x);
9768 let dtype = node_dtype(&graph_handle, x);
9769 // CDF half: 0.5 * (1 + erf(x/√2)).
9770 let x_over_sqrt2 = push_node(
9771 &graph_handle,
9772 Op::MulScalar(INV_SQRT_2),
9773 vec![x],
9774 x_shape.clone(),
9775 dtype,
9776 );
9777 let erf_arg = push_node(
9778 &graph_handle,
9779 Op::Erf,
9780 vec![x_over_sqrt2],
9781 x_shape.clone(),
9782 dtype,
9783 );
9784 let plus_one = push_node(
9785 &graph_handle,
9786 Op::AddScalar(1.0),
9787 vec![erf_arg],
9788 x_shape.clone(),
9789 dtype,
9790 );
9791 let cdf_term = push_node(
9792 &graph_handle,
9793 Op::MulScalar(0.5),
9794 vec![plus_one],
9795 x_shape.clone(),
9796 dtype,
9797 );
9798 // PDF half: x * (1/√(2π)) * exp(-x²/2).
9799 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9800 let half_x_sq = push_node(
9801 &graph_handle,
9802 Op::MulScalar(0.5),
9803 vec![x_sq],
9804 x_shape.clone(),
9805 dtype,
9806 );
9807 let neg_half_x_sq = push_node(
9808 &graph_handle,
9809 Op::Neg,
9810 vec![half_x_sq],
9811 x_shape.clone(),
9812 dtype,
9813 );
9814 let exp_term = push_node(
9815 &graph_handle,
9816 Op::Exp,
9817 vec![neg_half_x_sq],
9818 x_shape.clone(),
9819 dtype,
9820 );
9821 let phi = push_node(
9822 &graph_handle,
9823 Op::MulScalar(INV_SQRT_2PI),
9824 vec![exp_term],
9825 x_shape.clone(),
9826 dtype,
9827 );
9828 let pdf_term =
9829 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
9830 // Sum the two halves and apply upstream.
9831 let d_gelu = push_node(
9832 &graph_handle,
9833 Op::Add,
9834 vec![cdf_term, pdf_term],
9835 x_shape.clone(),
9836 dtype,
9837 );
9838 let grad_x =
9839 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
9840 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9841 }
9842 Op::Equal | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => {
9843 // Comparison family: handled by `NoGradientBinaryRule`
9844 // via `dispatch_gradient`. The `if let Some(grads) =
9845 // dispatch_gradient(...) { continue; }` block above
9846 // intercepts before we get here. This arm exists only
9847 // for exhaustiveness; it should be unreachable in
9848 // practice. Keeping it as a no-op rather than
9849 // `unreachable!()` defends against a future hand-edit
9850 // that removes the dispatcher arm by mistake — the
9851 // graph still terminates traversal cleanly.
9852 }
9853 Op::Cast(_) => {
9854 // Forward: y = cast(x, target_dtype).
9855 // Backward: dL/dx = cast(upstream, source_dtype).
9856 let x = inputs[0];
9857 let x_dtype = node_dtype(&graph_handle, x);
9858 let x_shape = node_shape(&graph_handle, x);
9859 let grad_x = push_node(
9860 &graph_handle,
9861 Op::Cast(x_dtype),
9862 vec![up_id],
9863 x_shape,
9864 x_dtype,
9865 );
9866 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9867 }
9868 Op::SumAll => {
9869 // Forward: y = sum(x), scalar.
9870 // Backward: dL/dx = broadcast_to(upstream, x.shape).
9871 let x = inputs[0];
9872 let x_shape = node_shape(&graph_handle, x);
9873 let dtype = node_dtype(&graph_handle, x);
9874 let grad_x = push_node(
9875 &graph_handle,
9876 Op::BroadcastTo(x_shape.clone()),
9877 vec![up_id],
9878 x_shape,
9879 dtype,
9880 );
9881 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9882 }
9883 Op::MeanAll => {
9884 // Forward: y = mean(x) = sum(x) / n, scalar.
9885 // Backward: dL/dx = broadcast_to(upstream / n, x.shape).
9886 // We build `ones / n` as a constant of shape x.shape
9887 // and multiply by broadcast_to(upstream, x.shape).
9888 // Simpler: broadcast upstream, then divide by an n-const.
9889 let x = inputs[0];
9890 let x_shape = node_shape(&graph_handle, x);
9891 let dtype = node_dtype(&graph_handle, x);
9892 let n_elem = x_shape.elem_count();
9893 let broadcast_up = push_node(
9894 &graph_handle,
9895 Op::BroadcastTo(x_shape.clone()),
9896 vec![up_id],
9897 x_shape.clone(),
9898 dtype,
9899 );
9900 let n_const =
9901 build_filled_const(&graph_handle, x_shape.clone(), dtype, n_elem as f64);
9902 let grad_x = push_node(
9903 &graph_handle,
9904 Op::Div,
9905 vec![broadcast_up, n_const],
9906 x_shape,
9907 dtype,
9908 );
9909 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9910 }
9911 Op::BroadcastTo(_) => {
9912 // Forward: y = broadcast_to(x, target).
9913 // Backward: dL/dx = reduce_sum_to(upstream, x.shape) —
9914 // sum away every dim that was expanded or newly added.
9915 let x = inputs[0];
9916 let x_shape = node_shape(&graph_handle, x);
9917 let dtype = node_dtype(&graph_handle, x);
9918 let grad_x = push_node(
9919 &graph_handle,
9920 Op::ReduceSumTo(x_shape.clone()),
9921 vec![up_id],
9922 x_shape,
9923 dtype,
9924 );
9925 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9926 }
9927 Op::Reshape(_) => {
9928 // Forward: y = reshape(x, target). Data unchanged.
9929 // Backward: reshape upstream back to x.shape.
9930 let x = inputs[0];
9931 let x_shape = node_shape(&graph_handle, x);
9932 let dtype = node_dtype(&graph_handle, x);
9933 let grad_x = push_node(
9934 &graph_handle,
9935 Op::Reshape(x_shape.clone()),
9936 vec![up_id],
9937 x_shape,
9938 dtype,
9939 );
9940 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9941 }
9942 Op::Contiguize => {
9943 // Forward: y = contiguize(x). Identity at the
9944 // value level; only the layout differs. Backward:
9945 // pass upstream through unchanged. The
9946 // downstream `accumulate_grad` will sum this
9947 // into x's gradient regardless of x's own layout.
9948 let x = inputs[0];
9949 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
9950 }
9951 Op::Unsqueeze { dim: _ } => {
9952 // Forward: y = unsqueeze(x, dim) — inserts a size-1
9953 // axis without touching bytes. Backward: drop that
9954 // axis. Bytes are unchanged either direction; a
9955 // Reshape to x.shape is the simplest expression of
9956 // "same bytes, different rank" that the executor
9957 // handles natively.
9958 let x = inputs[0];
9959 let x_shape = node_shape(&graph_handle, x);
9960 let dtype = node_dtype(&graph_handle, x);
9961 let grad_x = push_node(
9962 &graph_handle,
9963 Op::Reshape(x_shape.clone()),
9964 vec![up_id],
9965 x_shape,
9966 dtype,
9967 );
9968 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9969 }
9970 Op::Squeeze { dim } => {
9971 // Forward: y = squeeze(x, dim) — drops a size-1 axis,
9972 // metadata-only. Backward: re-insert the axis at the
9973 // same position via Unsqueeze. Both directions are
9974 // metadata-only views (no bytes touched).
9975 let x = inputs[0];
9976 let x_shape = node_shape(&graph_handle, x);
9977 let dtype = node_dtype(&graph_handle, x);
9978 let grad_x = push_node(
9979 &graph_handle,
9980 Op::Unsqueeze { dim },
9981 vec![up_id],
9982 x_shape,
9983 dtype,
9984 );
9985 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9986 }
9987 Op::ReduceSumTo(_) => {
9988 // Forward: y = reduce_sum_to(x, target).
9989 // Backward: broadcast upstream back to x.shape.
9990 let x = inputs[0];
9991 let x_shape = node_shape(&graph_handle, x);
9992 let dtype = node_dtype(&graph_handle, x);
9993 let grad_x = push_node(
9994 &graph_handle,
9995 Op::BroadcastTo(x_shape.clone()),
9996 vec![up_id],
9997 x_shape,
9998 dtype,
9999 );
10000 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10001 }
10002 Op::MaxAll | Op::MinAll => {
10003 // For y = max(x) (or min), the gradient is an
10004 // indicator at the argmax positions, distributed
10005 // across ties. Expressed without a dedicated argmax
10006 // op using the Step trick:
10007 //
10008 // broadcasted_y = broadcast_to(y, x.shape)
10009 // diff = broadcasted_y - x (for Max)
10010 // | x - broadcasted_y (for Min)
10011 // indicator = ones - step(diff)
10012 // grad_x = broadcast_to(upstream, x.shape) * indicator
10013 //
10014 // At argmax positions `diff == 0`, `step(0) == 0`, so
10015 // the indicator is 1. Elsewhere `diff > 0` so step is
10016 // 1 and the indicator is 0. Ties share the gradient.
10017 let x = inputs[0];
10018 let x_shape = node_shape(&graph_handle, x);
10019 let dtype = node_dtype(&graph_handle, x);
10020 let is_max = matches!(op, Op::MaxAll);
10021 let broadcasted_y = push_node(
10022 &graph_handle,
10023 Op::BroadcastTo(x_shape.clone()),
10024 vec![id],
10025 x_shape.clone(),
10026 dtype,
10027 );
10028 let diff = if is_max {
10029 push_node(
10030 &graph_handle,
10031 Op::Sub,
10032 vec![broadcasted_y, x],
10033 x_shape.clone(),
10034 dtype,
10035 )
10036 } else {
10037 push_node(
10038 &graph_handle,
10039 Op::Sub,
10040 vec![x, broadcasted_y],
10041 x_shape.clone(),
10042 dtype,
10043 )
10044 };
10045 let step_diff =
10046 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10047 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10048 let indicator = push_node(
10049 &graph_handle,
10050 Op::Sub,
10051 vec![ones, step_diff],
10052 x_shape.clone(),
10053 dtype,
10054 );
10055 let broadcast_up = push_node(
10056 &graph_handle,
10057 Op::BroadcastTo(x_shape.clone()),
10058 vec![up_id],
10059 x_shape.clone(),
10060 dtype,
10061 );
10062 let grad_x = push_node(
10063 &graph_handle,
10064 Op::Mul,
10065 vec![broadcast_up, indicator],
10066 x_shape,
10067 dtype,
10068 );
10069 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10070 }
10071 Op::SumDim(dim) => {
10072 // Insert a size-1 at `dim` via reshape, then broadcast
10073 // back to x.shape.
10074 let x = inputs[0];
10075 let x_shape = node_shape(&graph_handle, x);
10076 let dtype = node_dtype(&graph_handle, x);
10077 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10078 let reshaped = push_node(
10079 &graph_handle,
10080 Op::Reshape(keepdim_shape.clone()),
10081 vec![up_id],
10082 keepdim_shape,
10083 dtype,
10084 );
10085 let grad_x = push_node(
10086 &graph_handle,
10087 Op::BroadcastTo(x_shape.clone()),
10088 vec![reshaped],
10089 x_shape,
10090 dtype,
10091 );
10092 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10093 }
10094 Op::MeanDim(dim) => {
10095 // SumDim-style backward, then divide by the reduced dim size.
10096 let x = inputs[0];
10097 let x_shape = node_shape(&graph_handle, x);
10098 let dtype = node_dtype(&graph_handle, x);
10099 let reduced_size = x_shape.dims()[dim];
10100 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10101 let reshaped = push_node(
10102 &graph_handle,
10103 Op::Reshape(keepdim_shape.clone()),
10104 vec![up_id],
10105 keepdim_shape,
10106 dtype,
10107 );
10108 let broadcast = push_node(
10109 &graph_handle,
10110 Op::BroadcastTo(x_shape.clone()),
10111 vec![reshaped],
10112 x_shape.clone(),
10113 dtype,
10114 );
10115 let n_const = build_filled_const(
10116 &graph_handle,
10117 x_shape.clone(),
10118 dtype,
10119 reduced_size as f64,
10120 );
10121 let grad_x = push_node(
10122 &graph_handle,
10123 Op::Div,
10124 vec![broadcast, n_const],
10125 x_shape,
10126 dtype,
10127 );
10128 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10129 }
10130 Op::MaxDim(dim) | Op::MinDim(dim) => {
10131 // Same indicator trick as MaxAll/MinAll, but apply the
10132 // "reshape to keepdim then broadcast" pattern to both
10133 // the forward output and upstream before multiplying.
10134 let x = inputs[0];
10135 let x_shape = node_shape(&graph_handle, x);
10136 let dtype = node_dtype(&graph_handle, x);
10137 let is_max = matches!(op, Op::MaxDim(_));
10138 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10139 let y_keepdim = push_node(
10140 &graph_handle,
10141 Op::Reshape(keepdim_shape.clone()),
10142 vec![id],
10143 keepdim_shape.clone(),
10144 dtype,
10145 );
10146 let broadcasted_y = push_node(
10147 &graph_handle,
10148 Op::BroadcastTo(x_shape.clone()),
10149 vec![y_keepdim],
10150 x_shape.clone(),
10151 dtype,
10152 );
10153 let diff = if is_max {
10154 push_node(
10155 &graph_handle,
10156 Op::Sub,
10157 vec![broadcasted_y, x],
10158 x_shape.clone(),
10159 dtype,
10160 )
10161 } else {
10162 push_node(
10163 &graph_handle,
10164 Op::Sub,
10165 vec![x, broadcasted_y],
10166 x_shape.clone(),
10167 dtype,
10168 )
10169 };
10170 let step_diff =
10171 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10172 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10173 let indicator = push_node(
10174 &graph_handle,
10175 Op::Sub,
10176 vec![ones, step_diff],
10177 x_shape.clone(),
10178 dtype,
10179 );
10180 let up_keepdim = push_node(
10181 &graph_handle,
10182 Op::Reshape(keepdim_shape.clone()),
10183 vec![up_id],
10184 keepdim_shape,
10185 dtype,
10186 );
10187 let broadcast_up = push_node(
10188 &graph_handle,
10189 Op::BroadcastTo(x_shape.clone()),
10190 vec![up_keepdim],
10191 x_shape.clone(),
10192 dtype,
10193 );
10194 let grad_x = push_node(
10195 &graph_handle,
10196 Op::Mul,
10197 vec![broadcast_up, indicator],
10198 x_shape,
10199 dtype,
10200 );
10201 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10202 }
10203 // Phase 7.6 step 5 (2026-05-11): the legacy
10204 // `Op::SoftmaxLastDim` / `Op::LayerNormLastDim` /
10205 // `Op::RmsNormLastDim` / `Op::Rope` /
10206 // `Op::Conv2D` / `Op::FusedLinear` arms have been
10207 // dropped together with the variants themselves; the
10208 // `Op::Fused(fid, _)` arm below dispatches per id and
10209 // is the single source of truth for migrated forward
10210 // ops' backward.
10211 Op::ArgMaxDim(_) | Op::ArgMinDim(_) => {
10212 // Argmax/argmin produce integer indices, which are
10213 // non-differentiable. Panic rather than silently
10214 // zero-propagating — if the user has one of these in
10215 // their differentiated graph, they've almost
10216 // certainly made a mistake.
10217 panic!(
10218 "backward: ArgMaxDim/ArgMinDim produce integer \
10219 indices and cannot be differentiated through. \
10220 Use MaxDim/MinDim if you want a differentiable \
10221 selection."
10222 );
10223 }
10224 Op::ReduceMaxTo(_) => {
10225 // Forward: y = reduce_max_to(x, target).
10226 // Backward: route upstream to position(s) where
10227 // x equals its per-window max via the fused
10228 // backward helper Op::Fused(REDUCE_MAX_TO_BACKWARD,
10229 // _) (takes (x, upstream) and emits grad_x of
10230 // x.shape). Tied maxes share the gradient equally
10231 // (fair-share subgradient). Note this is the
10232 // backward of a *primitive* (Op::ReduceMaxTo),
10233 // not a fused forward — no BackwardKind::Fused
10234 // edge in the registry drives this; the explicit
10235 // emission is the source of truth.
10236 let x = inputs[0];
10237 let x_shape = node_shape(&graph_handle, x);
10238 let dtype = node_dtype(&graph_handle, x);
10239 let grad_x = push_node(
10240 &graph_handle,
10241 Op::Fused(
10242 crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD,
10243 crate::registry::FusedOpParams::ReduceMaxToBackward,
10244 ),
10245 vec![x, up_id],
10246 x_shape,
10247 dtype,
10248 );
10249 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10250 }
10251 // Phase 7.6 step 5 (final, 2026-05-11): legacy
10252 // `Op::QMatMul` arm dropped with the variant; QMatMul
10253 // backward panics via the Op::Fused arm below.
10254 // Phase 7.6 step 5 (2026-05-11): the legacy
10255 // `Op::SoftmaxLastDimBackward | Op::LayerNormLastDimBackward |
10256 // Op::RmsNormLastDimBackward | Op::ReduceMaxToBackward`
10257 // higher-order panic arm has been dropped together
10258 // with the variants themselves. The Op::Fused arm
10259 // below panics for those four ids.
10260 Op::IndexSelect { dim } => {
10261 // Forward: out = index_select(data, dim, indices).
10262 // Backward: grad_data = index_add(zeros_like(data), dim, indices, upstream).
10263 let data = inputs[0];
10264 let idx = inputs[1];
10265 let data_shape = node_shape(&graph_handle, data);
10266 let dtype = node_dtype(&graph_handle, data);
10267 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10268 let grad_data = push_node(
10269 &graph_handle,
10270 Op::IndexAdd { dim },
10271 vec![zeros, idx, up_id],
10272 data_shape,
10273 dtype,
10274 );
10275 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10276 // Index tensor is itself non-differentiable (integer dtype).
10277 }
10278 Op::Gather { dim } => {
10279 // Forward: out = gather(data, dim, indices).
10280 // Backward: grad_data = scatter_add(zeros_like(data), dim, indices, upstream).
10281 let data = inputs[0];
10282 let idx = inputs[1];
10283 let data_shape = node_shape(&graph_handle, data);
10284 let dtype = node_dtype(&graph_handle, data);
10285 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10286 let grad_data = push_node(
10287 &graph_handle,
10288 Op::ScatterAdd { dim },
10289 vec![zeros, idx, up_id],
10290 data_shape,
10291 dtype,
10292 );
10293 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10294 }
10295 Op::IndexAdd { dim } => {
10296 // Forward: out = index_add(base, dim, indices, src).
10297 // Backward:
10298 // grad_base = upstream (pass-through — base flows
10299 // through the non-indexed positions and
10300 // the accumulated positions don't zero
10301 // it out, they add to it)
10302 // grad_src = index_select(upstream, dim, indices)
10303 // (the pieces of upstream that came from
10304 // src in the forward).
10305 let base = inputs[0];
10306 let idx = inputs[1];
10307 let src = inputs[2];
10308 let src_shape = node_shape(&graph_handle, src);
10309 let dtype = node_dtype(&graph_handle, src);
10310 // grad_base: upstream passes through.
10311 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10312 // grad_src: select from upstream at the indices.
10313 let grad_src = push_node(
10314 &graph_handle,
10315 Op::IndexSelect { dim },
10316 vec![up_id, idx],
10317 src_shape,
10318 dtype,
10319 );
10320 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10321 }
10322 Op::Concat { dim } => {
10323 // Forward: out = concat(inputs.., dim).
10324 // Backward: split upstream along `dim` into one slice per
10325 // input at the cumulative offset, routing each slice to its
10326 // input. N-ary (unroll_scan stacks N per-step ys into a
10327 // single Concat; the SSM/Hopfield BPTT unroll relies on
10328 // this). Duplicate inputs accumulate via accumulate_grad.
10329 let mut start = 0usize;
10330 for &inp in &inputs {
10331 let in_shape = node_shape(&graph_handle, inp);
10332 let dtype = node_dtype(&graph_handle, inp);
10333 let len = in_shape.dims()[dim];
10334 let grad_in = push_node(
10335 &graph_handle,
10336 Op::Slice { dim, start, len },
10337 vec![up_id],
10338 in_shape,
10339 dtype,
10340 );
10341 accumulate_grad(&mut upstream, inp, grad_in, &graph_handle);
10342 start += len;
10343 }
10344 }
10345 Op::Slice { dim, start, len: _ } => {
10346 // Forward: out = slice(x, dim, start, len).
10347 // Backward: build a zeros tensor of x.shape, then
10348 // scatter the upstream into the slice range. We use
10349 // a concat of three pieces: left zeros, upstream,
10350 // right zeros (along `dim`).
10351 let x = inputs[0];
10352 let x_shape = node_shape(&graph_handle, x);
10353 let dtype = node_dtype(&graph_handle, x);
10354 let x_dims = x_shape.dims();
10355 let dim_size = x_dims[dim];
10356 let up_len = x_dims[dim].min(node_shape(&graph_handle, up_id).dims()[dim]);
10357 let left_len = start;
10358 let right_len = dim_size - start - up_len;
10359 // Build left zero pad if needed.
10360 let mut pieces: Vec<NodeId> = Vec::new();
10361 if left_len > 0 {
10362 let mut left_dims: Vec<usize> = x_dims.to_vec();
10363 left_dims[dim] = left_len;
10364 let left_shape = Shape::from_dims(&left_dims);
10365 pieces.push(build_filled_const(&graph_handle, left_shape, dtype, 0.0));
10366 }
10367 pieces.push(up_id);
10368 if right_len > 0 {
10369 let mut right_dims: Vec<usize> = x_dims.to_vec();
10370 right_dims[dim] = right_len;
10371 let right_shape = Shape::from_dims(&right_dims);
10372 pieces.push(build_filled_const(&graph_handle, right_shape, dtype, 0.0));
10373 }
10374 // Fold concat-left-to-right.
10375 let mut current = pieces[0];
10376 let mut current_dims: Vec<usize> = {
10377 let n = graph_handle.read().unwrap();
10378 n.node(current).shape.dims().to_vec()
10379 };
10380 for &next in &pieces[1..] {
10381 let next_dims: Vec<usize> = {
10382 let n = graph_handle.read().unwrap();
10383 n.node(next).shape.dims().to_vec()
10384 };
10385 let mut combined = current_dims.clone();
10386 combined[dim] = current_dims[dim] + next_dims[dim];
10387 let combined_shape = Shape::from_dims(&combined);
10388 current = push_node(
10389 &graph_handle,
10390 Op::Concat { dim },
10391 vec![current, next],
10392 combined_shape,
10393 dtype,
10394 );
10395 current_dims = combined;
10396 }
10397 accumulate_grad(&mut upstream, x, current, &graph_handle);
10398 }
10399 Op::AddScalar(_) => {
10400 // y = x + c, dy/dx = 1. Upstream passes through.
10401 let x = inputs[0];
10402 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10403 }
10404 Op::MulScalar(c) => {
10405 // y = x * c, dy/dx = c. Multiply upstream by c via
10406 // another MulScalar node.
10407 let x = inputs[0];
10408 let x_shape = node_shape(&graph_handle, x);
10409 let dtype = node_dtype(&graph_handle, x);
10410 let grad_x =
10411 push_node(&graph_handle, Op::MulScalar(c), vec![up_id], x_shape, dtype);
10412 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10413 }
10414 Op::PowI(n) => {
10415 // y = x^n, dy/dx = n * x^(n-1).
10416 // grad_x = upstream * n * x^(n-1). Emitted as a
10417 // single fused PowIBackward node; the executor
10418 // routes it to baracuda's `unary_powi_backward_*`
10419 // kernel (alpha.31) on CUDA, or falls back to the
10420 // primitive decomposition (PowI(n-1) → MulScalar →
10421 // Mul) on backends that haven't registered the
10422 // fused kernel.
10423 let x = inputs[0];
10424 let x_shape = node_shape(&graph_handle, x);
10425 let dtype = node_dtype(&graph_handle, x);
10426 let grad_x = push_node(
10427 &graph_handle,
10428 Op::Fused(
10429 crate::registry::FusedOps::POWI_BACKWARD,
10430 crate::registry::FusedOpParams::PowIBackward { exp: n },
10431 ),
10432 vec![x, up_id],
10433 x_shape,
10434 dtype,
10435 );
10436 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10437 }
10438 Op::Clamp { min, max } => {
10439 // Subgradient: 1 where min <= x <= max, 0 elsewhere.
10440 // Expressed via (step(x - min) - step(x - max))
10441 // which is 1 in the interior (x > min and x <= max...
10442 // actually step(0) = 0, so the right end is a bit
10443 // tricky). For a reference implementation the
10444 // simplest approach is a dedicated "clamp backward"
10445 // indicator. We build it out of the existing ops:
10446 //
10447 // lower_ok = step(x - min) // 1 where x > min
10448 // upper_ok = step(max - x) // 1 where x < max
10449 // indicator = lower_ok * upper_ok
10450 // grad_x = upstream * indicator
10451 //
10452 // This underestimates the gradient on the exact
10453 // boundary by a measure-zero amount — standard.
10454 let x = inputs[0];
10455 let x_shape = node_shape(&graph_handle, x);
10456 let dtype = node_dtype(&graph_handle, x);
10457 let min_shifted = push_node(
10458 &graph_handle,
10459 Op::AddScalar(-min),
10460 vec![x],
10461 x_shape.clone(),
10462 dtype,
10463 );
10464 let lower_ok = push_node(
10465 &graph_handle,
10466 Op::Step,
10467 vec![min_shifted],
10468 x_shape.clone(),
10469 dtype,
10470 );
10471 let max_minus_x = push_node(
10472 &graph_handle,
10473 Op::MulScalar(-1.0),
10474 vec![x],
10475 x_shape.clone(),
10476 dtype,
10477 );
10478 let max_minus_x = push_node(
10479 &graph_handle,
10480 Op::AddScalar(max),
10481 vec![max_minus_x],
10482 x_shape.clone(),
10483 dtype,
10484 );
10485 let upper_ok = push_node(
10486 &graph_handle,
10487 Op::Step,
10488 vec![max_minus_x],
10489 x_shape.clone(),
10490 dtype,
10491 );
10492 let indicator = push_node(
10493 &graph_handle,
10494 Op::Mul,
10495 vec![lower_ok, upper_ok],
10496 x_shape.clone(),
10497 dtype,
10498 );
10499 let grad_x = push_node(
10500 &graph_handle,
10501 Op::Mul,
10502 vec![up_id, indicator],
10503 x_shape,
10504 dtype,
10505 );
10506 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10507 }
10508 Op::Maximum => {
10509 // y_i = max(a_i, b_i). Gradient flows to whichever
10510 // input was the max at that position:
10511 // mask_a = step(a - b) (1 where a > b, else 0)
10512 // mask_b = 1 - mask_a (approximately — at ties
10513 // gradient goes to b due to
10514 // step(0) = 0)
10515 // grad_a = upstream * mask_a
10516 // grad_b = upstream * mask_b
10517 let a = inputs[0];
10518 let b = inputs[1];
10519 let shape = node_shape(&graph_handle, a);
10520 let dtype = node_dtype(&graph_handle, a);
10521 let diff = push_node(&graph_handle, Op::Sub, vec![a, b], shape.clone(), dtype);
10522 let mask_a =
10523 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10524 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10525 let mask_b = push_node(
10526 &graph_handle,
10527 Op::Sub,
10528 vec![ones, mask_a],
10529 shape.clone(),
10530 dtype,
10531 );
10532 let grad_a = push_node(
10533 &graph_handle,
10534 Op::Mul,
10535 vec![up_id, mask_a],
10536 shape.clone(),
10537 dtype,
10538 );
10539 let grad_b =
10540 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10541 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10542 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10543 }
10544 Op::Minimum => {
10545 // Symmetric to Maximum. mask_a = step(b - a).
10546 let a = inputs[0];
10547 let b = inputs[1];
10548 let shape = node_shape(&graph_handle, a);
10549 let dtype = node_dtype(&graph_handle, a);
10550 let diff = push_node(&graph_handle, Op::Sub, vec![b, a], shape.clone(), dtype);
10551 let mask_a =
10552 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10553 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10554 let mask_b = push_node(
10555 &graph_handle,
10556 Op::Sub,
10557 vec![ones, mask_a],
10558 shape.clone(),
10559 dtype,
10560 );
10561 let grad_a = push_node(
10562 &graph_handle,
10563 Op::Mul,
10564 vec![up_id, mask_a],
10565 shape.clone(),
10566 dtype,
10567 );
10568 let grad_b =
10569 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10570 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10571 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10572 }
10573 Op::ScatterAdd { dim } => {
10574 // Forward: out = scatter_add(base, dim, indices, src).
10575 // Backward:
10576 // grad_base = upstream (pass-through)
10577 // grad_src = gather(upstream, dim, indices)
10578 let base = inputs[0];
10579 let idx = inputs[1];
10580 let src = inputs[2];
10581 let src_shape = node_shape(&graph_handle, src);
10582 let dtype = node_dtype(&graph_handle, src);
10583 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10584 let grad_src = push_node(
10585 &graph_handle,
10586 Op::Gather { dim },
10587 vec![up_id, idx],
10588 src_shape,
10589 dtype,
10590 );
10591 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10592 }
10593 Op::Copy { .. } => {
10594 // Forward: out = copy(x, target). Backward: the
10595 // gradient flows back to `x`'s original device, so
10596 // the reverse would be another Copy. The source
10597 // device is x's residency — we don't have the typed
10598 // "where was x?" here without tracking it, so we
10599 // fall back to the graph's placement hint on x (if
10600 // any) or trust the scheduler to re-insert the
10601 // correct copy during Phase 4. For Phase 3 we
10602 // assume inference-only use and pass upstream through.
10603 let x = inputs[0];
10604 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10605 }
10606 Op::Release => {
10607 // Release has no data output and no gradient to
10608 // propagate. Input is destroyed; any downstream
10609 // node that needs gradient through the original
10610 // tensor must get it from a sibling Copy's backward
10611 // path, not this one.
10612 }
10613 Op::Move { .. } => {
10614 // Move is Copy + destroy-source. For backward,
10615 // treat it the same as Copy — gradient flows back
10616 // through the move. The Phase 3-style assumption
10617 // still applies: we pass upstream through and rely
10618 // on the scheduler to re-insert the correct reverse
10619 // transfer in a training pass. For inference-only
10620 // use (the current case), this is a no-op.
10621 let x = inputs[0];
10622 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10623 }
10624 Op::WriteSlice { .. } => {
10625 // KV-cache writes are forward-only — the slab being
10626 // written *into* gets mutated in place, and the
10627 // source slab is read non-destructively. There is
10628 // no meaningful gradient through a mutating write
10629 // in fuel's tape-based autograd model. If a use
10630 // case needs differentiable scatter, the gradient
10631 // path is a `Gather` (read the slab back) plus an
10632 // accumulating `IndexAdd` on the destination —
10633 // express that explicitly in forward.
10634 panic!(
10635 "NodeHandle::backward: Op::WriteSlice is non-differentiable. \
10636 Use Gather + IndexAdd if you need a differentiable scatter."
10637 );
10638 }
10639 Op::WriteSliceRotating { .. } => {
10640 // Same forward-only contract as WriteSlice — the
10641 // ring buffer's bytes are mutated in place at a
10642 // dynamic offset. Sliding-window KV caches don't
10643 // need a gradient path; a differentiable scatter
10644 // is expressible as Gather + IndexAdd in forward.
10645 panic!(
10646 "NodeHandle::backward: Op::WriteSliceRotating is non-differentiable. \
10647 Use Gather + IndexAdd if you need a differentiable scatter."
10648 );
10649 }
10650 Op::WriteSliceDoff { .. } => {
10651 // Forward-only, like WriteSlice/WriteSliceRotating —
10652 // the KV-cache buffer is mutated in place at a
10653 // device-resident offset. Decode-time append; no
10654 // gradient path.
10655 panic!(
10656 "NodeHandle::backward: Op::WriteSliceDoff is non-differentiable. \
10657 Use Gather + IndexAdd if you need a differentiable scatter."
10658 );
10659 }
10660 // Phase 7.6 step 5 (2026-05-11): the legacy
10661 // `Op::Conv2D { stride, padding, groups }` backward
10662 // arm has been dropped together with the variant;
10663 // `Op::Fused(CONV2D, _)` below carries the full
10664 // backward logic (including the inner dW Conv2D
10665 // emission, which itself goes through Op::Fused).
10666 // Phase 7.6 step 4 (final): the builders for
10667 // ConvTranspose2D, FlashAttn, and PagedAttn now emit
10668 // `Op::Fused(<id>, _)`; these legacy backward arms
10669 // still fire for direct legacy-variant constructions
10670 // Phase 7.6 step 5 (final, 2026-05-11): the legacy
10671 // `Op::ConvTranspose2D` / `Op::FlashAttn` /
10672 // `Op::PagedAttn` / `Op::FusedLinear` backward arms
10673 // have all been dropped together with the variants;
10674 // `Op::Fused(<id>, _)` below panics for each id.
10675 Op::Fused(fid, params) => {
10676 // Per-id backward dispatch. Each migrated fused op
10677 // gets a branch here that emits the appropriate
10678 // gradient subgraph.
10679 if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM {
10680 // grad_x = softmax_last_dim_backward(y, upstream).
10681 // Phase 7.6 step 4 (backward-helper batch):
10682 // emits Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, _)
10683 // — the architecturally-correct registry form,
10684 // matching the BackwardKind::Fused edge on
10685 // SOFTMAX_LAST_DIM's entry.
10686 let x = inputs[0];
10687 let y_shape = node_shape(&graph_handle, id);
10688 let dtype = node_dtype(&graph_handle, id);
10689 let grad_x = push_node(
10690 &graph_handle,
10691 Op::Fused(
10692 crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
10693 crate::registry::FusedOpParams::SoftmaxLastDimBackward,
10694 ),
10695 vec![id, up_id],
10696 y_shape,
10697 dtype,
10698 );
10699 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10700 } else if fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM {
10701 // grad_x = layer_norm_last_dim_backward(x, upstream, eps).
10702 // Phase 7.6 step 4 (backward-helper batch): emits
10703 // registry form Op::Fused(LAYER_NORM_LAST_DIM_BACKWARD, _).
10704 let eps = match params {
10705 crate::registry::FusedOpParams::LayerNormLastDim { eps } => eps,
10706 _ => panic!(
10707 "NodeHandle::backward: Op::Fused(LAYER_NORM_LAST_DIM, _) \
10708 expected FusedOpParams::LayerNormLastDim, got {params:?}",
10709 ),
10710 };
10711 let x = inputs[0];
10712 let x_shape = node_shape(&graph_handle, x);
10713 let dtype = node_dtype(&graph_handle, x);
10714 let grad_x = push_node(
10715 &graph_handle,
10716 Op::Fused(
10717 crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
10718 crate::registry::FusedOpParams::LayerNormLastDimBackward { eps },
10719 ),
10720 vec![x, up_id],
10721 x_shape,
10722 dtype,
10723 );
10724 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10725 } else if fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM {
10726 // grad_x = rms_norm_last_dim_backward(x, upstream, eps).
10727 // Phase 7.6 step 4 (backward-helper batch): emits
10728 // registry form Op::Fused(RMS_NORM_LAST_DIM_BACKWARD, _).
10729 let eps = match params {
10730 crate::registry::FusedOpParams::RmsNormLastDim { eps } => eps,
10731 _ => panic!(
10732 "NodeHandle::backward: Op::Fused(RMS_NORM_LAST_DIM, _) \
10733 expected FusedOpParams::RmsNormLastDim, got {params:?}",
10734 ),
10735 };
10736 let x = inputs[0];
10737 let x_shape = node_shape(&graph_handle, x);
10738 let dtype = node_dtype(&graph_handle, x);
10739 let grad_x = push_node(
10740 &graph_handle,
10741 Op::Fused(
10742 crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
10743 crate::registry::FusedOpParams::RmsNormLastDimBackward { eps },
10744 ),
10745 vec![x, up_id],
10746 x_shape,
10747 dtype,
10748 );
10749 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10750 } else if fid == crate::registry::FusedOps::ROPE {
10751 // grad_x = rope(upstream, cos, -sin) — same
10752 // formula as the legacy Op::Rope arm above.
10753 // Emit the registry form for the backward
10754 // Rope node so the gradient subgraph routes
10755 // through the same Op::Fused dispatch as the
10756 // forward.
10757 let x = inputs[0];
10758 let cos = inputs[1];
10759 let sin = inputs[2];
10760 let x_shape = node_shape(&graph_handle, x);
10761 let sin_shape = node_shape(&graph_handle, sin);
10762 let dtype = node_dtype(&graph_handle, x);
10763 let neg_sin =
10764 push_node(&graph_handle, Op::Neg, vec![sin], sin_shape, dtype);
10765 let grad_x = push_node(
10766 &graph_handle,
10767 Op::Fused(
10768 crate::registry::FusedOps::ROPE,
10769 crate::registry::FusedOpParams::Rope,
10770 ),
10771 vec![up_id, cos, neg_sin],
10772 x_shape,
10773 dtype,
10774 );
10775 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10776 } else if fid == crate::registry::FusedOps::FUSED_LINEAR {
10777 // (a @ b) + bias backward — same three-grad
10778 // decomposition as the legacy Op::FusedLinear
10779 // arm above. We reuse MatMul backward (no
10780 // intermediate matmul output is cached, so the
10781 // grad computes from upstream + a, b directly).
10782 let a = inputs[0];
10783 let b = inputs[1];
10784 let bias = inputs[2];
10785 let a_shape = node_shape(&graph_handle, a);
10786 let b_shape = node_shape(&graph_handle, b);
10787 let bias_shape = node_shape(&graph_handle, bias);
10788 let dtype = node_dtype(&graph_handle, a);
10789 let b_t_shape = transposed_shape(&b_shape);
10790 let b_t =
10791 push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
10792 let grad_a = push_node(
10793 &graph_handle,
10794 Op::MatMul,
10795 vec![up_id, b_t],
10796 a_shape.clone(),
10797 dtype,
10798 );
10799 let a_t_shape = transposed_shape(&a_shape);
10800 let a_t =
10801 push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
10802 let grad_b =
10803 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
10804 let grad_bias = push_node(
10805 &graph_handle,
10806 Op::ReduceSumTo(bias_shape.clone()),
10807 vec![up_id],
10808 bias_shape,
10809 dtype,
10810 );
10811 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10812 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10813 accumulate_grad(&mut upstream, bias, grad_bias, &graph_handle);
10814 } else if fid == crate::registry::FusedOps::CONV2D {
10815 // Same backward formulation as the legacy
10816 // Op::Conv2D arm above. The inner Conv2D node
10817 // emitted for grad_w also goes through the
10818 // registry (Op::Fused(CONV2D, _)) so the
10819 // gradient subgraph routes consistently. The
10820 // ConvTranspose2D node stays as a primitive
10821 // variant until that op migrates in its own
10822 // step-4 commit.
10823 let (stride, padding, groups) = match params {
10824 crate::registry::FusedOpParams::Conv2D {
10825 stride,
10826 padding,
10827 groups,
10828 } => (stride, padding, groups),
10829 _ => panic!(
10830 "NodeHandle::backward: Op::Fused(CONV2D, _) \
10831 expected FusedOpParams::Conv2D, got {params:?}",
10832 ),
10833 };
10834 let x = inputs[0];
10835 let weight = inputs[1];
10836 let x_shape = node_shape(&graph_handle, x);
10837 let w_shape = node_shape(&graph_handle, weight);
10838 let dtype = node_dtype(&graph_handle, x);
10839
10840 // dX via transposed conv (see legacy arm for derivation).
10841 let x_dims = x_shape.dims();
10842 let w_dims = w_shape.dims();
10843 let dy_dims = node_shape(&graph_handle, id).dims().to_vec();
10844 let (sh, sw) = stride;
10845 let (ph, pw) = padding;
10846 let (kh, kw) = (w_dims[2], w_dims[3]);
10847 let (h_in, w_in) = (x_dims[2], x_dims[3]);
10848 let (dy_h, dy_w) = (dy_dims[2], dy_dims[3]);
10849 let base_h = (dy_h - 1) * sh + (kh - 1) + 1;
10850 let base_w = (dy_w - 1) * sw + (kw - 1) + 1;
10851 let want_h = h_in + 2 * ph;
10852 let want_w = w_in + 2 * pw;
10853 let out_pad_h = want_h.saturating_sub(base_h);
10854 let out_pad_w = want_w.saturating_sub(base_w);
10855 if groups != 1 {
10856 panic!(
10857 "NodeHandle::backward: Op::Fused(CONV2D) groups>1 \
10858 backward not yet implemented (got groups={groups}). \
10859 The stride/padding/groups=1 case is wired; grouped \
10860 backward needs a per-group weight reshape.",
10861 );
10862 }
10863 let perm_01 = vec![1usize, 0, 2, 3];
10864 // Phase 7.6 step 4 (final): emit registry form
10865 // for the inner dX node so the gradient subgraph
10866 // routes consistently through Op::Fused dispatch.
10867 let grad_x = push_node(
10868 &graph_handle,
10869 Op::Fused(
10870 crate::registry::FusedOps::CONV_TRANSPOSE2D,
10871 crate::registry::FusedOpParams::ConvTranspose2D {
10872 stride,
10873 padding,
10874 output_padding: (out_pad_h, out_pad_w),
10875 dilation: (1, 1),
10876 groups,
10877 },
10878 ),
10879 vec![up_id, weight],
10880 x_shape.clone(),
10881 dtype,
10882 );
10883 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10884
10885 // dW via correlation expressed as a conv2d.
10886 if sh != 1 || sw != 1 {
10887 panic!(
10888 "NodeHandle::backward: Op::Fused(CONV2D) stride>1 \
10889 backward not yet implemented (got stride={stride:?}). \
10890 Conv2D needs a `dilation` field to express this \
10891 without composing extra ops.",
10892 );
10893 }
10894 let x_swapped_shape = {
10895 let d = x_dims;
10896 Shape::from_dims(&[d[1], d[0], d[2], d[3]])
10897 };
10898 let x_swapped = push_node(
10899 &graph_handle,
10900 Op::Permute(perm_01.clone()),
10901 vec![x],
10902 x_swapped_shape,
10903 dtype,
10904 );
10905 let dy_swapped_shape =
10906 Shape::from_dims(&[dy_dims[1], dy_dims[0], dy_dims[2], dy_dims[3]]);
10907 let dy_swapped = push_node(
10908 &graph_handle,
10909 Op::Permute(perm_01.clone()),
10910 vec![up_id],
10911 dy_swapped_shape,
10912 dtype,
10913 );
10914 let conv_out_shape =
10915 Shape::from_dims(&[w_dims[1], w_dims[0], w_dims[2], w_dims[3]]);
10916 let grad_w_pre_transpose = push_node(
10917 &graph_handle,
10918 Op::Fused(
10919 crate::registry::FusedOps::CONV2D,
10920 crate::registry::FusedOpParams::Conv2D {
10921 stride: (1, 1),
10922 padding,
10923 groups: 1,
10924 },
10925 ),
10926 vec![x_swapped, dy_swapped],
10927 conv_out_shape,
10928 dtype,
10929 );
10930 let grad_w = push_node(
10931 &graph_handle,
10932 Op::Permute(perm_01),
10933 vec![grad_w_pre_transpose],
10934 w_shape,
10935 dtype,
10936 );
10937 accumulate_grad(&mut upstream, weight, grad_w, &graph_handle);
10938
10939 // Bias (if present): sum dY over N, H, W via
10940 // ReduceSumTo([1, Cout, 1, 1]) then reshape to
10941 // [Cout]. Same path as the legacy arm.
10942 if inputs.len() >= 3 {
10943 let bias = inputs[2];
10944 let bias_shape = node_shape(&graph_handle, bias);
10945 let cout_4d = Shape::from_dims(&[1, dy_dims[1], 1, 1]);
10946 let reduced = push_node(
10947 &graph_handle,
10948 Op::ReduceSumTo(cout_4d.clone()),
10949 vec![up_id],
10950 cout_4d,
10951 dtype,
10952 );
10953 let grad_b = push_node(
10954 &graph_handle,
10955 Op::Reshape(bias_shape.clone()),
10956 vec![reduced],
10957 bias_shape,
10958 dtype,
10959 );
10960 accumulate_grad(&mut upstream, bias, grad_b, &graph_handle);
10961 }
10962 } else if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD
10963 || fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD
10964 || fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
10965 || fid == crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD
10966 {
10967 // Higher-order gradients through backward
10968 // helpers panic.
10969 panic!(
10970 "backward: higher-order gradients through \
10971 softmax/layer_norm/rms_norm/reduce_max_to backward \
10972 helpers are not yet supported in the MVP."
10973 );
10974 } else if fid == crate::registry::FusedOps::CONV_TRANSPOSE2D {
10975 // Higher-order grad of the transposed conv
10976 // isn't needed for Conv2D's backward (which
10977 // only consumes the forward output). Adding
10978 // it requires the same dilation-as-stride
10979 // trick as Conv2D's dW. Punt until a real
10980 // consumer asks for it.
10981 panic!(
10982 "NodeHandle::backward: ConvTranspose2D does \
10983 not yet have its own gradient rule \
10984 (only used in the forward path of \
10985 Conv2D's backward).",
10986 );
10987 } else if fid == crate::registry::FusedOps::FLASH_ATTN {
10988 // Emit three backward nodes: dQ via
10989 // FLASH_ATTN_BACKWARD_Q, dK via _K, dV via _V.
10990 // Each takes (q, k, v, dO, [alibi]) and
10991 // recomputes the softmax state independently
10992 // in CPU's math-definition path. GPU kernels
10993 // (when they ship) can fuse the recompute.
10994 let q = inputs[0];
10995 let k = inputs[1];
10996 let v = inputs[2];
10997 let alibi = inputs.get(3).copied();
10998 let q_shape = node_shape(&graph_handle, q);
10999 let k_shape = node_shape(&graph_handle, k);
11000 let v_shape = node_shape(&graph_handle, v);
11001 let dtype = node_dtype(&graph_handle, q);
11002 let (scale, causal, wl, wr, sc) = match params {
11003 crate::registry::FusedOpParams::FlashAttn {
11004 softmax_scale,
11005 causal,
11006 window_size_left,
11007 window_size_right,
11008 softcap,
11009 // Backward over the static (full-K) flash
11010 // only; the runtime-k_len capacity form is
11011 // forward-only (decode). k_len is ignored
11012 // here.
11013 k_len: _,
11014 } => (
11015 softmax_scale,
11016 causal,
11017 window_size_left,
11018 window_size_right,
11019 softcap,
11020 ),
11021 other => panic!(
11022 "NodeHandle::backward: FlashAttn node carries \
11023 unexpected params {other:?}",
11024 ),
11025 };
11026 let bw_params = crate::registry::FusedOpParams::FlashAttnBackward {
11027 softmax_scale: scale,
11028 causal,
11029 window_size_left: wl,
11030 window_size_right: wr,
11031 softcap: sc,
11032 };
11033 let mut bw_inputs = vec![q, k, v, up_id];
11034 if let Some(a) = alibi {
11035 bw_inputs.push(a);
11036 }
11037 let grad_q = push_node(
11038 &graph_handle,
11039 Op::Fused(
11040 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_Q,
11041 bw_params.clone(),
11042 ),
11043 bw_inputs.clone(),
11044 q_shape,
11045 dtype,
11046 );
11047 let grad_k = push_node(
11048 &graph_handle,
11049 Op::Fused(
11050 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_K,
11051 bw_params.clone(),
11052 ),
11053 bw_inputs.clone(),
11054 k_shape,
11055 dtype,
11056 );
11057 let grad_v = push_node(
11058 &graph_handle,
11059 Op::Fused(crate::registry::FusedOps::FLASH_ATTN_BACKWARD_V, bw_params),
11060 bw_inputs,
11061 v_shape,
11062 dtype,
11063 );
11064 accumulate_grad(&mut upstream, q, grad_q, &graph_handle);
11065 accumulate_grad(&mut upstream, k, grad_k, &graph_handle);
11066 accumulate_grad(&mut upstream, v, grad_v, &graph_handle);
11067 } else if fid == crate::registry::FusedOps::PAGED_ATTN {
11068 // Paged attention is decode-side only by
11069 // construction (variable-length KV cache, no
11070 // training pass writes through it). No
11071 // gradient rule.
11072 panic!(
11073 "NodeHandle::backward: PagedAttn is \
11074 decode-only; no gradient rule exists.",
11075 );
11076 } else if fid == crate::registry::FusedOps::QMATMUL {
11077 // Quantized matmul: weights are frozen
11078 // bytes; activation gradient isn't
11079 // implemented today. Dequantize-then-matmul
11080 // is the workaround if differentiable
11081 // quantized inference is needed.
11082 panic!(
11083 "backward: QMatMul is not differentiable \
11084 (quantized weights are frozen). Use a \
11085 dequantize + standard matmul if you \
11086 need gradients through this input."
11087 );
11088 } else {
11089 panic!(
11090 "NodeHandle::backward: Op::Fused id {fid:?} has no \
11091 backward arm wired yet. This is a programming \
11092 bug — extend the match when the op migrates \
11093 to the registry.",
11094 );
11095 }
11096 }
11097 Op::Alloc { .. } => {
11098 // Op::Alloc is a source op (zero inputs) that
11099 // produces a fresh zero-init buffer. No upstream
11100 // gradient to propagate — the alloc's "input" is
11101 // the abstract notion of fresh memory, which has
11102 // no derivative. Mirrors Op::Const's treatment.
11103 // (Phase 3a of bridge-retirement; see
11104 // `WorkItemKind::Alloc` in fuel-storage.)
11105 }
11106 Op::ZeroFill => {
11107 // Op::ZeroFill writes deterministic constants
11108 // (zeros) to its input's bytes. The output is
11109 // a constant tensor; gradient w.r.t. it is
11110 // meaningless. Like Op::Const / Op::Alloc, no
11111 // gradient propagates back.
11112 }
11113 Op::ScatterIntoSlot { .. } => {
11114 // Item 4 IR-only scaffold — the backward graph
11115 // emits this op as the producer's gradient
11116 // assembler, but `ScatterIntoSlot` itself has no
11117 // backward (it's a structural op composing
11118 // already-differentiated slot gradients). No
11119 // gradient propagates back; matches the
11120 // Op::Const / Op::Alloc / Op::ZeroFill treatment.
11121 }
11122 Op::Branch { .. } => {
11123 // PR-A0 inert scaffold. `Op::Branch` is the
11124 // multi-path phi/merge node; it is never constructed
11125 // in A0, so this arm is unreachable today. When the
11126 // PR-A1 builders land, gradient flow through a Branch
11127 // routes via its arms (each an `inputs[i]` route exit)
11128 // and reconverges at `reconverge_at` — not through the
11129 // merge node itself. `backward` is infallible
11130 // (`-> GradMap`), so the no-panic inert handling is to
11131 // drop the gradient at the structural node, matching
11132 // the Op::Const / Op::ScatterIntoSlot treatment above.
11133 // The real per-arm routing lands with the builders.
11134 }
11135 Op::Scan { .. } => {
11136 // Defensive `panic!` — `backward() -> GradMap` is infallible
11137 // (no Err channel), so this is an internal-error guard in the
11138 // same infallible walk that already panics for QMatMul /
11139 // PagedAttn, NOT a recoverable typed error. It is unreachable
11140 // via the public builders: the C3 pre-pass
11141 // (lower_scans_for_backward) unrolls every Op::Scan to
11142 // primitives before the topo order is taken, and the builders
11143 // always emit the View consumers the pre-pass's remap +
11144 // never-hang guard lower away. Reaching here means the
11145 // pre-pass did not run (an internal bug).
11146 panic!(
11147 "NodeHandle::backward: Op::Scan reached the reverse walk un-lowered — \
11148 the C3 lower_scans_for_backward pre-pass did not run (internal bug)."
11149 );
11150 }
11151 Op::ScanPlaceholder { .. } => {
11152 // Inert body-hole leaf (no inputs) — never a real
11153 // differentiation target. Drop gradient like Op::Const /
11154 // Op::Iota; a live backward never reaches it (the body is
11155 // materialized by unroll_scan before any realize).
11156 }
11157 Op::View { slot } | Op::ViewOwned { slot } => {
11158 // Multi-output projection — item 4 backward
11159 // composition (Option C, 2026-06-01).
11160 //
11161 // Forward (Op::View): shares the producer's
11162 // bundled Storage Arc and exposes one slot's
11163 // typed window. Forward (Op::ViewOwned): memcpys
11164 // the slot's bytes into a fresh Storage.
11165 //
11166 // Backward: scatter the upstream gradient into
11167 // the slot's byte range of a fresh zero-bundle of
11168 // the producer's primary shape, then accumulate
11169 // that partial-bundle gradient as the producer's
11170 // input gradient. Multiple View consumers of the
11171 // same producer accumulate via the standard
11172 // sum-of-partials path:
11173 // bundle_grad =
11174 // ScatterIntoSlot{0}(0, g_y) +
11175 // ScatterIntoSlot{1}(0, g_state) + ...
11176 //
11177 // **Status (item 4)**: IR-level wiring only —
11178 // emits the scatter chain in the backward graph,
11179 // but no Op::ScatterIntoSlot kernel is registered.
11180 // The production multi-output producers
11181 // (SelectiveScan, SsdChunkScan) are
11182 // `BackwardKind::NotDifferentiable`, so autograd
11183 // panics at the producer before this scatter is
11184 // realized. When a differentiable multi-output op
11185 // materializes (Mamba training, FSCE loss+grad
11186 // fused), it lights up the ScatterIntoSlot CPU
11187 // kernel + tests alongside its own backward.
11188 let producer = inputs[0];
11189 let producer_shape = node_shape(&graph_handle, producer);
11190 let producer_dtype = node_dtype(&graph_handle, producer);
11191 let zero = build_filled_const(
11192 &graph_handle,
11193 producer_shape.clone(),
11194 producer_dtype,
11195 0.0,
11196 );
11197 let scattered = push_node(
11198 &graph_handle,
11199 Op::ScatterIntoSlot { slot },
11200 vec![zero, up_id],
11201 producer_shape,
11202 producer_dtype,
11203 );
11204 accumulate_grad(&mut upstream, producer, scattered, &graph_handle);
11205 }
11206 Op::ReluInplace => {
11207 // Same backward as Op::Relu — d(relu(x))/dx = step(x).
11208 // The view-aware `derive_ordering` (Phase 4a) pins
11209 // `Op::Step(x)` to run BEFORE Op::ReluInplace, so the
11210 // step kernel sees x's original bytes.
11211 let x = inputs[0];
11212 let x_shape = node_shape(&graph_handle, x);
11213 let dtype = node_dtype(&graph_handle, x);
11214 let step_x =
11215 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
11216 let grad_x =
11217 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
11218 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11219 }
11220 Op::SiluInplace => {
11221 // Same backward as Op::Silu — grad_x = upstream * (s + y*(1-s))
11222 // where s = sigmoid(x) and y = silu(x) = this in-place node's
11223 // output. The post-mutation bytes at `id` ARE silu(x) (the
11224 // in-place op runs after the Sigmoid(x) read because of the
11225 // alias-aware ordering pass). `Op::Sigmoid(x)` reads x's
11226 // pre-mutation bytes; `Op::Mul(id, ...)` reads post-mutation
11227 // bytes — both correct.
11228 let x = inputs[0];
11229 let x_shape = node_shape(&graph_handle, x);
11230 let dtype = node_dtype(&graph_handle, x);
11231 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
11232 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
11233 let one_minus_s = push_node(
11234 &graph_handle,
11235 Op::Sub,
11236 vec![ones, s],
11237 x_shape.clone(),
11238 dtype,
11239 );
11240 let y_times_1ms = push_node(
11241 &graph_handle,
11242 Op::Mul,
11243 vec![id, one_minus_s],
11244 x_shape.clone(),
11245 dtype,
11246 );
11247 let inner = push_node(
11248 &graph_handle,
11249 Op::Add,
11250 vec![s, y_times_1ms],
11251 x_shape.clone(),
11252 dtype,
11253 );
11254 let grad_x =
11255 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
11256 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11257 }
11258 Op::TanhInplace => {
11259 // Same backward as Op::Tanh — grad_x = upstream * (1 - y²)
11260 // where y = tanh(x) = this in-place node's output. `Op::Sqr(id)`
11261 // reads post-mutation bytes (= tanh(x) by definition of the
11262 // in-place op); no need to reference x at all.
11263 let x = inputs[0];
11264 let y_shape = node_shape(&graph_handle, id);
11265 let dtype = node_dtype(&graph_handle, id);
11266 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
11267 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11268 let one_minus_sq = push_node(
11269 &graph_handle,
11270 Op::Sub,
11271 vec![ones, y_sq],
11272 y_shape.clone(),
11273 dtype,
11274 );
11275 let grad_x = push_node(
11276 &graph_handle,
11277 Op::Mul,
11278 vec![up_id, one_minus_sq],
11279 y_shape,
11280 dtype,
11281 );
11282 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11283 }
11284 Op::SigmoidInplace => {
11285 // Same backward as Op::Sigmoid — grad_x = upstream * y * (1 - y)
11286 // where y = sigmoid(x) = this in-place node's output.
11287 let x = inputs[0];
11288 let y_shape = node_shape(&graph_handle, id);
11289 let dtype = node_dtype(&graph_handle, id);
11290 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11291 let one_minus_y = push_node(
11292 &graph_handle,
11293 Op::Sub,
11294 vec![ones, id],
11295 y_shape.clone(),
11296 dtype,
11297 );
11298 let y_times_1my = push_node(
11299 &graph_handle,
11300 Op::Mul,
11301 vec![id, one_minus_y],
11302 y_shape.clone(),
11303 dtype,
11304 );
11305 let grad_x = push_node(
11306 &graph_handle,
11307 Op::Mul,
11308 vec![up_id, y_times_1my],
11309 y_shape,
11310 dtype,
11311 );
11312 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11313 }
11314 Op::GeluTanhInplace => {
11315 // Mirrors Op::GeluTanh's panic — the tanh-approximation
11316 // gradient is non-trivial and not yet implemented
11317 // for the non-inplace variant either. Users who
11318 // need a differentiable GELU should use SiluInplace
11319 // (which has a proper backward).
11320 panic!(
11321 "backward: GeluTanhInplace gradient is not yet supported. \
11322 Use SiluInplace for differentiable training; GeluTanhInplace \
11323 is currently inference-only (mirrors Op::GeluTanh's status)."
11324 );
11325 }
11326 Op::NegInplace => {
11327 // Same backward as Op::Neg — grad_x = -upstream. No
11328 // dependency on x or y; Phase 4a ordering not needed.
11329 let x = inputs[0];
11330 let x_shape = node_shape(&graph_handle, x);
11331 let dtype = node_dtype(&graph_handle, x);
11332 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
11333 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11334 }
11335 Op::AbsInplace => {
11336 // Same backward as Op::Abs — grad_x = sign(x) * upstream.
11337 // `Op::Sign(x)` reads x's pre-mutation bytes (Phase 4a
11338 // pins the in-place op after the Sign read).
11339 let x = inputs[0];
11340 let x_shape = node_shape(&graph_handle, x);
11341 let dtype = node_dtype(&graph_handle, x);
11342 let sign_x =
11343 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
11344 let grad_x =
11345 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
11346 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11347 }
11348 Op::SqrInplace => {
11349 // Same backward as Op::Sqr — grad_x = 2x * upstream,
11350 // expressed as `x + x` to avoid a scalar broadcast.
11351 // `x + x` reads pre-mutation bytes (Phase 4a).
11352 let x = inputs[0];
11353 let x_shape = node_shape(&graph_handle, x);
11354 let dtype = node_dtype(&graph_handle, x);
11355 let two_x =
11356 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
11357 let grad_x =
11358 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
11359 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11360 }
11361 Op::SqrtInplace => {
11362 // Same backward as Op::Sqrt — y = √x, grad_x = upstream/(2y).
11363 // Reads only the forward output `id`, which is post-mutation =
11364 // √x by definition; no pre-mutation x access needed.
11365 let x = inputs[0];
11366 let x_shape = node_shape(&graph_handle, x);
11367 let dtype = node_dtype(&graph_handle, x);
11368 let two_y =
11369 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
11370 let grad_x =
11371 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
11372 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11373 }
11374 Op::RsqrtInplace => {
11375 // Same backward as Op::Rsqrt — y = x^(-1/2),
11376 // grad_x = -0.5 * upstream * y³. Reads forward output (id)
11377 // only — post-mutation = y by definition.
11378 let x = inputs[0];
11379 let x_shape = node_shape(&graph_handle, x);
11380 let dtype = node_dtype(&graph_handle, x);
11381 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11382 let y_cu = push_node(
11383 &graph_handle,
11384 Op::Mul,
11385 vec![id, y_sq],
11386 x_shape.clone(),
11387 dtype,
11388 );
11389 let scaled = push_node(
11390 &graph_handle,
11391 Op::MulScalar(-0.5),
11392 vec![y_cu],
11393 x_shape.clone(),
11394 dtype,
11395 );
11396 let grad_x =
11397 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11398 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11399 }
11400 Op::RecipInplace => {
11401 // Same backward as Op::Recip — y = 1/x, grad_x = -upstream * y².
11402 // Reads forward output (id) only — post-mutation = 1/x.
11403 let x = inputs[0];
11404 let x_shape = node_shape(&graph_handle, x);
11405 let dtype = node_dtype(&graph_handle, x);
11406 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11407 let up_y_sq = push_node(
11408 &graph_handle,
11409 Op::Mul,
11410 vec![up_id, y_sq],
11411 x_shape.clone(),
11412 dtype,
11413 );
11414 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
11415 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11416 }
11417 Op::ExpInplace => {
11418 // Same backward as Op::Exp — d(exp(x))/dx = exp(x) = y = id.
11419 // grad_x = upstream * y. Reads forward output (id) only.
11420 let x = inputs[0];
11421 let out_shape = node_shape(&graph_handle, id);
11422 let dtype = node_dtype(&graph_handle, id);
11423 let grad_x =
11424 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
11425 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11426 }
11427 Op::LogInplace => {
11428 // Same backward as Op::Log — grad_x = upstream / x.
11429 // `Op::Div(up, x)` reads pre-mutation bytes of x (Phase 4a).
11430 let x = inputs[0];
11431 let x_shape = node_shape(&graph_handle, x);
11432 let dtype = node_dtype(&graph_handle, x);
11433 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
11434 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11435 }
11436 Op::SinInplace => {
11437 // Same backward as Op::Sin — grad_x = upstream * cos(x).
11438 // `Op::Cos(x)` reads pre-mutation x via Phase 4a ordering.
11439 let x = inputs[0];
11440 let x_shape = node_shape(&graph_handle, x);
11441 let dtype = node_dtype(&graph_handle, x);
11442 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
11443 let grad_x =
11444 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
11445 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11446 }
11447 Op::CosInplace => {
11448 // Same backward as Op::Cos — grad_x = -(upstream * sin(x)).
11449 let x = inputs[0];
11450 let x_shape = node_shape(&graph_handle, x);
11451 let dtype = node_dtype(&graph_handle, x);
11452 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
11453 let up_sin = push_node(
11454 &graph_handle,
11455 Op::Mul,
11456 vec![up_id, sin_x],
11457 x_shape.clone(),
11458 dtype,
11459 );
11460 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
11461 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11462 }
11463 Op::SignInplace | Op::FloorInplace | Op::CeilInplace | Op::RoundInplace => {
11464 // Same backward as Op::{Sign, Floor, Ceil, Round} —
11465 // derivative is 0 almost everywhere; drop gradient
11466 // (no accumulation, mirroring Op::Step's pattern).
11467 }
11468 Op::ErfInplace => {
11469 // Same backward as Op::Erf — grad_x = upstream * (2/√π) * exp(-x²).
11470 // `Op::Sqr(x)` reads pre-mutation x via Phase 4a ordering.
11471 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
11472 let x = inputs[0];
11473 let x_shape = node_shape(&graph_handle, x);
11474 let dtype = node_dtype(&graph_handle, x);
11475 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11476 let neg_x_sq =
11477 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
11478 let exp_neg = push_node(
11479 &graph_handle,
11480 Op::Exp,
11481 vec![neg_x_sq],
11482 x_shape.clone(),
11483 dtype,
11484 );
11485 let scaled = push_node(
11486 &graph_handle,
11487 Op::MulScalar(TWO_OVER_SQRT_PI),
11488 vec![exp_neg],
11489 x_shape.clone(),
11490 dtype,
11491 );
11492 let grad_x =
11493 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11494 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11495 }
11496 Op::ClampInplace { min, max } => {
11497 // Same backward as Op::Clamp — indicator is 1 where
11498 // min ≤ x ≤ max, 0 elsewhere. Reads pre-mutation x via
11499 // Phase 4a ordering.
11500 let x = inputs[0];
11501 let x_shape = node_shape(&graph_handle, x);
11502 let dtype = node_dtype(&graph_handle, x);
11503 let min_shifted = push_node(
11504 &graph_handle,
11505 Op::AddScalar(-min),
11506 vec![x],
11507 x_shape.clone(),
11508 dtype,
11509 );
11510 let lower_ok = push_node(
11511 &graph_handle,
11512 Op::Step,
11513 vec![min_shifted],
11514 x_shape.clone(),
11515 dtype,
11516 );
11517 let neg_x = push_node(
11518 &graph_handle,
11519 Op::MulScalar(-1.0),
11520 vec![x],
11521 x_shape.clone(),
11522 dtype,
11523 );
11524 let max_minus_x = push_node(
11525 &graph_handle,
11526 Op::AddScalar(max),
11527 vec![neg_x],
11528 x_shape.clone(),
11529 dtype,
11530 );
11531 let upper_ok = push_node(
11532 &graph_handle,
11533 Op::Step,
11534 vec![max_minus_x],
11535 x_shape.clone(),
11536 dtype,
11537 );
11538 let indicator = push_node(
11539 &graph_handle,
11540 Op::Mul,
11541 vec![lower_ok, upper_ok],
11542 x_shape.clone(),
11543 dtype,
11544 );
11545 let grad_x = push_node(
11546 &graph_handle,
11547 Op::Mul,
11548 vec![up_id, indicator],
11549 x_shape,
11550 dtype,
11551 );
11552 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11553 }
11554 Op::PowIInplace(n) => {
11555 // Same backward as Op::PowI — single fused
11556 // POWI_BACKWARD node `(x, upstream) → exp · x^(exp-1) ·
11557 // upstream`. Reads pre-mutation x via Phase 4a ordering.
11558 let x = inputs[0];
11559 let x_shape = node_shape(&graph_handle, x);
11560 let dtype = node_dtype(&graph_handle, x);
11561 let grad_x = push_node(
11562 &graph_handle,
11563 Op::Fused(
11564 crate::registry::FusedOps::POWI_BACKWARD,
11565 crate::registry::FusedOpParams::PowIBackward { exp: n },
11566 ),
11567 vec![x, up_id],
11568 x_shape,
11569 dtype,
11570 );
11571 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11572 }
11573 Op::GeluInplace => {
11574 // Same backward as Op::Gelu — exact-GELU derivative
11575 // is Φ(x) + x·φ(x). Both halves read pre-mutation x via
11576 // Phase 4a ordering. Identical 12-node chain to Op::Gelu.
11577 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
11578 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
11579 let x = inputs[0];
11580 let x_shape = node_shape(&graph_handle, x);
11581 let dtype = node_dtype(&graph_handle, x);
11582 let x_over_sqrt2 = push_node(
11583 &graph_handle,
11584 Op::MulScalar(INV_SQRT_2),
11585 vec![x],
11586 x_shape.clone(),
11587 dtype,
11588 );
11589 let erf_arg = push_node(
11590 &graph_handle,
11591 Op::Erf,
11592 vec![x_over_sqrt2],
11593 x_shape.clone(),
11594 dtype,
11595 );
11596 let plus_one = push_node(
11597 &graph_handle,
11598 Op::AddScalar(1.0),
11599 vec![erf_arg],
11600 x_shape.clone(),
11601 dtype,
11602 );
11603 let cdf_term = push_node(
11604 &graph_handle,
11605 Op::MulScalar(0.5),
11606 vec![plus_one],
11607 x_shape.clone(),
11608 dtype,
11609 );
11610 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11611 let half_x_sq = push_node(
11612 &graph_handle,
11613 Op::MulScalar(0.5),
11614 vec![x_sq],
11615 x_shape.clone(),
11616 dtype,
11617 );
11618 let neg_half = push_node(
11619 &graph_handle,
11620 Op::Neg,
11621 vec![half_x_sq],
11622 x_shape.clone(),
11623 dtype,
11624 );
11625 let exp_term = push_node(
11626 &graph_handle,
11627 Op::Exp,
11628 vec![neg_half],
11629 x_shape.clone(),
11630 dtype,
11631 );
11632 let phi = push_node(
11633 &graph_handle,
11634 Op::MulScalar(INV_SQRT_2PI),
11635 vec![exp_term],
11636 x_shape.clone(),
11637 dtype,
11638 );
11639 let pdf_term =
11640 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
11641 let d_gelu = push_node(
11642 &graph_handle,
11643 Op::Add,
11644 vec![cdf_term, pdf_term],
11645 x_shape.clone(),
11646 dtype,
11647 );
11648 let grad_x =
11649 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
11650 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11651 }
11652 }
11653 }
11654
11655 GradMap {
11656 graph: graph_handle,
11657 forward_to_grad: upstream,
11658 }
11659 }
11660}
11661
11662/// Map from forward-graph node IDs to the IDs of their accumulated
11663/// backward-graph gradient nodes, returned by [`NodeHandle::backward`].
11664///
11665/// All gradient nodes live on the same graph as the forward nodes. Getting
11666/// a gradient by calling [`GradMap::get`] returns a new [`NodeHandle`] handle
11667/// pointing at the gradient node so callers can realize it, plug it into
11668/// further computation, or back-propagate through it again.
11669pub struct GradMap {
11670 graph: SharedGraph,
11671 forward_to_grad: HashMap<NodeId, NodeId>,
11672}
11673
11674impl GradMap {
11675 /// Get the gradient tensor for a forward tensor from the same graph.
11676 ///
11677 /// Returns `None` if the forward tensor was not reachable from the
11678 /// root passed to `backward` (i.e. not part of the computation being
11679 /// differentiated).
11680 ///
11681 /// # Panics
11682 ///
11683 /// Panics if any operand belongs to a different [`Graph`] than the one this
11684 /// builder is building into. Operand identity is graph-scoped and checked by
11685 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
11686 /// deliberate and replaces the hang a cross-graph handle used to produce.
11687 /// Build every operand from one graph, or use a `Result`-returning entry
11688 /// point where one exists.
11689 pub fn get(&self, forward: &NodeHandle) -> Option<NodeHandle> {
11690 assert!(
11691 Arc::ptr_eq(&self.graph, &forward.graph),
11692 "GradMap::get: tensor is from a different graph",
11693 );
11694 let &grad_id = self.forward_to_grad.get(&forward.id)?;
11695 Some(NodeHandle {
11696 graph: self.graph.clone(),
11697 id: grad_id,
11698 })
11699 }
11700
11701 /// Number of forward nodes that have a recorded gradient.
11702 pub fn len(&self) -> usize {
11703 self.forward_to_grad.len()
11704 }
11705
11706 /// Whether this map has no gradients (e.g. a backward over a lone const).
11707 pub fn is_empty(&self) -> bool {
11708 self.forward_to_grad.is_empty()
11709 }
11710}
11711
11712// -------- internal helpers shared by the backward pass --------------------
11713
11714/// The generic decompose-backward hook (Op::Scan Phase 2, C3): before the
11715/// reverse walk takes its topo order, lower every reachable `Op::Scan` to
11716/// `bound` primitives and decompose the two SSM `Op::Fused` recipes into their
11717/// `Op::Scan` form, rewiring consumers so the walk sees only differentiable
11718/// primitives. BPTT differentiates the static-`bound` unroll (the runtime
11719/// early-exit predicate is a forward-only optimization, ignored here — spec C3
11720/// static-horizon note). Operates in place on the shared graph (a `backward()`
11721/// caller is a training step that wants the unrolled activations anyway).
11722/// Returns the (possibly remapped) root NodeId to walk from.
11723fn lower_scans_for_backward(graph: &SharedGraph, root: NodeId) -> NodeId {
11724 use std::collections::HashMap;
11725 let mut root = root;
11726 // helper: apply a remap to every consumer's inputs + the root, in place.
11727 fn apply_remap(graph: &SharedGraph, remap: &HashMap<NodeId, NodeId>, root: &mut NodeId) {
11728 if remap.is_empty() {
11729 return;
11730 }
11731 let mut g = graph.write().unwrap();
11732 let n = g.len();
11733 for nid in 0..n {
11734 let ilen = g.node(NodeId(nid)).inputs.len();
11735 for i in 0..ilen {
11736 let cur = g.node(NodeId(nid)).inputs[i];
11737 if let Some(&new) = remap.get(&cur) {
11738 g.rewrite_input(NodeId(nid), cur, new);
11739 }
11740 }
11741 }
11742 if let Some(&new) = remap.get(root) {
11743 *root = new;
11744 }
11745 }
11746
11747 // --- Pass 1: decompose SSM Op::Fused(SELECTIVE_SCAN|SSD_CHUNK_SCAN) into Op::Scan.
11748 {
11749 let ssm = [
11750 crate::registry::FusedOps::SELECTIVE_SCAN,
11751 crate::registry::FusedOps::SSD_CHUNK_SCAN,
11752 ];
11753 let targets: Vec<(
11754 NodeId,
11755 crate::registry::FusedOpId,
11756 crate::registry::FusedOpParams,
11757 )> = {
11758 let g = graph.read().unwrap();
11759 crate::topo_order(&g, root)
11760 .into_iter()
11761 .filter_map(|id| match &g.node(id).op {
11762 Op::Fused(fid, params) if ssm.contains(fid) => Some((id, *fid, params.clone())),
11763 _ => None,
11764 })
11765 .collect()
11766 };
11767 let mut remap = HashMap::new();
11768 for (id, fid, params) in targets {
11769 if let Some(entry) = crate::registry::default_registry().entry(fid) {
11770 let y = {
11771 let mut g = graph.write().unwrap();
11772 (entry.decompose)(&mut g, id, ¶ms)
11773 };
11774 if y != id {
11775 remap.insert(id, y);
11776 // Collapse the fused node's slot-0 View consumers DIRECTLY to
11777 // the decompose output. Slot 0 is the primary value (the
11778 // multi-output authoring contract: Node.shape == slot-0
11779 // shape), and the SSM decompose re-presents its primary AS
11780 // slot 0, so `View{0}(y) == y`. Without this collapse the
11781 // outer View{0} survives into the reverse walk and emits an
11782 // `Op::ScatterIntoSlot` (which has no CPU realize kernel),
11783 // so realizing the gradient would fail. Slot-1 (last_state)
11784 // consumers keep their `View{1}(y)` re-projection via the
11785 // default input rewrite (remap[id] = y) and are not
11786 // differentiated on this path.
11787 let g = graph.read().unwrap();
11788 for nid in 0..g.len() {
11789 let node = g.node(NodeId(nid));
11790 if let Op::View { slot: 0 } | Op::ViewOwned { slot: 0 } = node.op
11791 && node.inputs.first() == Some(&id)
11792 {
11793 remap.insert(NodeId(nid), y);
11794 }
11795 }
11796 }
11797 }
11798 }
11799 apply_remap(graph, &remap, &mut root);
11800 }
11801
11802 // --- Pass 2: unroll every reachable Op::Scan to `bound` primitives.
11803 loop {
11804 let scans: Vec<(NodeId, usize, ScanEmit)> = {
11805 let g = graph.read().unwrap();
11806 crate::topo_order(&g, root)
11807 .into_iter()
11808 .filter_map(|id| match &g.node(id).op {
11809 Op::Scan { bound, emit, .. } => Some((id, *bound, *emit)),
11810 _ => None,
11811 })
11812 .collect()
11813 };
11814 if scans.is_empty() {
11815 break;
11816 }
11817 let mut remap = HashMap::new();
11818 for (scan_id, bound, emit) in scans {
11819 let (a, b) = {
11820 let mut g = graph.write().unwrap();
11821 match crate::scan::unroll_scan(&mut g, scan_id, bound) {
11822 Ok(pair) => pair,
11823 Err(_) => continue, // malformed scan: leave it; the C4 guard describes it.
11824 }
11825 };
11826 // Normalize to (slot 0 = stacked_ys, slots 1.. = final carries).
11827 //
11828 // GAP-303: `unroll_scan` now returns (selected, complementary) as
11829 // VECS. The `ys` side is always exactly one node; the carry side is
11830 // `n_carries` wide. At `n_carries == 1` this is byte-for-byte the old
11831 // behaviour -- one ys, one carry, slot 1 the only carry slot.
11832 let (ys_v, carries) = match emit {
11833 ScanEmit::All => (a, b),
11834 ScanEmit::Final => (b, a),
11835 };
11836 let Some(&slot0) = ys_v.first() else {
11837 continue; // malformed: no stacked ys; the C4 guard describes it.
11838 };
11839 // Remap the scan's View{slot}/ViewOwned{slot} consumers to the unroll outputs.
11840 let g = graph.read().unwrap();
11841 for nid in 0..g.len() {
11842 let node = g.node(NodeId(nid));
11843 if let Op::View { slot } | Op::ViewOwned { slot } = node.op
11844 && node.inputs.first() == Some(&scan_id)
11845 {
11846 // ⚠️ Slot 0 is `ys`; slot k>=1 is carry k-1. The old form was
11847 // `if slot == 0 { slot0 } else { slot1 }`, which folded EVERY
11848 // slot above 0 onto the single carry -- a fifth site of the
11849 // 2-slot assumption. Out-of-range slots are LEFT UNMAPPED for
11850 // the C4 guard rather than indexed (never-panic).
11851 let target = if slot == 0 {
11852 Some(slot0)
11853 } else {
11854 carries.get(slot as usize - 1).copied()
11855 };
11856 if let Some(t) = target {
11857 remap.insert(NodeId(nid), t);
11858 }
11859 }
11860 }
11861 }
11862 // Defensive never-hang guard: if a full pass lowered no scan to a
11863 // consumer remap (e.g. a malformed scan that unroll rejects, or a raw
11864 // scan producer with no View consumers), stop rather than re-scanning
11865 // the same unchanged graph forever. Any residual Op::Scan then reaches
11866 // the C4 defensive `panic!` guard (backward is infallible, so it cannot
11867 // return an error) — an internal-bug signal, never an infinite loop.
11868 if remap.is_empty() {
11869 break;
11870 }
11871 apply_remap(graph, &remap, &mut root);
11872 // Unrolled graphs contain no Op::Scan, so a well-formed graph terminates
11873 // in <= 2 iterations (the loop re-scans in case a decomposed body itself
11874 // contained a scan; the current SSM decompose does not).
11875 }
11876 root
11877}
11878
11879/// Read a node's shape without holding the borrow past the call site.
11880fn node_shape(graph: &SharedGraph, id: NodeId) -> Shape {
11881 graph.read().unwrap().node(id).shape.clone()
11882}
11883
11884/// Read a node's dtype without holding the borrow past the call site.
11885fn node_dtype(graph: &SharedGraph, id: NodeId) -> DType {
11886 graph.read().unwrap().node(id).dtype
11887}
11888
11889/// Shape with its last two dims swapped. Used by MatMul's backward rule
11890/// to construct transpose-node output shapes for any rank ≥ 2.
11891fn transposed_shape(shape: &Shape) -> Shape {
11892 let d = shape.dims();
11893 assert!(
11894 d.len() >= 2,
11895 "transposed_shape: expected rank ≥ 2, got {d:?}",
11896 );
11897 let rank = d.len();
11898 let mut out: Vec<usize> = d.to_vec();
11899 out.swap(rank - 2, rank - 1);
11900 Shape::from_dims(&out)
11901}
11902
11903/// Given a full tensor shape and a dim that was reduced away, produce the
11904/// keepdim shape — i.e. the full shape with size 1 at `dim`. Used by
11905/// axis-reduction backward rules to reshape the reduced upstream back to
11906/// a shape that broadcasts against the original input.
11907fn reshape_to_keepdim(full_dims: &[usize], dim: usize) -> Shape {
11908 assert!(
11909 dim < full_dims.len(),
11910 "reshape_to_keepdim: dim {dim} out of bounds for {full_dims:?}",
11911 );
11912 let mut out: Vec<usize> = full_dims.to_vec();
11913 out[dim] = 1;
11914 Shape::from_dims(&out)
11915}
11916
11917/// Validate that `src` can be broadcast to `dst` using NumPy rules:
11918/// right-align, pad the shorter shape with 1s on the left, and for each
11919/// aligned dimension the src size must equal the dst size or be 1.
11920fn check_broadcast_compatible(src: &[usize], dst: &[usize]) {
11921 assert!(
11922 src.len() <= dst.len(),
11923 "broadcast_to: source rank {} exceeds target rank {}",
11924 src.len(),
11925 dst.len(),
11926 );
11927 let pad = dst.len() - src.len();
11928 for (i, &s) in src.iter().enumerate() {
11929 let d = dst[pad + i];
11930 assert!(
11931 s == d || s == 1,
11932 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11933 pad + i,
11934 );
11935 }
11936}
11937
11938/// Result-returning sibling of [`check_broadcast_compatible`].
11939fn try_check_broadcast_compatible(
11940 src: &[usize],
11941 dst: &[usize],
11942) -> std::result::Result<(), fuel_ir::Error> {
11943 if src.len() > dst.len() {
11944 return Err(fuel_ir::Error::Msg(format!(
11945 "broadcast_to: source rank {} exceeds target rank {}",
11946 src.len(),
11947 dst.len(),
11948 ))
11949 .bt());
11950 }
11951 let pad = dst.len() - src.len();
11952 for (i, &s) in src.iter().enumerate() {
11953 let d = dst[pad + i];
11954 if s != d && s != 1 {
11955 return Err(fuel_ir::Error::Msg(format!(
11956 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11957 pad + i,
11958 ))
11959 .bt());
11960 }
11961 }
11962 Ok(())
11963}
11964
11965/// Compute the NumPy broadcast shape of two input shapes. Right-align,
11966/// pad the shorter with leading 1s, and take the element-wise max at
11967/// each position. Panics if the shapes are incompatible (neither can
11968/// expand to match the other at some dim).
11969fn compute_broadcast_shape(a: &[usize], b: &[usize]) -> Vec<usize> {
11970 let n = a.len().max(b.len());
11971 let a_pad = n - a.len();
11972 let b_pad = n - b.len();
11973 let mut out = Vec::with_capacity(n);
11974 for i in 0..n {
11975 let ai = if i < a_pad { 1 } else { a[i - a_pad] };
11976 let bi = if i < b_pad { 1 } else { b[i - b_pad] };
11977 let oi = if ai == bi {
11978 ai
11979 } else if ai == 1 {
11980 bi
11981 } else if bi == 1 {
11982 ai
11983 } else {
11984 panic!(
11985 "compute_broadcast_shape: incompatible shapes {a:?} vs {b:?} at axis {i}: {ai} vs {bi}",
11986 );
11987 };
11988 out.push(oi);
11989 }
11990 out
11991}
11992
11993/// Push a node to the graph and return its ID. Used by backward to append
11994/// gradient-computing nodes without going through the public builders,
11995/// which would re-validate shapes the backward pass has already derived.
11996fn push_node(
11997 graph: &SharedGraph,
11998 op: Op,
11999 inputs: Vec<NodeId>,
12000 shape: Shape,
12001 dtype: DType,
12002) -> NodeId {
12003 graph.write().unwrap().push(Node {
12004 op,
12005 inputs,
12006 shape,
12007 dtype,
12008 })
12009}
12010
12011/// Build a ones tensor of the given shape and dtype as a `Const` node.
12012/// Used to seed the initial upstream gradient at the root of the backward
12013/// pass (`dL/dL = 1`).
12014fn build_ones(graph: &SharedGraph, shape: Shape, dtype: DType) -> NodeId {
12015 build_filled_const(graph, shape, dtype, 1.0)
12016}
12017
12018/// Build a constant tensor of the given shape and dtype filled with
12019/// `value` (expressed as `f64` and converted to the target dtype). Used
12020/// by backward rules that need a scalar-valued broadcast, for example
12021/// `MeanAll`'s `1/n` factor expressed as "divide by an n-filled const."
12022///
12023/// Build RoPE cos/sin tables for a given `(base, start_pos, seq,
12024/// head_dim)`. Each returned `Vec<f32>` has shape `[seq, head_dim]`
12025/// (row-major) in the half-split layout [`NodeHandle::rope_with_tables`]
12026/// expects: positions `[:, :half]` and `[:, half:]` hold the same
12027/// value for the same `(p, i)`, so a single elementwise multiply with
12028/// `self` does the right thing alongside `rotate_half(self) * sin`.
12029///
12030/// Exposed as a free function so callers can share the tables across
12031/// many RoPE applications (e.g. every attention layer in a transformer
12032/// forward pass).
12033pub fn build_rope_tables(
12034 base: f64,
12035 start_pos: usize,
12036 seq: usize,
12037 head_dim: usize,
12038) -> (Vec<f32>, Vec<f32>) {
12039 assert!(
12040 head_dim.is_multiple_of(2),
12041 "build_rope_tables: head_dim {head_dim} must be even",
12042 );
12043 let half = head_dim / 2;
12044 let inv_freq: Vec<f64> = (0..half)
12045 .map(|i| base.powf(-2.0 * (i as f64) / (head_dim as f64)))
12046 .collect();
12047 build_rope_tables_with_inv_freq(&inv_freq, start_pos, seq, head_dim)
12048}
12049
12050/// [`build_rope_tables`] with the inverse frequencies supplied directly rather
12051/// than derived from a single `base`.
12052///
12053/// Every RoPE variant Fuel supports differs from the default in **exactly** this
12054/// vector: LLaMA-3.1's long-context scaling is a per-dimension transform of the
12055/// same `head_dim / 2` values, and the position loop below is bit-identical
12056/// either way. Splitting the frequency choice out is what lets a scaled model
12057/// reuse the whole decode path — the KV-cache forward, the held-graph persistent
12058/// forward, and their per-token rebinds — instead of needing a parallel copy of
12059/// each.
12060///
12061/// `inv_freq.len()` must be `head_dim / 2`.
12062pub fn build_rope_tables_with_inv_freq(
12063 inv_freq: &[f64],
12064 start_pos: usize,
12065 seq: usize,
12066 head_dim: usize,
12067) -> (Vec<f32>, Vec<f32>) {
12068 assert!(
12069 head_dim.is_multiple_of(2),
12070 "build_rope_tables_with_inv_freq: head_dim {head_dim} must be even",
12071 );
12072 let half = head_dim / 2;
12073 assert_eq!(
12074 inv_freq.len(),
12075 half,
12076 "build_rope_tables_with_inv_freq: inv_freq len {} != head_dim/2 {half}",
12077 inv_freq.len(),
12078 );
12079 let mut cos_data = vec![0.0_f32; seq * head_dim];
12080 let mut sin_data = vec![0.0_f32; seq * head_dim];
12081 for p in 0..seq {
12082 let pos = (start_pos + p) as f64;
12083 for (i, &freq) in inv_freq.iter().enumerate() {
12084 let theta = pos * freq;
12085 let c = theta.cos() as f32;
12086 let s = theta.sin() as f32;
12087 cos_data[p * head_dim + i] = c;
12088 cos_data[p * head_dim + i + half] = c;
12089 sin_data[p * head_dim + i] = s;
12090 sin_data[p * head_dim + i + half] = s;
12091 }
12092 }
12093 (cos_data, sin_data)
12094}
12095
12096/// Only float dtypes are supported here — integer/index tensors never
12097/// appear as gradients, so a `U32` call indicates a bug in a backward
12098/// rule rather than a missing feature.
12099///
12100/// Phase 7.5 G2: gradient consts are slot-populating Op::Const
12101/// nodes. Device is picked from any existing slot (the forward pass
12102/// always populated at least one slot-bearing leaf by the time
12103/// backward runs). For a CPU-rooted graph the device's
12104/// `storage_from_host_buffer_owned_dyn` is a zero-copy wrap; for
12105/// GPU-rooted, an H2D upload (matching today's eval_const path on
12106/// first realize).
12107fn build_filled_const(graph: &SharedGraph, shape: Shape, dtype: DType, value: f64) -> NodeId {
12108 let n = shape.elem_count();
12109 let buf = match dtype {
12110 DType::F32 => fuel_ir::HostBuffer::F32(vec![value as f32; n]),
12111 DType::F64 => fuel_ir::HostBuffer::F64(vec![value; n]),
12112 DType::BF16 => fuel_ir::HostBuffer::BF16(vec![bf16::from_f64(value); n]),
12113 DType::F16 => fuel_ir::HostBuffer::F16(vec![f16::from_f64(value); n]),
12114 other => panic!(
12115 "backward: build_filled_const: unsupported dtype {other:?} \
12116 (gradients are always floats — this would indicate a bug in \
12117 a backward rule that tried to differentiate through an \
12118 integer tensor)",
12119 ),
12120 };
12121 let device = pick_device_from_graph(graph);
12122 let backend_storage = device
12123 .storage_from_host_buffer_owned_dyn(buf)
12124 .expect("build_filled_const: storage_from_host_buffer_owned_dyn failed");
12125 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
12126 let id = push_node(graph, Op::Const, vec![], shape, dtype);
12127 graph.write().unwrap().set_storage(id, storage_arc);
12128 id
12129}
12130
12131/// G2 helper: walk the graph for any populated slot and return its
12132/// device. Used by gradient builders that don't have an explicit
12133/// device parameter — the graph always has at least one slot-bearing
12134/// Const leaf by the time backward() runs (the forward pass's inputs
12135/// are slot-rooted Const leaves), so this can be relied on.
12136fn pick_device_from_graph(graph: &SharedGraph) -> Arc<dyn fuel_backend_contract::DynBackendDevice> {
12137 let g = graph.read().unwrap();
12138 for i in 0..g.len() {
12139 if let Some(slot_arc) = g.storage_for(NodeId(i)) {
12140 return slot_arc.read().unwrap().device();
12141 }
12142 }
12143 panic!(
12144 "build_filled_const: graph has no populated storage slots; backward \
12145 requires at least one slot-bearing Const leaf to pick a gradient \
12146 device from. Was the forward pass built with G2-migrated \
12147 constructors (from_f32/etc. with explicit &Device)?"
12148 )
12149}
12150
12151/// Accumulate a new gradient contribution into the upstream map.
12152///
12153/// If `forward_id` already has an upstream gradient, emit an `Add` node to
12154/// sum the two contributions. If not, record the new one as-is. This is
12155/// the multi-variable chain rule in its operational form: when a forward
12156/// node has multiple downstream consumers, the gradients from each must
12157/// be summed.
12158fn accumulate_grad(
12159 upstream: &mut HashMap<NodeId, NodeId>,
12160 forward_id: NodeId,
12161 new_grad_id: NodeId,
12162 graph: &SharedGraph,
12163) {
12164 match upstream.get(&forward_id).copied() {
12165 None => {
12166 upstream.insert(forward_id, new_grad_id);
12167 }
12168 Some(existing_id) => {
12169 let shape = node_shape(graph, forward_id);
12170 let dtype = node_dtype(graph, forward_id);
12171 let combined = push_node(graph, Op::Add, vec![existing_id, new_grad_id], shape, dtype);
12172 upstream.insert(forward_id, combined);
12173 }
12174 }
12175}
12176
12177#[cfg(test)]
12178mod tests {
12179 use super::*;
12180
12181 /// Phase 7.5 G2: tests need a real device to allocate slot
12182 /// storage through the new constructor API. `cpu_dev()` returns a
12183 /// stable singleton CpuBackendDevice handle so every call site can
12184 /// just pass `cpu_dev()` without per-test boilerplate.
12185 fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
12186 static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
12187 std::sync::OnceLock::new();
12188 D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
12189 }
12190
12191 /// `Tensor::awq_matmul`'s public builder end-to-end: a well-formed call
12192 /// produces a `Fused(AWQ_MATMUL, ..)` node with the right output
12193 /// shape/dtype. The decompose MATH is tested at the registry level
12194 /// (`registry::awq_matmul::tests`); this just confirms the builder's
12195 /// own validation + node construction work from the public API.
12196 #[test]
12197 fn awq_matmul_builder_produces_expected_node() {
12198 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12199 .unwrap();
12200 let qweight = act
12201 .const_u32_like(vec![0u32; 8], Shape::from_dims(&[8, 1]))
12202 .unwrap();
12203 let qzeros = act
12204 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12205 .unwrap();
12206 let scales = act
12207 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12208 .unwrap();
12209 let out = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12210 assert_eq!(out.shape().dims(), &[2, 8]);
12211 assert_eq!(out.dtype(), DType::F32);
12212 assert!(matches!(
12213 out.graph.read().unwrap().node(out.id).op,
12214 Op::Fused(id, _) if id == crate::registry::FusedOps::AWQ_MATMUL
12215 ));
12216 }
12217
12218 /// Born-red: a non-U32 `qweight` must panic with a clear message, not
12219 /// silently misinterpret bytes.
12220 #[test]
12221 #[should_panic(expected = "qweight must be U32")]
12222 fn awq_matmul_builder_panics_on_wrong_qweight_dtype() {
12223 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12224 .unwrap();
12225 let qweight = act
12226 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[8, 1]))
12227 .unwrap();
12228 let qzeros = act
12229 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12230 .unwrap();
12231 let scales = act
12232 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12233 .unwrap();
12234 let _ = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12235 }
12236
12237 #[test]
12238 fn builders_agree_with_primitive_shape() {
12239 // No-drift guard (Convergence A, Task 6): every routed builder's output
12240 // shape/dtype must equal primitive_shape's answer for the same Op. If a
12241 // builder's inline math ever diverged from primitive_shape, this fails.
12242 let x = NodeHandle::from_f32(
12243 vec![0.0_f32; 2 * 3 * 4],
12244 Shape::from_dims(&[2, 3, 4]),
12245 cpu_dev(),
12246 )
12247 .unwrap();
12248 let checks: Vec<(NodeHandle, Op)> = vec![
12249 (
12250 x.slice(1, 0, 2),
12251 Op::Slice {
12252 dim: 1,
12253 start: 0,
12254 len: 2,
12255 },
12256 ),
12257 (x.mean_dim(2), Op::MeanDim(2)),
12258 (
12259 x.try_permute(&[2, 0, 1]).unwrap(),
12260 Op::Permute(vec![2, 0, 1]),
12261 ),
12262 (x.cast(DType::F16), Op::Cast(DType::F16)),
12263 ];
12264 for (t, op) in checks {
12265 let (ps_shape, ps_dtype) =
12266 crate::shape::primitive_shape(&op, &[x.shape()], &[x.dtype()]).unwrap();
12267 assert_eq!(t.shape(), ps_shape, "shape drift for {op:?}");
12268 assert_eq!(t.dtype(), ps_dtype, "dtype drift for {op:?}");
12269 }
12270 }
12271
12272 #[test]
12273 fn destructive_input_release_is_some_zero() {
12274 assert_eq!(Op::Release.destructive_input(), Some(0));
12275 }
12276
12277 /// Phase 7.5 storage-unification B2: target_backend side-table
12278 /// is sparse — empty by default, set explicitly per node.
12279 #[test]
12280 fn target_backend_side_table_starts_empty() {
12281 let mut g = Graph::new();
12282 let id = g.push(Node {
12283 op: Op::Const,
12284 inputs: vec![],
12285 shape: Shape::from_dims(&[1]),
12286 dtype: DType::F32,
12287 });
12288 assert_eq!(g.target_backend(id), None);
12289 assert_eq!(g.target_backend_count(), 0);
12290 }
12291
12292 /// set_target_backend then read returns the same value.
12293 #[test]
12294 fn target_backend_set_and_read() {
12295 let mut g = Graph::new();
12296 let id = g.push(Node {
12297 op: Op::Const,
12298 inputs: vec![],
12299 shape: Shape::from_dims(&[1]),
12300 dtype: DType::F32,
12301 });
12302 g.set_target_backend(id, BackendId::Cpu);
12303 assert_eq!(g.target_backend(id), Some(BackendId::Cpu));
12304 assert_eq!(g.target_backend_count(), 1);
12305 }
12306
12307 /// set_target_backend overwrites prior value.
12308 #[test]
12309 fn target_backend_overwrite() {
12310 let mut g = Graph::new();
12311 let id = g.push(Node {
12312 op: Op::Const,
12313 inputs: vec![],
12314 shape: Shape::from_dims(&[1]),
12315 dtype: DType::F32,
12316 });
12317 g.set_target_backend(id, BackendId::Cpu);
12318 g.set_target_backend(id, BackendId::Cuda);
12319 assert_eq!(g.target_backend(id), Some(BackendId::Cuda));
12320 assert_eq!(g.target_backend_count(), 1);
12321 }
12322
12323 /// Layouts side-table: default fallback returns
12324 /// `Layout::contiguous(node.shape)` for any node without an
12325 /// explicit entry.
12326 #[test]
12327 fn layout_default_is_contiguous_over_node_shape() {
12328 let mut g = Graph::new();
12329 let id = g.push(Node {
12330 op: Op::Const,
12331 inputs: vec![],
12332 shape: Shape::from_dims(&[2, 3]),
12333 dtype: DType::F32,
12334 });
12335 assert!(!g.has_explicit_layout(id));
12336 assert_eq!(g.explicit_layout_count(), 0);
12337 let l = g.layout(id);
12338 assert_eq!(l.shape().dims(), &[2, 3]);
12339 assert!(l.is_contiguous());
12340 assert_eq!(l.start_offset(), 0);
12341 }
12342
12343 /// set_layout records a strided Layout (e.g. for a transpose
12344 /// view). Subsequent reads return the explicit entry.
12345 #[test]
12346 fn layout_explicit_strided_is_remembered() {
12347 let mut g = Graph::new();
12348 let id = g.push(Node {
12349 op: Op::Transpose,
12350 inputs: vec![],
12351 shape: Shape::from_dims(&[3, 2]),
12352 dtype: DType::F32,
12353 });
12354 // Strided view: shape stays [3, 2] (the post-transpose view),
12355 // strides are [1, 3] (row-of-output is column-of-source).
12356 let l = Layout::new(
12357 Shape::from_dims(&[3, 2]),
12358 fuel_ir::StrideVec::from_slice(&[1_isize, 3]),
12359 0,
12360 );
12361 g.set_layout(id, l);
12362 assert!(g.has_explicit_layout(id));
12363 assert_eq!(g.explicit_layout_count(), 1);
12364 assert_eq!(g.layout(id).stride(), &[1, 3]);
12365 assert!(!g.layout(id).is_contiguous());
12366 }
12367
12368 /// set_layout twice with different layouts overwrites.
12369 #[test]
12370 fn layout_set_overwrites() {
12371 use fuel_ir::StrideVec;
12372 let mut g = Graph::new();
12373 let id = g.push(Node {
12374 op: Op::Transpose,
12375 inputs: vec![],
12376 shape: Shape::from_dims(&[2]),
12377 dtype: DType::F32,
12378 });
12379 g.set_layout(id, Layout::contiguous(Shape::from_dims(&[2])));
12380 g.set_layout(
12381 id,
12382 Layout::new(Shape::from_dims(&[2]), StrideVec::from_slice(&[3_isize]), 1),
12383 );
12384 assert_eq!(g.layout(id).start_offset(), 1);
12385 assert_eq!(g.explicit_layout_count(), 1);
12386 }
12387
12388 /// Phase 7.5 work item G — empty-map invariants. End-to-end
12389 /// tests of the storage map (with real `Storage` values) live in
12390 /// fuel-core's `tensor::node_handle_tests`, since constructing a
12391 /// real `Storage` requires a `DynBackendStorage` implementation
12392 /// from a backend crate, and fuel-graph deliberately depends only
12393 /// on fuel-core-types.
12394 #[test]
12395 fn graph_storage_map_starts_empty() {
12396 let g = Graph::new();
12397 assert_eq!(g.storage_len(), 0);
12398 assert!(!g.has_storage(NodeId(0)));
12399 assert!(g.storage_for(NodeId(0)).is_none());
12400 }
12401
12402 #[test]
12403 fn conv2d_builder_emits_conv2d_node_with_right_shape() {
12404 // k=3 s=1 p=1 keeps H and W.
12405 let x = NodeHandle::from_f32(
12406 vec![0.0_f32; 2 * 4 * 4],
12407 Shape::from_dims(&[1, 2, 4, 4]),
12408 cpu_dev(),
12409 )
12410 .unwrap();
12411 let w = x
12412 .const_f32_like(
12413 vec![0.0_f32; 3 * 2 * 3 * 3],
12414 Shape::from_dims(&[3, 2, 3, 3]),
12415 )
12416 .unwrap();
12417 let b = x
12418 .const_f32_like(vec![0.0_f32; 3], Shape::from_dims(&[3]))
12419 .unwrap();
12420 let y = x.conv2d(&w, Some(&b), (1, 1), (1, 1), 1);
12421 assert_eq!(y.shape().dims(), &[1, 3, 4, 4]);
12422 }
12423
12424 #[test]
12425 fn conv2d_builder_stride_and_no_padding() {
12426 // k=3 s=2 p=0 on H=W=8 gives (8-3)/2+1 = 3.
12427 let x = NodeHandle::from_f32(
12428 vec![0.0_f32; 2 * 8 * 8],
12429 Shape::from_dims(&[1, 2, 8, 8]),
12430 cpu_dev(),
12431 )
12432 .unwrap();
12433 let w = x
12434 .const_f32_like(
12435 vec![0.0_f32; 4 * 2 * 3 * 3],
12436 Shape::from_dims(&[4, 2, 3, 3]),
12437 )
12438 .unwrap();
12439 let y = x.conv2d(&w, None, (2, 2), (0, 0), 1);
12440 assert_eq!(y.shape().dims(), &[1, 4, 3, 3]);
12441 }
12442
12443 #[test]
12444 fn conv2d_builder_depthwise_groups() {
12445 // groups=Cin=Cout=4 is the depthwise case. Weight per channel is [Cin/groups=1, kH, kW].
12446 let x = NodeHandle::from_f32(
12447 vec![0.0_f32; 4 * 4 * 4],
12448 Shape::from_dims(&[1, 4, 4, 4]),
12449 cpu_dev(),
12450 )
12451 .unwrap();
12452 let w = x
12453 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 1, 3, 3]))
12454 .unwrap();
12455 let y = x.conv2d(&w, None, (1, 1), (1, 1), 4);
12456 assert_eq!(y.shape().dims(), &[1, 4, 4, 4]);
12457 }
12458
12459 #[test]
12460 fn conv_transpose2d_builder_emits_node_with_right_shape() {
12461 // Hin=4, Kh=3, s=2, pad=1, out_pad=1 → Hout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12462 let x = NodeHandle::from_f32(
12463 vec![0.0_f32; 2 * 4 * 4],
12464 Shape::from_dims(&[1, 2, 4, 4]),
12465 cpu_dev(),
12466 )
12467 .unwrap();
12468 let w = x
12469 .const_f32_like(
12470 vec![0.0_f32; 2 * 3 * 3 * 3],
12471 Shape::from_dims(&[2, 3, 3, 3]),
12472 )
12473 .unwrap();
12474 let y = x.conv_transpose2d(&w, (2, 2), (1, 1), (1, 1), (1, 1), 1);
12475 assert_eq!(y.shape().dims(), &[1, 3, 8, 8]);
12476 }
12477
12478 #[test]
12479 fn conv_transpose1d_builder_shape_stride_2_pad_1() {
12480 // Lin=4, K=3, s=2, pad=1, out_pad=1, dil=1
12481 // Lout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12482 let x = NodeHandle::from_f32(
12483 vec![0.0_f32; 2 * 4],
12484 Shape::from_dims(&[1, 2, 4]),
12485 cpu_dev(),
12486 )
12487 .unwrap();
12488 let w = x
12489 .const_f32_like(vec![0.0_f32; 2 * 3 * 3], Shape::from_dims(&[2, 3, 3]))
12490 .unwrap();
12491 let y = x.conv_transpose1d(&w, 2, 1, 1, 1, 1);
12492 assert_eq!(y.shape().dims(), &[1, 3, 8]);
12493 }
12494
12495 #[test]
12496 fn conv_transpose1d_builder_shape_stride_4_no_pad() {
12497 // Lin=2, K=4, s=4, pad=0, out_pad=0, dil=1
12498 // Lout = (2-1)*4 + (4-1) + 0 + 1 - 0 = 8.
12499 let x = NodeHandle::from_f32(vec![0.0_f32; 2], Shape::from_dims(&[1, 1, 2]), cpu_dev())
12500 .unwrap();
12501 let w = x
12502 .const_f32_like(vec![0.0_f32; 4], Shape::from_dims(&[1, 1, 4]))
12503 .unwrap();
12504 let y = x.conv_transpose1d(&w, 4, 0, 0, 1, 1);
12505 assert_eq!(y.shape().dims(), &[1, 1, 8]);
12506 }
12507
12508 #[test]
12509 fn conv_transpose1d_builder_with_groups() {
12510 // groups=2: input Cin=4 splits into 2 groups of 2; weight
12511 // Cin=4 first dim matches input; Cout/group=3 → total Cout=6.
12512 // Lin=3, K=3, s=1, pad=0, out_pad=0, dil=1 → Lout = (3-1)*1 + 2 + 0 + 1 = 5.
12513 let x = NodeHandle::from_f32(
12514 vec![0.0_f32; 4 * 3],
12515 Shape::from_dims(&[1, 4, 3]),
12516 cpu_dev(),
12517 )
12518 .unwrap();
12519 let w = x
12520 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 3, 3]))
12521 .unwrap();
12522 let y = x.conv_transpose1d(&w, 1, 0, 0, 1, 2);
12523 assert_eq!(y.shape().dims(), &[1, 6, 5]);
12524 }
12525
12526 #[test]
12527 fn conv2d_backward_grads_have_input_shapes() {
12528 // Forward Y = conv2d(X, W) with stride=1, pad=1, groups=1 keeps H,W.
12529 // Backward should produce dX with X's shape and dW with W's shape.
12530 let x = NodeHandle::from_f32(
12531 (0..(2 * 4 * 4))
12532 .map(|i| (i as f32) * 0.05 - 0.5)
12533 .collect::<Vec<f32>>(),
12534 Shape::from_dims(&[1, 2, 4, 4]),
12535 cpu_dev(),
12536 )
12537 .unwrap();
12538 let w = x
12539 .const_f32_like(
12540 (0..(3 * 2 * 3 * 3))
12541 .map(|i| (i as f32) * 0.07 - 0.4)
12542 .collect::<Vec<f32>>(),
12543 Shape::from_dims(&[3, 2, 3, 3]),
12544 )
12545 .unwrap();
12546 let y = x.conv2d(&w, None, (1, 1), (1, 1), 1);
12547 let scalar_out = y.sum_all();
12548 let grads = scalar_out.backward();
12549 let dx = grads.get(&x).expect("conv2d backward produced no dX");
12550 let dw = grads.get(&w).expect("conv2d backward produced no dW");
12551 assert_eq!(dx.shape().dims(), x.shape().dims());
12552 assert_eq!(dw.shape().dims(), w.shape().dims());
12553 }
12554
12555 #[test]
12556 fn destructive_input_move_is_some_zero() {
12557 assert_eq!(
12558 Op::Move {
12559 target: DeviceLocation::Cpu
12560 }
12561 .destructive_input(),
12562 Some(0)
12563 );
12564 }
12565
12566 #[test]
12567 fn destructive_input_non_destructive_ops_are_none() {
12568 assert_eq!(
12569 Op::Copy {
12570 target: DeviceLocation::Cpu
12571 }
12572 .destructive_input(),
12573 None
12574 );
12575 assert_eq!(Op::Add.destructive_input(), None);
12576 assert_eq!(Op::Mul.destructive_input(), None);
12577 assert_eq!(Op::MatMul.destructive_input(), None);
12578 assert_eq!(Op::Relu.destructive_input(), None);
12579 }
12580
12581 #[test]
12582 fn move_to_device_emits_op_move_node() {
12583 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12584 let moved = a.move_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12585 let g = moved.graph().read().unwrap();
12586 match &g.node(moved.id()).op {
12587 Op::Move { target } => {
12588 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12589 }
12590 other => panic!("expected Op::Move, got {other:?}"),
12591 }
12592 assert_eq!(g.node(moved.id()).inputs, vec![a.id()]);
12593 // Output has the input's shape (residency changes, data doesn't).
12594 assert_eq!(g.node(moved.id()).shape.elem_count(), 2);
12595 }
12596
12597 #[test]
12598 fn copy_to_device_emits_op_copy_node() {
12599 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12600 let b = a.copy_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12601 let g = b.graph().read().unwrap();
12602 match &g.node(b.id()).op {
12603 Op::Copy { target } => {
12604 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12605 }
12606 other => panic!("expected Op::Copy, got {other:?}"),
12607 }
12608 // Source stays resident: the original `a` node still in the graph
12609 // and is the input of the Copy node.
12610 assert_eq!(g.node(b.id()).inputs, vec![a.id()]);
12611 }
12612
12613 #[test]
12614 fn release_builder_emits_op_release_node() {
12615 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12616 let released = a.release();
12617 let g = released.graph().read().unwrap();
12618 assert!(matches!(g.node(released.id()).op, Op::Release));
12619 assert_eq!(g.node(released.id()).inputs, vec![a.id()]);
12620 // Output is a zero-element marker.
12621 assert_eq!(g.node(released.id()).shape.elem_count(), 0);
12622 }
12623
12624 #[test]
12625 fn placement_is_none_by_default() {
12626 let a =
12627 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12628 assert_eq!(a.placement(), None);
12629 }
12630
12631 #[test]
12632 fn on_device_sets_placement_hint() {
12633 let a =
12634 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12635 let b = a
12636 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12637 .unwrap();
12638 // Only tag the Add node; the const leaves remain unplaced.
12639 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
12640 assert_eq!(c.placement(), Some(DeviceLocation::Vulkan { gpu_id: 0 }));
12641 assert_eq!(a.placement(), None);
12642 assert_eq!(b.placement(), None);
12643 }
12644
12645 #[test]
12646 fn placement_survives_graph_re_reads() {
12647 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12648 let tagged = a.clone().on_device(DeviceLocation::Cpu);
12649 // Re-read from a fresh borrow — round-trips through the side-table.
12650 assert_eq!(
12651 tagged.graph().read().unwrap().placement(tagged.id()),
12652 Some(DeviceLocation::Cpu)
12653 );
12654 }
12655
12656 #[test]
12657 fn from_f32_creates_single_const_node() {
12658 let a =
12659 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12660 assert_eq!(a.graph().read().unwrap().len(), 1);
12661 assert_eq!(a.shape().dims(), &[3]);
12662 assert_eq!(a.dtype(), DType::F32);
12663 let node = a.graph().read().unwrap().node(a.id()).clone();
12664 // Phase 7.5 G2: factory now emits Op::Const + slot.
12665 assert!(matches!(node.op, Op::Const));
12666 assert!(node.inputs.is_empty());
12667 // The slot is populated with F32 storage.
12668 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12669 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
12670 }
12671
12672 #[test]
12673 fn add_appends_a_node_and_tracks_inputs() {
12674 let a =
12675 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12676 let b = a
12677 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12678 .unwrap();
12679 let c = a.add(&b);
12680 assert_eq!(c.graph().read().unwrap().len(), 3); // const, const, add
12681 let node = c.graph().read().unwrap().node(c.id()).clone();
12682 assert!(matches!(node.op, Op::Add));
12683 assert_eq!(node.inputs.len(), 2);
12684 assert_eq!(node.inputs[0], a.id());
12685 assert_eq!(node.inputs[1], b.id());
12686 assert_eq!(c.shape().dims(), &[3]);
12687 }
12688
12689 #[test]
12690 fn chained_ops_all_share_one_graph() {
12691 let a =
12692 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12693 let b = a
12694 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12695 .unwrap();
12696 let c = a.add(&b).mul(&a).sqr().relu();
12697 assert_eq!(c.graph().read().unwrap().len(), 6); // 2 consts + add + mul + sqr + relu
12698 assert_eq!(c.shape().dims(), &[3]);
12699 }
12700
12701 #[test]
12702 fn matmul_validates_shapes_and_produces_correct_output_shape() {
12703 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12704 let b = a
12705 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
12706 .unwrap();
12707 let c = a.matmul(&b);
12708 assert_eq!(c.shape().dims(), &[2, 4]);
12709 }
12710
12711 #[test]
12712 #[should_panic(expected = "shape mismatch")]
12713 fn add_panics_on_shape_mismatch() {
12714 let a =
12715 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12716 let b = a
12717 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12718 .unwrap();
12719 let _ = a.add(&b);
12720 }
12721
12722 #[test]
12723 #[should_panic(expected = "inner dim mismatch")]
12724 fn matmul_panics_on_inner_dim_mismatch() {
12725 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12726 let b = a
12727 .const_f32_like(vec![1.0; 8], Shape::from_dims(&[4, 2]))
12728 .unwrap();
12729 let _ = a.matmul(&b);
12730 }
12731
12732 #[test]
12733 #[should_panic(expected = "must live on the same graph")]
12734 fn cross_graph_op_is_rejected() {
12735 let a =
12736 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12737 let b =
12738 NodeHandle::from_f32(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12739 let _ = a.add(&b);
12740 }
12741
12742 // ----- graph identity + graph-scoped construction -----
12743 //
12744 // Two changes land together: (1) every Graph carries a monotonic GraphId so
12745 // an affinity failure can name WHICH graphs rather than only that they
12746 // differ; (2) constructors accept an existing graph, so a consumer never has
12747 // to discover `const_*_like` to build a second tensor.
12748
12749 #[test]
12750 fn each_new_graph_gets_a_distinct_id() {
12751 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12752 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12753 assert_ne!(a.graph_id(), b.graph_id());
12754 }
12755
12756 #[test]
12757 fn same_graph_tensors_share_one_id() {
12758 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12759 let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
12760 assert_eq!(a.graph_id(), b.graph_id());
12761 }
12762
12763 #[test]
12764 fn affinity_panic_names_both_graph_ids() {
12765 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12766 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12767 let (ia, ib) = (a.graph_id(), b.graph_id());
12768 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| a.add(&b)))
12769 .expect_err("cross-graph add must panic");
12770 let text = err
12771 .downcast_ref::<String>()
12772 .cloned()
12773 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
12774 .expect("panic payload is a string");
12775 assert!(
12776 text.contains(&format!("#{ia}")) && text.contains(&format!("#{ib}")),
12777 "affinity panic must name BOTH graph ids so the caller can see it made two; got: {text}",
12778 );
12779 }
12780
12781 #[test]
12782 fn from_f32_on_builds_into_the_given_graph() {
12783 let root =
12784 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12785 let w = NodeHandle::from_f32_on(
12786 root.graph(),
12787 vec![4.0, 5.0, 6.0],
12788 Shape::from_dims(&[3]),
12789 cpu_dev(),
12790 )
12791 .unwrap();
12792 assert_eq!(root.graph_id(), w.graph_id());
12793 assert!(Arc::ptr_eq(root.graph(), w.graph()));
12794 }
12795
12796 #[test]
12797 fn graph_scoped_construction_composes_without_an_anchor() {
12798 // The program that could not previously be written: build two tensors
12799 // and combine them, without discovering `const_*_like`.
12800 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12801 let a = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev())
12802 .unwrap();
12803 let b = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[3, 2]), cpu_dev())
12804 .unwrap();
12805 let y = a.matmul(&b);
12806 assert_eq!(y.shape().dims(), &[2, 2]);
12807 assert_eq!(y.graph_id(), a.graph_id());
12808 }
12809
12810 #[test]
12811 fn graph_scoped_constructors_cover_every_dtype() {
12812 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12813 let s = Shape::from_dims(&[1]);
12814 let f32t = NodeHandle::from_f32_on(&g, vec![1.0f32], s.clone(), cpu_dev()).unwrap();
12815 let f64t = NodeHandle::from_f64_on(&g, vec![1.0f64], s.clone(), cpu_dev()).unwrap();
12816 let bf16t =
12817 NodeHandle::from_bf16_on(&g, vec![half::bf16::from_f32(1.0)], s.clone(), cpu_dev())
12818 .unwrap();
12819 let f16t =
12820 NodeHandle::from_f16_on(&g, vec![half::f16::from_f32(1.0)], s.clone(), cpu_dev())
12821 .unwrap();
12822 let u32t = NodeHandle::from_u32_on(&g, vec![1u32], s, cpu_dev()).unwrap();
12823 for t in [&f64t, &bf16t, &f16t, &u32t] {
12824 assert_eq!(
12825 t.graph_id(),
12826 f32t.graph_id(),
12827 "all must share the given graph"
12828 );
12829 }
12830 assert_eq!(f64t.dtype(), DType::F64);
12831 assert_eq!(bf16t.dtype(), DType::BF16);
12832 assert_eq!(f16t.dtype(), DType::F16);
12833 assert_eq!(u32t.dtype(), DType::U32);
12834 }
12835
12836 // ----- multi-dtype graph builders -----
12837
12838 #[test]
12839 fn from_f64_tags_node_with_f64_dtype() {
12840 let a =
12841 NodeHandle::from_f64(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12842 assert_eq!(a.dtype(), DType::F64);
12843 let node = a.graph().read().unwrap().node(a.id()).clone();
12844 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
12845 assert!(matches!(node.op, Op::Const));
12846 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12847 assert_eq!(slot.read().unwrap().dtype(), DType::F64);
12848 }
12849
12850 #[test]
12851 fn from_bf16_tags_node_with_bf16_dtype() {
12852 let a = NodeHandle::from_bf16(
12853 vec![bf16::from_f32(1.0), bf16::from_f32(2.0)],
12854 Shape::from_dims(&[2]),
12855 cpu_dev(),
12856 )
12857 .unwrap();
12858 assert_eq!(a.dtype(), DType::BF16);
12859 let node = a.graph().read().unwrap().node(a.id()).clone();
12860 assert!(matches!(node.op, Op::Const));
12861 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12862 assert_eq!(slot.read().unwrap().dtype(), DType::BF16);
12863 }
12864
12865 #[test]
12866 fn from_f16_tags_node_with_f16_dtype() {
12867 let a = NodeHandle::from_f16(
12868 vec![f16::from_f32(1.0), f16::from_f32(2.0)],
12869 Shape::from_dims(&[2]),
12870 cpu_dev(),
12871 )
12872 .unwrap();
12873 assert_eq!(a.dtype(), DType::F16);
12874 let node = a.graph().read().unwrap().node(a.id()).clone();
12875 assert!(matches!(node.op, Op::Const));
12876 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12877 assert_eq!(slot.read().unwrap().dtype(), DType::F16);
12878 }
12879
12880 #[test]
12881 #[should_panic(expected = "dtype mismatch")]
12882 fn add_panics_on_mixed_dtype() {
12883 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12884 let b = a
12885 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12886 .unwrap();
12887 let _ = a.add(&b);
12888 }
12889
12890 // ----- transpose -----
12891
12892 #[test]
12893 fn transpose_swaps_shape_dims() {
12894 let a = NodeHandle::from_f32(
12895 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
12896 Shape::from_dims(&[2, 3]),
12897 cpu_dev(),
12898 )
12899 .unwrap();
12900 let t = a.transpose();
12901 assert_eq!(t.shape().dims(), &[3, 2]);
12902 let node = t.graph().read().unwrap().node(t.id()).clone();
12903 assert!(matches!(node.op, Op::Transpose));
12904 assert_eq!(node.inputs, vec![a.id()]);
12905 }
12906
12907 #[test]
12908 #[should_panic(expected = "rank ≥ 2")]
12909 fn transpose_rejects_rank_1() {
12910 let a =
12911 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12912 let _ = a.transpose();
12913 }
12914
12915 #[test]
12916 fn transpose_on_rank_3_swaps_last_two_dims() {
12917 // [2, 3, 4] → [2, 4, 3]
12918 let a = NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev())
12919 .unwrap();
12920 let t = a.transpose();
12921 assert_eq!(t.shape().dims(), &[2, 4, 3]);
12922 }
12923
12924 // ----- additional builder validation tests -----
12925
12926 #[test]
12927 fn matmul_rank_3_batched_shape() {
12928 // [2, 3, 4] @ [2, 4, 5] → [2, 3, 5]
12929 let a =
12930 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12931 let b = a
12932 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12933 .unwrap();
12934 let c = a.matmul(&b);
12935 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12936 }
12937
12938 #[test]
12939 #[should_panic(expected = "batch dim mismatch")]
12940 fn matmul_rank_3_rejects_batch_dim_mismatch() {
12941 let a =
12942 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12943 let b = a
12944 .const_f32_like(vec![0.0; 60], Shape::from_dims(&[3, 4, 5]))
12945 .unwrap();
12946 let _ = a.matmul(&b);
12947 }
12948
12949 #[test]
12950 fn matmul_auto_broadcasts_rank_2_rhs_against_batched_lhs() {
12951 // [batch=2, seq=3, k=4] @ [k=4, n=5] → [2, 3, 5]. This is the
12952 // canonical "linear layer across a batch" pattern and should
12953 // Just Work without an explicit broadcast_to on the RHS.
12954 let a =
12955 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12956 let b = a
12957 .const_f32_like(vec![0.0; 20], Shape::from_dims(&[4, 5]))
12958 .unwrap();
12959 let c = a.matmul(&b);
12960 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12961 }
12962
12963 #[test]
12964 fn matmul_auto_broadcasts_rank_2_lhs_against_batched_rhs() {
12965 // [m=3, k=4] @ [batch=2, k=4, n=5] → [2, 3, 5].
12966 let a = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
12967 let b = a
12968 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12969 .unwrap();
12970 let c = a.matmul(&b);
12971 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12972 }
12973
12974 #[test]
12975 fn concat_output_shape_sums_along_dim() {
12976 // [2, 3] concat [2, 4] along dim 1 → [2, 7]
12977 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12978 let b = a
12979 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
12980 .unwrap();
12981 let c = a.concat(&b, 1);
12982 assert_eq!(c.shape().dims(), &[2, 7]);
12983 }
12984
12985 #[test]
12986 #[should_panic(expected = "non-dim shapes")]
12987 fn concat_rejects_nondim_shape_mismatch() {
12988 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12989 let b = a
12990 .const_f32_like(vec![0.0; 12], Shape::from_dims(&[3, 4]))
12991 .unwrap();
12992 let _ = a.concat(&b, 1);
12993 }
12994
12995 #[test]
12996 #[should_panic(expected = "rank mismatch")]
12997 fn concat_rejects_rank_mismatch() {
12998 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12999 let b = a
13000 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[6]))
13001 .unwrap();
13002 let _ = a.concat(&b, 0);
13003 }
13004
13005 #[test]
13006 fn slice_shrinks_only_the_slice_dim() {
13007 // [3, 4] slice dim 1, start 1, len 2 → [3, 2]
13008 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13009 let s = x.slice(1, 1, 2);
13010 assert_eq!(s.shape().dims(), &[3, 2]);
13011 }
13012
13013 #[test]
13014 #[should_panic(expected = "exceeds dim size")]
13015 fn slice_rejects_out_of_bounds_range() {
13016 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13017 let _ = x.slice(1, 1, 3); // start=1, len=3 → would need dim>=4
13018 }
13019
13020 #[test]
13021 fn broadcast_add_shape_promotes_to_common_shape() {
13022 // [4, 1] + [1, 3] → [4, 3]
13023 let a = NodeHandle::from_f32(vec![0.0; 4], Shape::from_dims(&[4, 1]), cpu_dev()).unwrap();
13024 let b = a
13025 .const_f32_like(vec![0.0; 3], Shape::from_dims(&[1, 3]))
13026 .unwrap();
13027 let c = a.broadcast_add(&b);
13028 assert_eq!(c.shape().dims(), &[4, 3]);
13029 }
13030
13031 #[test]
13032 fn broadcast_sub_pads_shorter_shape_with_leading_ones() {
13033 // [3] - [2, 3] → [2, 3]
13034 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13035 let b = a
13036 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[2, 3]))
13037 .unwrap();
13038 let c = a.broadcast_sub(&b);
13039 assert_eq!(c.shape().dims(), &[2, 3]);
13040 }
13041
13042 #[test]
13043 #[should_panic(expected = "incompatible shapes")]
13044 fn broadcast_add_rejects_incompatible_shapes() {
13045 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13046 let b = a
13047 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13048 .unwrap();
13049 let _ = a.broadcast_add(&b);
13050 }
13051
13052 #[test]
13053 fn argmax_dim_is_u32_and_removes_reduced_dim() {
13054 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13055 let am = x.argmax_dim(1);
13056 assert_eq!(am.dtype(), DType::U32);
13057 assert_eq!(am.shape().dims(), &[2]);
13058 }
13059
13060 #[test]
13061 #[should_panic(expected = "out of bounds")]
13062 fn argmax_dim_rejects_bad_dim() {
13063 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13064 let _ = x.argmax_dim(5);
13065 }
13066
13067 #[test]
13068 fn index_add_shape_validation() {
13069 let base = NodeHandle::from_f32(vec![0.0; 10], Shape::from_dims(&[10]), cpu_dev()).unwrap();
13070 let idx = base
13071 .const_u32_like(vec![1, 3, 5], Shape::from_dims(&[3]))
13072 .unwrap();
13073 let src = base
13074 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13075 .unwrap();
13076 let out = base.index_add(0, &idx, &src);
13077 assert_eq!(out.shape().dims(), &[10]);
13078 }
13079
13080 #[test]
13081 #[should_panic(expected = "dtypes must match")]
13082 fn index_add_rejects_dtype_mismatch() {
13083 let base = NodeHandle::from_f32(vec![0.0; 5], Shape::from_dims(&[5]), cpu_dev()).unwrap();
13084 let idx = base
13085 .const_u32_like(vec![0, 2], Shape::from_dims(&[2]))
13086 .unwrap();
13087 let src = base
13088 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13089 .unwrap();
13090 let _ = base.index_add(0, &idx, &src);
13091 }
13092
13093 #[test]
13094 fn scatter_add_validates_index_matches_src() {
13095 let base =
13096 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13097 let idx = base
13098 .const_u32_like(vec![0, 2, 1, 0], Shape::from_dims(&[2, 2]))
13099 .unwrap();
13100 let src = base
13101 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13102 .unwrap();
13103 let out = base.scatter_add(1, &idx, &src);
13104 assert_eq!(out.shape().dims(), &[2, 3]);
13105 }
13106
13107 #[test]
13108 #[should_panic(expected = "same shape")]
13109 fn scatter_add_rejects_index_src_shape_mismatch() {
13110 let base =
13111 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13112 let idx = base
13113 .const_u32_like(vec![0, 1], Shape::from_dims(&[2]))
13114 .unwrap();
13115 let src = base
13116 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13117 .unwrap();
13118 let _ = base.scatter_add(1, &idx, &src);
13119 }
13120
13121 #[test]
13122 fn reduce_sum_to_validates_compatibility() {
13123 // [3, 4] can reduce to [4] (sum along dim 0) or [3, 1] (sum along dim 1).
13124 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13125 let r1 = x.reduce_sum_to(Shape::from_dims(&[4]));
13126 assert_eq!(r1.shape().dims(), &[4]);
13127 let r2 = x.reduce_sum_to(Shape::from_dims(&[3, 1]));
13128 assert_eq!(r2.shape().dims(), &[3, 1]);
13129 }
13130
13131 #[test]
13132 #[should_panic(expected = "incompatible")]
13133 fn reduce_sum_to_rejects_non_broadcast_target() {
13134 // [3, 4] cannot reduce to [3, 2] — target must be broadcast-into-source.
13135 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13136 let _ = x.reduce_sum_to(Shape::from_dims(&[3, 2]));
13137 }
13138
13139 #[test]
13140 fn unsqueeze_inserts_size_one_dim() {
13141 let x = NodeHandle::from_f32(
13142 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13143 Shape::from_dims(&[2, 3]),
13144 cpu_dev(),
13145 )
13146 .unwrap();
13147 // Insert at position 0: [2, 3] -> [1, 2, 3]
13148 let y0 = x.unsqueeze(0);
13149 assert_eq!(y0.shape().dims(), &[1, 2, 3]);
13150 // Insert at position 1: [2, 3] -> [2, 1, 3]
13151 let y1 = x.unsqueeze(1);
13152 assert_eq!(y1.shape().dims(), &[2, 1, 3]);
13153 // Insert at the end (rank): [2, 3] -> [2, 3, 1]
13154 let y2 = x.unsqueeze(2);
13155 assert_eq!(y2.shape().dims(), &[2, 3, 1]);
13156 // Op variant correctness.
13157 let g = x.graph().read().unwrap();
13158 assert!(matches!(g.node(y0.id()).op, Op::Unsqueeze { dim: 0 }));
13159 assert!(matches!(g.node(y1.id()).op, Op::Unsqueeze { dim: 1 }));
13160 assert!(matches!(g.node(y2.id()).op, Op::Unsqueeze { dim: 2 }));
13161 }
13162
13163 #[test]
13164 #[should_panic(expected = "out of bounds")]
13165 fn unsqueeze_rejects_dim_above_rank() {
13166 let x = NodeHandle::from_f32(vec![1.0; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
13167 // dim=2 > rank=1 → panic.
13168 let _ = x.unsqueeze(2);
13169 }
13170
13171 #[test]
13172 fn unsqueeze_layout_side_table_populated() {
13173 // After Graph::push auto-derives the Layout side-table for view
13174 // ops, an unsqueeze node should have an explicit layout entry
13175 // with a stride-0 axis at the inserted position.
13176 let x = NodeHandle::from_f32(
13177 vec![1.0, 2.0, 3.0, 4.0],
13178 Shape::from_dims(&[2, 2]),
13179 cpu_dev(),
13180 )
13181 .unwrap();
13182 let y = x.unsqueeze(1);
13183 let g = x.graph().read().unwrap();
13184 assert!(
13185 g.has_explicit_layout(y.id()),
13186 "Graph::push should auto-populate layout for view ops"
13187 );
13188 let l = g.layout(y.id());
13189 assert_eq!(l.shape().dims(), &[2, 1, 2]);
13190 // Stride at the inserted axis should be 0 (per the convention
13191 // chosen in Layout::unsqueeze).
13192 assert_eq!(l.stride()[1], 0);
13193 }
13194
13195 #[test]
13196 fn reduce_max_to_validates_compatibility() {
13197 // [3, 4] can reduce to [4] (max along dim 0) or [3, 1] (max along dim 1).
13198 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13199 let r1 = x.reduce_max_to(Shape::from_dims(&[4]));
13200 assert_eq!(r1.shape().dims(), &[4]);
13201 assert!(matches!(
13202 r1.graph().read().unwrap().node(r1.id()).op,
13203 Op::ReduceMaxTo(_)
13204 ));
13205 let r2 = x.reduce_max_to(Shape::from_dims(&[3, 1]));
13206 assert_eq!(r2.shape().dims(), &[3, 1]);
13207 }
13208
13209 #[test]
13210 #[should_panic(expected = "incompatible")]
13211 fn reduce_max_to_rejects_non_broadcast_target() {
13212 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13213 let _ = x.reduce_max_to(Shape::from_dims(&[3, 2]));
13214 }
13215
13216 #[test]
13217 fn reshape_preserves_element_count() {
13218 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13219 let r = x.reshape(Shape::from_dims(&[2, 6]));
13220 assert_eq!(r.shape().dims(), &[2, 6]);
13221 }
13222
13223 #[test]
13224 #[should_panic(expected = "element count mismatch")]
13225 fn reshape_rejects_different_element_count() {
13226 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13227 let _ = x.reshape(Shape::from_dims(&[3, 3]));
13228 }
13229
13230 #[test]
13231 #[should_panic(expected = "same graph")]
13232 fn concat_across_graphs_panics() {
13233 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13234 let b = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13235 let _ = a.concat(&b, 0);
13236 }
13237
13238 #[test]
13239 fn scalar_ops_preserve_shape_and_dtype() {
13240 let x =
13241 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13242 let y = x.add_scalar(5.0).mul_scalar(2.0).powi(2).clamp(0.0, 100.0);
13243 assert_eq!(y.shape().dims(), &[3]);
13244 assert_eq!(y.dtype(), DType::F32);
13245 }
13246
13247 #[test]
13248 fn maximum_requires_matching_shapes() {
13249 let a =
13250 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13251 let b = a
13252 .const_f32_like(vec![4.0, 1.0, 5.0], Shape::from_dims(&[3]))
13253 .unwrap();
13254 let m = a.maximum(&b);
13255 assert_eq!(m.shape().dims(), &[3]);
13256 }
13257
13258 #[test]
13259 #[should_panic(expected = "shape mismatch")]
13260 fn maximum_rejects_shape_mismatch() {
13261 let a =
13262 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13263 let b = a
13264 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13265 .unwrap();
13266 let _ = a.maximum(&b);
13267 }
13268
13269 // ----- topo_order -----
13270
13271 #[test]
13272 fn topo_order_places_inputs_before_dependents() {
13273 // Build: c = (a + b) * a
13274 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13275 let b = a
13276 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13277 .unwrap();
13278 let sum = a.add(&b);
13279 let c = sum.mul(&a);
13280 let order = topo_order(&c.graph().read().unwrap(), c.id());
13281 // The order should contain exactly 4 nodes (a, b, sum, c) and
13282 // place each input strictly before its dependents.
13283 assert_eq!(order.len(), 4);
13284 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13285 assert!(pos(a.id()) < pos(sum.id()));
13286 assert!(pos(b.id()) < pos(sum.id()));
13287 assert!(pos(sum.id()) < pos(c.id()));
13288 assert!(pos(a.id()) < pos(c.id()));
13289 }
13290
13291 #[test]
13292 fn topo_order_visits_each_node_once_when_shared() {
13293 // (a + a) — `a` appears twice in the Add's inputs but the topo
13294 // pass should still visit it exactly once.
13295 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13296 let double = a.add(&a);
13297 let order = topo_order(&double.graph().read().unwrap(), double.id());
13298 assert_eq!(order.len(), 2);
13299 assert_eq!(order[0], a.id());
13300 assert_eq!(order[1], double.id());
13301 }
13302
13303 #[test]
13304 fn topo_order_multi_unions_multiple_roots() {
13305 // Build a DAG where two "output" nodes share a common input.
13306 //
13307 // a ─┬─> add1 (= a + b) ← root_1
13308 // └─> add2 (= a + c) ← root_2
13309 // b ───> add1
13310 // c ───> add2
13311 //
13312 // topo_order_multi(&[add1, add2]) must contain all 5 nodes
13313 // (a, b, c, add1, add2) with a before add1/add2 and b before
13314 // add1 and c before add2.
13315 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13316 let b = a
13317 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13318 .unwrap();
13319 let c = a
13320 .const_f32_like(vec![5.0, 6.0], Shape::from_dims(&[2]))
13321 .unwrap();
13322 let add1 = a.add(&b);
13323 let add2 = a.add(&c);
13324 let order = topo_order_multi(&add1.graph().read().unwrap(), &[add1.id(), add2.id()]);
13325 assert_eq!(order.len(), 5);
13326 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13327 assert!(pos(a.id()) < pos(add1.id()));
13328 assert!(pos(a.id()) < pos(add2.id()));
13329 assert!(pos(b.id()) < pos(add1.id()));
13330 assert!(pos(c.id()) < pos(add2.id()));
13331 }
13332
13333 // ----- backward -----
13334
13335 #[test]
13336 fn backward_of_lone_const_seeds_ones() {
13337 // backward(a) gives a = 1s (the root's upstream is a ones tensor,
13338 // which is the gradient stored for the root itself).
13339 let a =
13340 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13341 let grads = a.backward();
13342 let g_a = grads.get(&a).expect("root gets a seed gradient");
13343 // The seed is a Const ones node of matching shape. Phase 7.5
13344 // G2: gradient consts are slot-rooted Op::Const — no
13345 // host-side ConstData on the node.
13346 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13347 assert!(matches!(node.op, Op::Const));
13348 let slot = g_a.graph().read().unwrap().storage_for(g_a.id()).unwrap();
13349 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
13350 assert_eq!(g_a.shape().dims(), &[3]);
13351 }
13352
13353 #[test]
13354 fn backward_of_add_passes_upstream_through() {
13355 // c = a + b ⇒ dc/da = 1, dc/db = 1.
13356 // Upstream seed is a ones tensor. So grad_a and grad_b are both
13357 // the same ones node (no new math emitted for Add's backward).
13358 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13359 let b = a
13360 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13361 .unwrap();
13362 let c = a.add(&b);
13363 let grads = c.backward();
13364 let g_a = grads.get(&a).unwrap();
13365 let g_b = grads.get(&b).unwrap();
13366 assert_eq!(g_a.id(), g_b.id(), "Add backward routes upstream unchanged");
13367 assert_eq!(g_a.shape().dims(), &[2]);
13368 }
13369
13370 #[test]
13371 fn backward_of_mul_emits_two_mul_nodes() {
13372 // c = a * b ⇒ dc/da = b, dc/db = a (upstream is 1s).
13373 // The backward pass should emit two new Mul nodes (upstream * b,
13374 // upstream * a).
13375 let a = NodeHandle::from_f32(vec![2.0, 3.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13376 let b = a
13377 .const_f32_like(vec![5.0, 7.0], Shape::from_dims(&[2]))
13378 .unwrap();
13379 let c = a.mul(&b);
13380 let nodes_before = c.graph().read().unwrap().len();
13381 let grads = c.backward();
13382 let nodes_after = grads.graph.read().unwrap().len();
13383 // Backward adds: one ones const + two Mul nodes = 3 new nodes.
13384 assert_eq!(nodes_after - nodes_before, 3);
13385 let g_a = grads.get(&a).unwrap();
13386 let g_b = grads.get(&b).unwrap();
13387 // Both gradient nodes should be Mul nodes.
13388 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13389 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13390 assert!(matches!(node_a.op, Op::Mul));
13391 assert!(matches!(node_b.op, Op::Mul));
13392 }
13393
13394 #[test]
13395 fn backward_accumulates_when_node_used_twice() {
13396 // c = a * a ⇒ dc/da = 2a via two separate contributions.
13397 // After backward, the gradient for a should be an Add node
13398 // combining the two Mul contributions (one from each input slot
13399 // of the forward Mul).
13400 let a = NodeHandle::from_f32(vec![3.0, 5.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13401 let c = a.mul(&a);
13402 let grads = c.backward();
13403 let g_a = grads.get(&a).unwrap();
13404 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13405 // The final gradient for `a` is an Add combining the two
13406 // upstream-times-other-input contributions.
13407 assert!(
13408 matches!(node.op, Op::Add),
13409 "expected accumulated gradient to be an Add node, got {:?}",
13410 node.op,
13411 );
13412 }
13413
13414 #[test]
13415 fn backward_of_matmul_emits_transpose_and_matmul_nodes() {
13416 // Forward: Y = A @ B, A:[2,3], B:[3,4], Y:[2,4].
13417 // Backward: dA = dY @ B^T (shape [2,3]), dB = A^T @ dY (shape [3,4]).
13418 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13419 let b = a
13420 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13421 .unwrap();
13422 let y = a.matmul(&b);
13423 let grads = y.backward();
13424 let g_a = grads.get(&a).unwrap();
13425 let g_b = grads.get(&b).unwrap();
13426 // Gradient shapes must match the forward shapes.
13427 assert_eq!(g_a.shape().dims(), &[2, 3]);
13428 assert_eq!(g_b.shape().dims(), &[3, 4]);
13429 // Both should be MatMul nodes (the outermost op of each gradient).
13430 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13431 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13432 assert!(matches!(node_a.op, Op::MatMul));
13433 assert!(matches!(node_b.op, Op::MatMul));
13434 }
13435
13436 // ----- new builder validation -----
13437
13438 #[test]
13439 fn cast_tags_node_with_target_dtype() {
13440 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13441 let b = a.cast(DType::F64);
13442 assert_eq!(b.dtype(), DType::F64);
13443 assert_eq!(b.shape().dims(), &[2]);
13444 let node = b.graph().read().unwrap().node(b.id()).clone();
13445 assert!(matches!(node.op, Op::Cast(DType::F64)));
13446 }
13447
13448 #[test]
13449 fn broadcast_to_accepts_right_aligned_expansion() {
13450 // [3] broadcasts to [2, 3]: pad with leading 1, expand.
13451 let a =
13452 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13453 let b = a.broadcast_to(Shape::from_dims(&[2, 3]));
13454 assert_eq!(b.shape().dims(), &[2, 3]);
13455 }
13456
13457 #[test]
13458 fn broadcast_to_accepts_size_one_expansion() {
13459 // [3, 1] broadcasts to [3, 4]: size-1 dim expands.
13460 let a = NodeHandle::from_f32(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3, 1]), cpu_dev())
13461 .unwrap();
13462 let b = a.broadcast_to(Shape::from_dims(&[3, 4]));
13463 assert_eq!(b.shape().dims(), &[3, 4]);
13464 }
13465
13466 #[test]
13467 #[should_panic(expected = "incompatible")]
13468 fn broadcast_to_rejects_incompatible_dim() {
13469 // [3] cannot broadcast to [2, 4] — the source dim 3 must match 4.
13470 let a =
13471 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13472 let _ = a.broadcast_to(Shape::from_dims(&[2, 4]));
13473 }
13474
13475 #[test]
13476 fn sum_all_produces_rank_zero_output() {
13477 let a =
13478 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13479 let s = a.sum_all();
13480 assert_eq!(s.shape().dims(), &[] as &[usize]);
13481 }
13482
13483 #[test]
13484 fn sum_dim_removes_reduced_dim_from_shape() {
13485 let a =
13486 NodeHandle::from_f32(vec![1.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13487 // Reducing dim 1 should give shape [2, 4].
13488 let s = a.sum_dim(1);
13489 assert_eq!(s.shape().dims(), &[2, 4]);
13490 }
13491
13492 #[test]
13493 #[should_panic(expected = "out of bounds")]
13494 fn sum_dim_rejects_bad_dim() {
13495 let a =
13496 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13497 let _ = a.sum_dim(5);
13498 }
13499
13500 #[test]
13501 fn softmax_and_layer_norm_preserve_shape() {
13502 let a = NodeHandle::from_f32(
13503 vec![1.0, 2.0, 3.0, 4.0],
13504 Shape::from_dims(&[2, 2]),
13505 cpu_dev(),
13506 )
13507 .unwrap();
13508 assert_eq!(a.softmax_last_dim().shape().dims(), &[2, 2]);
13509 assert_eq!(a.layer_norm_last_dim(1e-5).shape().dims(), &[2, 2]);
13510 }
13511
13512 #[test]
13513 fn neg_sub_div_sqrt_log_sin_cos_tanh_sigmoid_all_build() {
13514 // Smoke test: every new builder produces a node with the expected
13515 // shape and dtype. Numerical correctness is exercised in exec.rs.
13516 let a =
13517 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13518 let b = a
13519 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13520 .unwrap();
13521 for tensor in [
13522 a.neg(),
13523 a.sub(&b),
13524 a.div(&b),
13525 a.sqrt(),
13526 a.log(),
13527 a.sin(),
13528 a.cos(),
13529 a.tanh(),
13530 a.sigmoid(),
13531 a.step(),
13532 ] {
13533 assert_eq!(tensor.shape().dims(), &[3]);
13534 assert_eq!(tensor.dtype(), DType::F32);
13535 }
13536 }
13537
13538 // ----- index tensors and indexing ops -----
13539
13540 #[test]
13541 fn from_u32_tags_node_with_u32_dtype() {
13542 let a = NodeHandle::from_u32(vec![1, 2, 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13543 assert_eq!(a.dtype(), DType::U32);
13544 let node = a.graph().read().unwrap().node(a.id()).clone();
13545 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13546 assert!(matches!(node.op, Op::Const));
13547 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13548 assert_eq!(slot.read().unwrap().dtype(), DType::U32);
13549 }
13550
13551 #[test]
13552 fn index_select_produces_shape_with_dim_replaced() {
13553 let data =
13554 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13555 let idx = data
13556 .const_u32_like(vec![0, 2, 1, 0, 2], Shape::from_dims(&[5]))
13557 .unwrap();
13558 let out = data.index_select(0, &idx);
13559 assert_eq!(out.shape().dims(), &[5, 4]);
13560 assert_eq!(out.dtype(), DType::F32);
13561 }
13562
13563 #[test]
13564 #[should_panic(expected = "must be U32")]
13565 fn index_select_rejects_float_index() {
13566 let data =
13567 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13568 let bad = data
13569 .const_f32_like(vec![0.0, 1.0], Shape::from_dims(&[2]))
13570 .unwrap();
13571 let _ = data.index_select(0, &bad);
13572 }
13573
13574 #[test]
13575 #[should_panic(expected = "must be rank 1")]
13576 fn index_select_rejects_multi_dim_index() {
13577 let data =
13578 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13579 let idx = data
13580 .const_u32_like(vec![0, 1, 0, 1], Shape::from_dims(&[2, 2]))
13581 .unwrap();
13582 let _ = data.index_select(0, &idx);
13583 }
13584
13585 #[test]
13586 fn gather_output_shape_matches_index_shape() {
13587 let data =
13588 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13589 // Index shape [2, 5] — same rank as data (rank 2).
13590 let idx = data
13591 .const_u32_like(vec![0; 10], Shape::from_dims(&[2, 5]))
13592 .unwrap();
13593 let out = data.gather(1, &idx);
13594 assert_eq!(out.shape().dims(), &[2, 5]);
13595 }
13596
13597 #[test]
13598 #[should_panic(expected = "same rank")]
13599 fn gather_rejects_rank_mismatch() {
13600 let data =
13601 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13602 // Rank-1 index for rank-2 data → error.
13603 let idx = data
13604 .const_u32_like(vec![0, 1, 0], Shape::from_dims(&[3]))
13605 .unwrap();
13606 let _ = data.gather(1, &idx);
13607 }
13608
13609 #[test]
13610 fn backward_of_relu_emits_step_node() {
13611 // Before: this used to panic. After adding Step + Relu backward,
13612 // it should successfully emit a backward graph rooted in a Mul
13613 // whose second input is a Step node.
13614 let a =
13615 NodeHandle::from_f32(vec![-1.0, 2.0, -3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13616 let y = a.relu();
13617 let grads = y.backward();
13618 let g_a = grads.get(&a).unwrap();
13619 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13620 assert!(matches!(node.op, Op::Mul));
13621 // Find a Step node somewhere in the node's inputs.
13622 let any_step = node
13623 .inputs
13624 .iter()
13625 .any(|&id| matches!(g_a.graph().read().unwrap().node(id).op, Op::Step,));
13626 assert!(any_step, "Relu backward must reference a Step node");
13627 }
13628
13629 #[test]
13630 fn recip_and_abs_builders_produce_unary_nodes() {
13631 // Smoke test: NodeHandle::recip()/abs() build single-input nodes
13632 // with the expected op variant and shape passthrough.
13633 let a =
13634 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13635 let r = a.recip();
13636 let b = a.abs();
13637 assert_eq!(r.shape().dims(), &[3]);
13638 assert_eq!(b.shape().dims(), &[3]);
13639 let r_node = r.graph().read().unwrap().node(r.id()).clone();
13640 let b_node = b.graph().read().unwrap().node(b.id()).clone();
13641 assert!(matches!(r_node.op, Op::Recip));
13642 assert!(matches!(b_node.op, Op::Abs));
13643 assert_eq!(r_node.inputs, vec![a.id()]);
13644 assert_eq!(b_node.inputs, vec![a.id()]);
13645 }
13646
13647 #[test]
13648 fn backward_of_recip_is_neg_of_upstream_times_y_squared() {
13649 // y = 1/x ⇒ dy/dx = -y². The backward graph should be a Neg
13650 // wrapping a Mul whose inputs include a Sqr node — and the Sqr
13651 // should reference the forward Recip output, not a fresh recompute.
13652 let a = NodeHandle::from_f32(vec![2.0, 4.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13653 let y = a.recip();
13654 let y_id = y.id();
13655 let grads = y.backward();
13656 let g_a = grads.get(&a).unwrap();
13657 let g = g_a.graph().read().unwrap();
13658 let neg_node = g.node(g_a.id()).clone();
13659 assert!(
13660 matches!(neg_node.op, Op::Neg),
13661 "outermost backward op must be Neg"
13662 );
13663 let mul_id = neg_node.inputs[0];
13664 let mul_node = g.node(mul_id).clone();
13665 assert!(matches!(mul_node.op, Op::Mul));
13666 // One of the Mul's inputs is a Sqr node fed by the forward Recip.
13667 let sqr_id = mul_node
13668 .inputs
13669 .iter()
13670 .copied()
13671 .find(|&id| matches!(g.node(id).op, Op::Sqr))
13672 .expect("backward chain must contain a Sqr node");
13673 let sqr_node = g.node(sqr_id).clone();
13674 assert_eq!(
13675 sqr_node.inputs,
13676 vec![y_id],
13677 "Sqr's input must be the forward Recip output, not a recompute"
13678 );
13679 }
13680
13681 #[test]
13682 fn backward_of_abs_emits_sign_mul() {
13683 // y = |x|, dy/dx = sign(x). After PR B2 landed Op::Sign, the
13684 // backward chain shrinks from 5 nodes (step+neg+step+sub+mul)
13685 // to 2 (sign+mul): grad_x = upstream * sign(x), where Sign is
13686 // a single primitive that returns -1/0/1 directly.
13687 let a = NodeHandle::from_f32(vec![-2.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13688 let y = a.abs();
13689 let grads = y.backward();
13690 let g_a = grads.get(&a).unwrap();
13691 let g = g_a.graph().read().unwrap();
13692 let mul_node = g.node(g_a.id()).clone();
13693 assert!(matches!(mul_node.op, Op::Mul));
13694 // Exactly one input of the Mul is a Sign node (the other is
13695 // the upstream gradient — a Const-rooted ones-tensor here).
13696 let sign_count = mul_node
13697 .inputs
13698 .iter()
13699 .filter(|&&id| matches!(g.node(id).op, Op::Sign))
13700 .count();
13701 assert_eq!(
13702 sign_count, 1,
13703 "Abs backward must reference exactly 1 Sign node, got {sign_count}"
13704 );
13705 // The Sign node should feed off the original input `a`.
13706 let sign_id = mul_node
13707 .inputs
13708 .iter()
13709 .copied()
13710 .find(|&id| matches!(g.node(id).op, Op::Sign))
13711 .unwrap();
13712 assert_eq!(
13713 g.node(sign_id).inputs,
13714 vec![a.id()],
13715 "Sign's input must be the forward input `a`"
13716 );
13717 }
13718
13719 #[test]
13720 fn eq_builder_produces_bool_output_with_input_shape() {
13721 // GAP-168(c): NodeHandle::eq builds a binary node whose dtype is Bool
13722 // regardless of input dtype (CireSnave's ruling — "Fuel uses Bool
13723 // where possible"), with shape == lhs.shape() (and == rhs.shape()).
13724 let a =
13725 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13726 let b = a
13727 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13728 .unwrap();
13729 let m = a.eq(&b);
13730 assert_eq!(m.shape().dims(), &[3]);
13731 assert_eq!(m.dtype(), DType::Bool, "eq output must be Bool");
13732 let m_node = m.graph().read().unwrap().node(m.id()).clone();
13733 assert!(matches!(m_node.op, Op::Equal));
13734 assert_eq!(m_node.inputs, vec![a.id(), b.id()]);
13735 }
13736
13737 #[test]
13738 fn all_six_comparisons_produce_bool() {
13739 // GAP-168(c): eq/ne/lt/le/gt/ge every one returns DType::Bool, not the
13740 // legacy U8 mask. Shape is preserved (== lhs == rhs). One assertion per
13741 // operator so a regression names the operator that drifted.
13742 let a =
13743 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13744 let b = a
13745 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13746 .unwrap();
13747 for (name, m) in [
13748 ("eq", a.eq(&b)),
13749 ("ne", a.ne(&b)),
13750 ("lt", a.lt(&b)),
13751 ("le", a.le(&b)),
13752 ("gt", a.gt(&b)),
13753 ("ge", a.ge(&b)),
13754 ] {
13755 assert_eq!(m.dtype(), DType::Bool, "{name} output must be Bool");
13756 assert_eq!(m.shape().dims(), &[3], "{name} preserves input shape");
13757 }
13758 }
13759
13760 #[test]
13761 fn try_unsqueeze_returns_err_on_dim_above_rank() {
13762 // try_unsqueeze surfaces bad dim as Err; unsqueeze panics
13763 // on the same input. Both share the validation message.
13764 let a =
13765 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13766 let err = a.try_unsqueeze(5).expect_err("dim above rank must error");
13767 assert!(
13768 format!("{err:?}").contains("out of bounds"),
13769 "error must mention bounds, got: {err:?}"
13770 );
13771 // Happy path still works.
13772 let ok = a.try_unsqueeze(0).expect("dim=0 valid for any rank");
13773 assert_eq!(ok.shape().dims(), &[1, 3]);
13774 }
13775
13776 #[test]
13777 fn try_reshape_returns_err_on_count_mismatch() {
13778 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
13779 .unwrap();
13780 let err = a
13781 .try_reshape(Shape::from_dims(&[3]))
13782 .expect_err("count mismatch must error");
13783 assert!(
13784 format!("{err:?}").contains("element count mismatch"),
13785 "error must mention count mismatch, got: {err:?}"
13786 );
13787 let ok = a
13788 .try_reshape(Shape::from_dims(&[2, 2]))
13789 .expect("matching count is ok");
13790 assert_eq!(ok.shape().dims(), &[2, 2]);
13791 }
13792
13793 #[test]
13794 fn try_broadcast_to_returns_err_on_incompatible_shape() {
13795 let a =
13796 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13797 let err = a
13798 .try_broadcast_to(Shape::from_dims(&[2, 4]))
13799 .expect_err("source dim 3 cannot broadcast to dim 4");
13800 assert!(
13801 format!("{err:?}").contains("incompatible"),
13802 "error must mention incompatibility, got: {err:?}"
13803 );
13804 let ok = a
13805 .try_broadcast_to(Shape::from_dims(&[2, 3]))
13806 .expect("dim 3 broadcasts to dim 3");
13807 assert_eq!(ok.shape().dims(), &[2, 3]);
13808 }
13809
13810 #[test]
13811 fn try_transpose_returns_err_on_rank_below_2() {
13812 let a =
13813 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13814 let err = a
13815 .try_transpose()
13816 .expect_err("rank-1 input cannot transpose");
13817 assert!(
13818 format!("{err:?}").contains("rank ≥ 2"),
13819 "error must mention rank requirement, got: {err:?}"
13820 );
13821 let m = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13822 let mt = m.try_transpose().expect("rank-2 transposes ok");
13823 assert_eq!(mt.shape().dims(), &[3, 2]);
13824 }
13825
13826 #[test]
13827 fn try_permute_returns_err_on_bad_axes() {
13828 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13829 // Wrong axes length:
13830 let err = a.try_permute(&[0]).expect_err("axes length mismatch");
13831 assert!(
13832 format!("{err:?}").contains("must equal tensor rank"),
13833 "error must mention length, got: {err:?}"
13834 );
13835 // Out-of-bounds axis:
13836 let err = a.try_permute(&[0, 5]).expect_err("axis 5 out of rank 2");
13837 assert!(format!("{err:?}").contains("out of bounds"));
13838 // Duplicate axis:
13839 let err = a.try_permute(&[0, 0]).expect_err("duplicate axis");
13840 assert!(format!("{err:?}").contains("duplicate"));
13841 // Happy path:
13842 let ok = a.try_permute(&[1, 0]).expect("valid permutation");
13843 assert_eq!(ok.shape().dims(), &[3, 2]);
13844 }
13845
13846 #[test]
13847 fn squeeze_drops_size_one_dim_metadata_only() {
13848 // Build [2, 1, 3] → squeeze(1) → [2, 3]. Op::Squeeze, view-op,
13849 // shape pruned, dtype preserved, single input slot.
13850 let a =
13851 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13852 let s = a.squeeze(1).expect("squeeze on size-1 dim");
13853 assert_eq!(s.shape().dims(), &[2, 3]);
13854 assert_eq!(s.dtype(), DType::F32);
13855 let node = s.graph().read().unwrap().node(s.id()).clone();
13856 assert!(matches!(node.op, Op::Squeeze { dim: 1 }));
13857 assert_eq!(node.inputs, vec![a.id()]);
13858 // Squeeze joins the view-op set so the Layout side-table is
13859 // populated automatically.
13860 assert!(
13861 node.op.is_view_op(),
13862 "Op::Squeeze must register as a view op"
13863 );
13864 }
13865
13866 #[test]
13867 fn squeeze_rejects_non_size_one_dim() {
13868 // Result-returning: bad dim surfaces as Err, not panic.
13869 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13870 let err = a
13871 .squeeze(1)
13872 .expect_err("squeezing a non-size-1 dim must error");
13873 assert!(
13874 format!("{err:?}").contains("expected 1"),
13875 "error message should mention the size-1 expectation, got: {err:?}"
13876 );
13877 }
13878
13879 #[test]
13880 fn squeeze_rejects_dim_above_rank() {
13881 let a =
13882 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13883 let err = a.squeeze(5).expect_err("dim above rank must error");
13884 assert!(
13885 format!("{err:?}").contains("out of bounds"),
13886 "error message should mention bounds, got: {err:?}"
13887 );
13888 }
13889
13890 #[test]
13891 fn backward_through_squeeze_emits_unsqueeze() {
13892 // y = squeeze(x, 1). Backward: re-insert dim 1 via Unsqueeze.
13893 // Gradient shape must equal x.shape exactly.
13894 let a =
13895 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13896 let y = a.squeeze(1).expect("squeeze on size-1 dim");
13897 let grads = y.backward();
13898 let g_a = grads.get(&a).expect("gradient for a");
13899 assert_eq!(
13900 g_a.shape().dims(),
13901 &[2, 1, 3],
13902 "Squeeze backward gradient must restore the original shape"
13903 );
13904 // The chain is: ones-seed (post-squeeze, shape [2,3])
13905 // → Unsqueeze(dim=1) → shape [2, 1, 3].
13906 let g_node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13907 assert!(
13908 matches!(g_node.op, Op::Unsqueeze { dim: 1 }),
13909 "Squeeze backward must be Unsqueeze at the same dim"
13910 );
13911 }
13912
13913 #[test]
13914 fn floor_builder_produces_unary_node_same_dtype() {
13915 // NodeHandle::floor builds a unary node preserving shape + dtype.
13916 let a =
13917 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13918 let f = a.floor();
13919 assert_eq!(f.shape().dims(), &[3]);
13920 assert_eq!(f.dtype(), DType::F32);
13921 let node = f.graph().read().unwrap().node(f.id()).clone();
13922 assert!(matches!(node.op, Op::Floor));
13923 assert_eq!(node.inputs, vec![a.id()]);
13924 }
13925
13926 #[test]
13927 fn backward_through_floor_drops_gradient_silently() {
13928 // Op::Floor has zero gradient almost everywhere; the inline
13929 // backward arm is a no-op. backward() must succeed and the
13930 // input gets no gradient (the input's upstream is never
13931 // populated through the Floor node).
13932 let a =
13933 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13934 let y = a.floor();
13935 let grads = y.backward();
13936 // a's gradient is dropped — no entry in the GradMap.
13937 assert!(
13938 grads.get(&a).is_none(),
13939 "Floor must not propagate gradient to its input"
13940 );
13941 }
13942
13943 #[test]
13944 fn where_cond_builder_produces_ternary_with_a_dtype() {
13945 // self is a Bool cond (GAP-168(c)); a/b are F32. Output dtype = F32
13946 // (= a's dtype), shape = self.shape() (= a.shape() = b.shape()).
13947 // Op::Where node carries 3 inputs in order (cond, a, b).
13948 let a =
13949 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13950 let b = a
13951 .const_f32_like(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3]))
13952 .unwrap();
13953 let eq_a_b = a.eq(&b); // Bool mask
13954 let picked = eq_a_b.where_cond(&a, &b);
13955 assert_eq!(picked.shape().dims(), &[3]);
13956 assert_eq!(picked.dtype(), DType::F32, "Where output dtype = a/b dtype");
13957 let node = picked.graph().read().unwrap().node(picked.id()).clone();
13958 assert!(matches!(node.op, Op::Where));
13959 assert_eq!(node.inputs.len(), 3);
13960 assert_eq!(
13961 node.inputs,
13962 vec![eq_a_b.id(), a.id(), b.id()],
13963 "Where input order: (cond, a, b)"
13964 );
13965 }
13966
13967 #[test]
13968 fn backward_reuses_exp_forward_output() {
13969 // Exp's backward rule uses the forward output directly. The
13970 // gradient for x should be a Mul whose inputs include the
13971 // forward Exp node (not a new Exp node).
13972 let a = NodeHandle::from_f32(vec![0.0, 1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13973 let e = a.exp();
13974 let exp_forward_id = e.id();
13975 let grads = e.backward();
13976 let g_a = grads.get(&a).unwrap();
13977 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13978 assert!(matches!(node.op, Op::Mul));
13979 // One of the Mul's inputs should be the original forward Exp node.
13980 assert!(
13981 node.inputs.contains(&exp_forward_id),
13982 "Exp backward should reference the forward output ({exp_forward_id:?}), \
13983 got inputs {:?}",
13984 node.inputs,
13985 );
13986 }
13987
13988 // ---- Op::WriteSlice (Phase E.3.2) ---------------------------------------
13989
13990 #[test]
13991 fn write_slice_destructive_input_is_zero() {
13992 let op = Op::WriteSlice {
13993 ranges: vec![(0, 1), (0, 32), (0, 128)],
13994 dyn_offset: None,
13995 };
13996 assert_eq!(op.destructive_input(), Some(0));
13997 }
13998
13999 #[test]
14000 fn write_slice_short_name() {
14001 let op = Op::WriteSlice {
14002 ranges: vec![(0, 1)],
14003 dyn_offset: None,
14004 };
14005 assert_eq!(op.short_name(), "WriteSlice");
14006 }
14007
14008 #[test]
14009 fn write_slice_emits_op_writeslice_node() {
14010 // dest shape [4, 3]; source shape [1, 3]; write at row 2.
14011 let dest =
14012 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14013 let src = dest
14014 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14015 .unwrap();
14016 let out = dest
14017 .write_slice(&src, vec![(2, 3), (0, 3)])
14018 .expect("write_slice should accept matching shapes");
14019 let g = out.graph().read().unwrap();
14020 match &g.node(out.id()).op {
14021 Op::WriteSlice { ranges, dyn_offset } => {
14022 assert_eq!(ranges, &vec![(2, 3), (0, 3)]);
14023 assert_eq!(dyn_offset, &None);
14024 }
14025 other => panic!("expected Op::WriteSlice, got {other:?}"),
14026 }
14027 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14028 // Output shape == destination shape; bytes are post-write same buffer.
14029 assert_eq!(g.node(out.id()).shape.dims(), &[4, 3]);
14030 }
14031
14032 #[test]
14033 fn write_slice_dyn_records_dynamic_offset() {
14034 use fuel_ir::{DynScalar, SymId};
14035 // dest capacity [8, 3]; source [1, 3]; dynamic start on axis 0.
14036 let dest =
14037 NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[8, 3]), cpu_dev()).unwrap();
14038 let src = dest
14039 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14040 .unwrap();
14041 let sym = SymId(0);
14042 // ranges[0].0 is ignored (start is dynamic); width = 1 - 0 = 1
14043 // matches source dim 0. Axis 1 is static, full width.
14044 let out = dest
14045 .write_slice_dyn(&src, vec![(0, 1), (0, 3)], 0, DynScalar::Sym(sym))
14046 .expect("write_slice_dyn should accept matching widths");
14047 let g = out.graph().read().unwrap();
14048 match &g.node(out.id()).op {
14049 Op::WriteSlice { ranges, dyn_offset } => {
14050 assert_eq!(ranges, &vec![(0, 1), (0, 3)]);
14051 assert_eq!(dyn_offset, &Some((0, DynScalar::Sym(sym))));
14052 }
14053 other => panic!("expected Op::WriteSlice, got {other:?}"),
14054 }
14055 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14056 assert_eq!(g.node(out.id()).shape.dims(), &[8, 3]);
14057 }
14058
14059 #[test]
14060 fn write_slice_dyn_rejects_slab_wider_than_capacity() {
14061 use fuel_ir::{DynScalar, SymId};
14062 // dest capacity on axis 0 is 2, but the dynamic-axis slab is
14063 // width 4 — can never fit regardless of the runtime offset.
14064 let dest =
14065 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14066 let src = dest
14067 .const_f32_like(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]))
14068 .unwrap();
14069 let err = dest.write_slice_dyn(&src, vec![(0, 4), (0, 3)], 0, DynScalar::Sym(SymId(0)));
14070 assert!(
14071 err.is_err(),
14072 "dynamic-axis slab wider than capacity must error at build"
14073 );
14074 }
14075
14076 #[test]
14077 fn write_slice_dyn_rejects_axis_out_of_bounds() {
14078 use fuel_ir::{DynScalar, SymId};
14079 let dest =
14080 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14081 let src = dest
14082 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14083 .unwrap();
14084 let err = dest.write_slice_dyn(&src, vec![(0, 1), (0, 3)], 5, DynScalar::Sym(SymId(0)));
14085 assert!(err.is_err(), "dyn_axis past rank must error");
14086 }
14087
14088 #[test]
14089 fn flash_attn_dyn_records_runtime_k_len() {
14090 use fuel_ir::{DynScalar, SymId};
14091 // q [1, 2, 3, 4]; K/V capacity [1, 1, 8, 4] (GQA Hq=2, Hkv=1).
14092 let q = NodeHandle::from_f32(
14093 vec![0.0_f32; 2 * 3 * 4],
14094 Shape::from_dims(&[1, 2, 3, 4]),
14095 cpu_dev(),
14096 )
14097 .unwrap();
14098 let k = q
14099 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14100 .unwrap();
14101 let v = q
14102 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14103 .unwrap();
14104 let sym = SymId(0);
14105 let out = q.flash_attn_dyn(
14106 &k,
14107 &v,
14108 None,
14109 /*scale*/ 0.5,
14110 /*causal*/ true,
14111 None,
14112 None,
14113 None,
14114 DynScalar::Sym(sym),
14115 );
14116 // Output adopts q's shape, not the capacity.
14117 assert_eq!(out.shape().dims(), &[1, 2, 3, 4]);
14118 let g = out.graph().read().unwrap();
14119 match &g.node(out.id()).op {
14120 Op::Fused(fid, crate::registry::FusedOpParams::FlashAttn { causal, k_len, .. })
14121 if *fid == crate::registry::FusedOps::FLASH_ATTN =>
14122 {
14123 assert!(*causal);
14124 assert_eq!(k_len, &Some(DynScalar::Sym(sym)));
14125 }
14126 other => panic!("expected Op::Fused(FLASH_ATTN, FlashAttn), got {other:?}"),
14127 }
14128 assert_eq!(g.node(out.id()).inputs, vec![q.id(), k.id(), v.id()]);
14129 }
14130
14131 #[test]
14132 #[should_panic(expected = "k_len")]
14133 fn flash_attn_dyn_concrete_k_len_exceeding_capacity_panics() {
14134 use fuel_ir::DynScalar;
14135 let q = NodeHandle::from_f32(
14136 vec![0.0_f32; 2 * 4],
14137 Shape::from_dims(&[1, 1, 2, 4]),
14138 cpu_dev(),
14139 )
14140 .unwrap();
14141 let k = q
14142 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14143 .unwrap();
14144 let v = q
14145 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14146 .unwrap();
14147 // Concrete k_len=5 > capacity 4 → build-time panic.
14148 let _ = q.flash_attn_dyn(
14149 &k,
14150 &v,
14151 None,
14152 1.0,
14153 true,
14154 None,
14155 None,
14156 None,
14157 DynScalar::Concrete(5),
14158 );
14159 }
14160
14161 #[test]
14162 fn write_slice_rejects_rank_mismatch() {
14163 let dest =
14164 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14165 let src = dest
14166 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
14167 .unwrap();
14168 // ranges has rank 2 (matches dest) but source has rank 1.
14169 let err = dest.write_slice(&src, vec![(0, 1), (0, 3)]);
14170 assert!(err.is_err(), "rank mismatch must error");
14171 }
14172
14173 // ---- cross-graph operands must fail at BUILD time, never hang -----------
14174 //
14175 // Node ids are indices into ONE graph's arena, so an operand built on a
14176 // DIFFERENT graph records an id that indexes an unrelated node (or none),
14177 // producing a malformed dependency graph. The failure surfaces as neither
14178 // a panic nor an error: the executor **HANGS at realize**, waiting on a
14179 // dependency that can never resolve — low CPU, no stack, no message. That
14180 // is strictly worse than a panic, and it violates two rules at once:
14181 // "validate at graph-build time" and never-hang.
14182 //
14183 // `matmul`, `qmatmul`, `conv2d`, `paged_attn`, and everything routed via
14184 // `binary_op` already assert this. These builders did not — a real cost: a
14185 // peer session spent a long bisect localizing exactly this on `write_slice`.
14186 //
14187 // These tests only BUILD, never realize, so before the fix they fail fast
14188 // instead of hanging the suite.
14189
14190 #[test]
14191 fn write_slice_rejects_cross_graph_source() {
14192 let dest =
14193 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14194 // A SECOND `from_*` mints a second graph — the easy mistake to make,
14195 // and currently the un-diagnosable one.
14196 let foreign =
14197 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]), cpu_dev())
14198 .unwrap();
14199 assert_ne!(
14200 dest.graph_id(),
14201 foreign.graph_id(),
14202 "fixture must be cross-graph"
14203 );
14204
14205 let err = dest.write_slice(&foreign, vec![(2, 3), (0, 3)]);
14206 assert!(
14207 err.is_err(),
14208 "cross-graph source must be a build-time Err, not a realize-time hang",
14209 );
14210 let msg = format!("{}", err.unwrap_err());
14211 assert!(
14212 msg.contains("same graph"),
14213 "error should say the operands must share a graph, got: {msg}",
14214 );
14215 }
14216
14217 #[test]
14218 fn masked_fill_rejects_cross_graph_mask() {
14219 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14220 let foreign_mask =
14221 NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14222 assert_ne!(
14223 x.graph_id(),
14224 foreign_mask.graph_id(),
14225 "fixture must be cross-graph"
14226 );
14227
14228 let err = x.masked_fill(&foreign_mask, Scalar::F32(0.0));
14229 assert!(
14230 err.is_err(),
14231 "cross-graph mask must be a build-time Err, not a realize-time hang",
14232 );
14233 // MUST assert the reason, not just is_err(): this fixture also has a
14234 // dtype mismatch, so a bare `is_err()` passes for the WRONG reason and
14235 // would stay green even with no graph check at all.
14236 let msg = format!("{}", err.unwrap_err());
14237 assert!(
14238 msg.contains("same graph"),
14239 "must fail on GRAPH affinity, not incidentally on dtype, got: {msg}",
14240 );
14241 }
14242
14243 #[test]
14244 fn masked_fill_rejects_scale_dtype_at_build() {
14245 // F8E8M0 is a block-scale dtype: it HAS a scalar value (so the
14246 // value-dtype check passes) but no zero, so the MaskedFill backward
14247 // cannot produce a gradient. Reject at build time — and this must fail
14248 // on the dtype guard specifically: graph / shape / mask-Bool / value-dtype
14249 // are all satisfied, so a bare `is_err()` can only be the guard firing.
14250 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14251 let scale = x.cast(DType::F8E8M0);
14252 let mask = x.cast(DType::Bool);
14253 let value = Scalar::one(DType::F8E8M0).unwrap();
14254
14255 let err = scale.masked_fill(&mask, value);
14256 assert!(
14257 err.is_err(),
14258 "masked_fill on a scale dtype must be a build-time Err"
14259 );
14260 let msg = format!("{}", err.unwrap_err());
14261 assert!(
14262 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14263 "must fail on the packed/scale dtype guard, got: {msg}",
14264 );
14265 }
14266
14267 /// GAP-075 fix B: pin the REJECT verdict for every unfillable dtype
14268 /// individually (not a bucket count). The guard is semantic — packed
14269 /// formats (F4/F6*) have no representable fill value; block-scales
14270 /// (F8E8M0/F8E6M2) have no zero for the zero-filling backward — so each must
14271 /// be a build-time Err on the dtype GUARD specifically (its message names
14272 /// the op). Per-dtype pinning protects the classification: a future dtype
14273 /// misfiled into the allow arm can't hide behind a passing tally, and a new
14274 /// dtype with no verdict is caught by the compiler (the match is exhaustive,
14275 /// no wildcard). Paired with the allow test below (opposite assertion), the
14276 /// two are mutually non-vacuous.
14277 #[test]
14278 fn masked_fill_rejects_every_unfillable_dtype() {
14279 for dt in [
14280 DType::F4,
14281 DType::F6E2M3,
14282 DType::F6E3M2,
14283 DType::F8E8M0,
14284 DType::F8E6M2,
14285 ] {
14286 let x =
14287 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14288 let t = x.cast(dt);
14289 let mask = x.cast(DType::Bool);
14290 // The dtype guard fires before the value-dtype check, so a dummy
14291 // value is fine; the message assertion proves it was the guard.
14292 let err = t.masked_fill(&mask, Scalar::F32(0.0));
14293 assert!(err.is_err(), "masked_fill must reject {dt:?} at build time");
14294 let msg = format!("{}", err.unwrap_err());
14295 assert!(
14296 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14297 "{dt:?} must fail on the semantic dtype guard, got: {msg}",
14298 );
14299 }
14300 }
14301
14302 /// GAP-075 fix B: the allow arm is a graph-build PERMISSION (masked_fill is
14303 /// semantically well-defined — a fill value + a zero), NOT a claim a backend
14304 /// can allocate/run the dtype. F32 is the live consumer path (attention
14305 /// masking); I32 is an allowed verdict no consumer currently exercises —
14306 /// locking it preserves today's answer without asserting integer masked_fill
14307 /// is known to compute correctly (a backend lacking I32 storage still
14308 /// declines loudly at allocation, downstream of this permission).
14309 #[test]
14310 fn masked_fill_permits_fillable_dtypes_as_permission_not_capability() {
14311 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14312 let mask = x.cast(DType::Bool);
14313 assert!(
14314 x.masked_fill(&mask, Scalar::F32(0.0)).is_ok(),
14315 "F32 masked_fill must build (the live consumer path)",
14316 );
14317 let xi = x.cast(DType::I32);
14318 assert!(
14319 xi.masked_fill(&mask, Scalar::one(DType::I32).unwrap())
14320 .is_ok(),
14321 "I32 masked_fill must build — permission preserved, not a correctness claim",
14322 );
14323 }
14324
14325 #[test]
14326 #[should_panic(expected = "same graph")]
14327 fn rope_with_tables_panics_on_cross_graph_tables() {
14328 // Returns `NodeHandle`, so it follows the convention of the already-checked
14329 // builders (`matmul`, `paged_attn`) and asserts. A panic names the
14330 // problem at the build site; the status quo hangs later saying nothing.
14331 let x = NodeHandle::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[1, 1, 2, 4]), cpu_dev())
14332 .unwrap();
14333 let cos =
14334 NodeHandle::from_f32(vec![1.0_f32; 8], Shape::from_dims(&[2, 4]), cpu_dev()).unwrap();
14335 let sin = x
14336 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]))
14337 .unwrap();
14338 let _ = x.rope_with_tables(&cos, &sin);
14339 }
14340
14341 #[test]
14342 fn write_slice_rejects_slab_width_mismatch() {
14343 let dest =
14344 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14345 // Source has 2 elements along axis 0, but slab is width 1.
14346 let src = dest
14347 .const_f32_like(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]))
14348 .unwrap();
14349 let err = dest.write_slice(&src, vec![(2, 3), (0, 3)]);
14350 assert!(err.is_err(), "slab-width mismatch must error");
14351 }
14352
14353 #[test]
14354 fn write_slice_rejects_range_past_dest_extent() {
14355 let dest =
14356 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14357 let src = dest
14358 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14359 .unwrap();
14360 // axis 0: dest extent is 4; range [4, 5) is out of bounds.
14361 let err = dest.write_slice(&src, vec![(4, 5), (0, 3)]);
14362 assert!(err.is_err(), "range past dest extent must error");
14363 }
14364
14365 #[test]
14366 fn write_slice_derives_ordering_after_other_readers() {
14367 // Graph:
14368 // dest = ...; src = ...
14369 // ro = dest.relu() (non-destructive reader of dest)
14370 // w = dest.write_slice(&src, [(0,1),(0,3)]) (destructive on dest)
14371 // Expected ordering: w must run after ro.
14372 let dest =
14373 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14374 let src = dest
14375 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14376 .unwrap();
14377 let ro = dest.relu();
14378 let w = dest.write_slice(&src, vec![(0, 1), (0, 3)]).unwrap();
14379 let ord = crate::opt::derive_ordering(&dest.graph().read().unwrap(), &[ro.id(), w.id()]);
14380 let deps = ord.deps_of(w.id());
14381 assert_eq!(
14382 deps.len(),
14383 1,
14384 "write_slice should have one ordering dep (the relu)"
14385 );
14386 assert_eq!(
14387 deps[0],
14388 ro.id(),
14389 "write_slice must run after the non-destructive reader"
14390 );
14391 }
14392
14393 // ---- In-place ops Phase 1 -----------------------------------------------
14394 //
14395 // Smoke tests for the 5 new in-place unary variants
14396 // (`Op::ReluInplace`, `Op::SiluInplace`, `Op::GeluTanhInplace`,
14397 // `Op::TanhInplace`, `Op::SigmoidInplace`) and `FusedOps::INPLACE_AFFINE`.
14398 // Phase 1 only ships the structural plumbing (Op IR + destructive_input +
14399 // short_name + scheduler integration); dispatch + autograd land in Phases
14400 // 3 + 4. See `docs/session-prompts/in-place-ops-infrastructure.md`.
14401
14402 #[test]
14403 fn inplace_unary_destructive_input_is_zero() {
14404 for op in [
14405 Op::ReluInplace,
14406 Op::SiluInplace,
14407 Op::GeluTanhInplace,
14408 Op::TanhInplace,
14409 Op::SigmoidInplace,
14410 Op::NegInplace,
14411 Op::AbsInplace,
14412 Op::SqrInplace,
14413 Op::SqrtInplace,
14414 Op::RsqrtInplace,
14415 Op::RecipInplace,
14416 Op::ExpInplace,
14417 Op::LogInplace,
14418 Op::SinInplace,
14419 Op::CosInplace,
14420 Op::SignInplace,
14421 Op::FloorInplace,
14422 Op::CeilInplace,
14423 Op::RoundInplace,
14424 Op::ErfInplace,
14425 Op::GeluInplace,
14426 ] {
14427 assert_eq!(
14428 op.destructive_input(),
14429 Some(0),
14430 "in-place unary {op:?} must declare input 0 destructive",
14431 );
14432 }
14433 }
14434
14435 #[test]
14436 fn inplace_unary_short_names_round_trip() {
14437 assert_eq!(Op::ReluInplace.short_name(), "ReluInplace");
14438 assert_eq!(Op::SiluInplace.short_name(), "SiluInplace");
14439 assert_eq!(Op::GeluTanhInplace.short_name(), "GeluTanhInplace");
14440 assert_eq!(Op::TanhInplace.short_name(), "TanhInplace");
14441 assert_eq!(Op::SigmoidInplace.short_name(), "SigmoidInplace");
14442 assert_eq!(Op::NegInplace.short_name(), "NegInplace");
14443 assert_eq!(Op::AbsInplace.short_name(), "AbsInplace");
14444 assert_eq!(Op::SqrInplace.short_name(), "SqrInplace");
14445 assert_eq!(Op::SqrtInplace.short_name(), "SqrtInplace");
14446 assert_eq!(Op::RsqrtInplace.short_name(), "RsqrtInplace");
14447 assert_eq!(Op::RecipInplace.short_name(), "RecipInplace");
14448 assert_eq!(Op::ExpInplace.short_name(), "ExpInplace");
14449 assert_eq!(Op::LogInplace.short_name(), "LogInplace");
14450 assert_eq!(Op::SinInplace.short_name(), "SinInplace");
14451 assert_eq!(Op::CosInplace.short_name(), "CosInplace");
14452 assert_eq!(Op::SignInplace.short_name(), "SignInplace");
14453 assert_eq!(Op::FloorInplace.short_name(), "FloorInplace");
14454 assert_eq!(Op::CeilInplace.short_name(), "CeilInplace");
14455 assert_eq!(Op::RoundInplace.short_name(), "RoundInplace");
14456 assert_eq!(Op::ErfInplace.short_name(), "ErfInplace");
14457 assert_eq!(Op::GeluInplace.short_name(), "GeluInplace");
14458 assert_eq!(
14459 Op::ClampInplace { min: 0.0, max: 1.0 }.short_name(),
14460 "ClampInplace"
14461 );
14462 assert_eq!(Op::PowIInplace(3).short_name(), "PowIInplace");
14463 }
14464
14465 #[test]
14466 fn inplace_affine_fused_op_destructive_input_is_zero() {
14467 let op = Op::Fused(
14468 crate::registry::FusedOps::INPLACE_AFFINE,
14469 crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 },
14470 );
14471 assert_eq!(op.destructive_input(), Some(0));
14472 }
14473
14474 #[test]
14475 fn destructive_input_for_fused_is_registry_declared() {
14476 // GAP-076: a fused op's destructiveness is a MANDATORY declared field on
14477 // its registry entry, and `Op::destructive_input` reads that field via
14478 // `default_registry()` rather than a hardcoded id match that could drift
14479 // out of sync. This locks BOTH directions of the declaration plus the
14480 // routing that reads it. Regression lock, not a born-red: no op was
14481 // misclassified before the fix — its value is that a future wrong
14482 // declaration (or a reverted routing) reddens HERE instead of surfacing
14483 // as an intermittent scheduler data race that points nowhere near this
14484 // code. The exhaustive match in `Op::destructive_input` and the
14485 // mandatory struct field are the compile-time seams; this is the belt.
14486 use crate::registry::{FusedOps, default_registry};
14487 let reg = default_registry();
14488 assert_eq!(
14489 reg.entry(FusedOps::INPLACE_AFFINE)
14490 .expect("INPLACE_AFFINE is registered")
14491 .destructive_input,
14492 Some(0),
14493 "InplaceAffine must declare itself destructive on input 0",
14494 );
14495 assert_eq!(
14496 reg.entry(FusedOps::SOFTMAX_LAST_DIM)
14497 .expect("SOFTMAX_LAST_DIM is registered")
14498 .destructive_input,
14499 None,
14500 "a functional fused op must declare itself non-destructive",
14501 );
14502 // Routing reads the declared field (not a hardcoded id match).
14503 let op = Op::Fused(
14504 FusedOps::INPLACE_AFFINE,
14505 crate::registry::FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 },
14506 );
14507 assert_eq!(op.destructive_input(), Some(0));
14508 }
14509
14510 #[test]
14511 fn inplace_affine_params_key_dedupe_on_same_mul_add() {
14512 // Two `InplaceAffine` params with identical (mul, add) hash to the
14513 // same key; differing values produce distinct keys. Lets CSE / the
14514 // existing op_key infrastructure collapse identical in-place affines
14515 // (when callers wire them through the equivalent graph machinery).
14516 let a = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14517 let b = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14518 let c = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 0.5 };
14519 assert_eq!(a.key(), b.key(), "identical mul/add must dedupe");
14520 assert_ne!(a.key(), c.key(), "different add must produce distinct key");
14521 }
14522
14523 // ---- Phase 4 — autograd through in-place ops ----
14524 //
14525 // The view-aware `derive_ordering` (Phase 4a) ensures backward
14526 // grad nodes that read forward inputs run BEFORE any in-place
14527 // mutation of those inputs. The backward arms in
14528 // `NodeHandle::backward` (Phase 4b) emit the same gradient graph as
14529 // the non-inplace cousins. These tests prove that calling
14530 // `.backward()` through an in-place node:
14531 // (1) does NOT panic (was previously guarded by the Phase 1
14532 // defensive panic);
14533 // (2) emits the same gradient-node structure as the non-inplace
14534 // cousin (matching node counts + op types as a structural
14535 // proxy for numerical equivalence — the actual numerics are
14536 // exercised by the live oracle tests in fuel-storage).
14537
14538 #[test]
14539 fn backward_through_relu_inplace_does_not_panic() {
14540 // y = x.relu_inplace(); loss = y.sum_all(); loss.backward()
14541 // Phase 1's defensive panic is removed; backward emits
14542 // Op::Step(x) + Op::Mul(upstream, step) — same as Op::Relu.
14543 let x =
14544 NodeHandle::from_f32(vec![1.0, -2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14545 let y = x.relu_inplace();
14546 let loss = y.sum_all();
14547 let grads = loss.backward();
14548 let g_x = grads.get(&x).expect("gradient for x should be present");
14549 // Same structural form as Op::Relu's backward: gradient node
14550 // is an Op::Mul (upstream × step(x)).
14551 let g_node = g_x.graph().read().unwrap().node(g_x.id()).clone();
14552 assert!(
14553 matches!(g_node.op, Op::Mul),
14554 "relu backward grad is Mul; got {:?}",
14555 g_node.op
14556 );
14557 }
14558
14559 #[test]
14560 fn backward_through_sigmoid_inplace_does_not_panic() {
14561 let x = NodeHandle::from_f32(vec![0.5, -0.5], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14562 let y = x.sigmoid_inplace();
14563 let loss = y.sum_all();
14564 let grads = loss.backward();
14565 let g_x = grads.get(&x);
14566 assert!(g_x.is_some());
14567 }
14568
14569 #[test]
14570 fn backward_through_tanh_inplace_does_not_panic() {
14571 let x =
14572 NodeHandle::from_f32(vec![0.1, 0.2, 0.3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14573 let y = x.tanh_inplace();
14574 let loss = y.sum_all();
14575 let grads = loss.backward();
14576 let g_x = grads.get(&x);
14577 assert!(g_x.is_some());
14578 }
14579
14580 #[test]
14581 fn backward_through_silu_inplace_does_not_panic() {
14582 let x = NodeHandle::from_f32(vec![0.1, 0.2], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14583 let y = x.silu_inplace();
14584 let loss = y.sum_all();
14585 let grads = loss.backward();
14586 let g_x = grads.get(&x);
14587 assert!(g_x.is_some());
14588 }
14589
14590 #[test]
14591 fn backward_through_gelu_inplace_panics_matching_op_gelu() {
14592 // GeluTanhInplace mirrors Op::GeluTanh's "currently inference-only"
14593 // panic — both rely on the same not-yet-implemented gradient.
14594 // SiluInplace is the recommended differentiable alternative.
14595 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14596 let y = x.gelu_tanh_inplace();
14597 let loss = y.sum_all();
14598 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| loss.backward()));
14599 assert!(
14600 result.is_err(),
14601 "GeluTanhInplace backward should panic (mirrors Op::GeluTanh)"
14602 );
14603 }
14604
14605 #[test]
14606 fn backward_through_relu_inplace_emits_same_graph_shape_as_functional() {
14607 // Structural parity: relu_inplace backward emits the same node
14608 // count + same op variants as relu backward, since the
14609 // gradient formula is identical.
14610 let x_inp =
14611 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14612 let y_inp = x_inp.relu_inplace();
14613 let loss_inp = y_inp.sum_all();
14614 let nodes_before_inp = loss_inp.graph().read().unwrap().len();
14615 let _ = loss_inp.backward();
14616 let added_inp = loss_inp.graph().read().unwrap().len() - nodes_before_inp;
14617
14618 let x_fn =
14619 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14620 let y_fn = x_fn.relu();
14621 let loss_fn = y_fn.sum_all();
14622 let nodes_before_fn = loss_fn.graph().read().unwrap().len();
14623 let _ = loss_fn.backward();
14624 let added_fn = loss_fn.graph().read().unwrap().len() - nodes_before_fn;
14625
14626 assert_eq!(
14627 added_inp, added_fn,
14628 "ReluInplace backward should add the same number of nodes as Relu backward ({added_fn}), got {added_inp}",
14629 );
14630 }
14631
14632 #[test]
14633 fn relu_inplace_builder_emits_op_reluinplace() {
14634 let x = NodeHandle::from_f32(
14635 vec![1.0_f32, -1.0, 2.0, -2.0],
14636 Shape::from_dims(&[4]),
14637 cpu_dev(),
14638 )
14639 .unwrap();
14640 let y = x.relu_inplace();
14641 let g = y.graph().read().unwrap();
14642 let node = g.node(y.id());
14643 assert!(matches!(node.op, Op::ReluInplace));
14644 assert_eq!(node.inputs, vec![x.id()]);
14645 assert_eq!(node.shape.dims(), &[4]);
14646 assert_eq!(node.dtype, DType::F32);
14647 }
14648
14649 #[test]
14650 fn affine_inplace_builder_emits_fused_inplace_affine() {
14651 let x = NodeHandle::from_f32(
14652 vec![1.0_f32, 2.0, 3.0, 4.0],
14653 Shape::from_dims(&[4]),
14654 cpu_dev(),
14655 )
14656 .unwrap();
14657 let y = x.affine_inplace(2.0, 0.5);
14658 let g = y.graph().read().unwrap();
14659 let node = g.node(y.id());
14660 match &node.op {
14661 Op::Fused(id, crate::registry::FusedOpParams::InplaceAffine { mul, add }) => {
14662 assert_eq!(*id, crate::registry::FusedOps::INPLACE_AFFINE);
14663 assert_eq!(*mul, 2.0);
14664 assert_eq!(*add, 0.5);
14665 }
14666 other => panic!("expected Op::Fused(INPLACE_AFFINE, InplaceAffine), got {other:?}"),
14667 }
14668 assert_eq!(node.inputs, vec![x.id()]);
14669 assert_eq!(node.shape.dims(), &[4]);
14670 }
14671
14672 #[test]
14673 fn all_inplace_unary_builders_round_trip_through_op_variants() {
14674 // One smoke per variant — each builder emits exactly the
14675 // matching `Op::*Inplace` variant, single input, shape +
14676 // dtype unchanged.
14677 let x = NodeHandle::from_f32(vec![0.5_f32; 8], Shape::from_dims(&[8]), cpu_dev()).unwrap();
14678 fn check(y: NodeHandle, x_id: NodeId, expect: fn(&Op) -> bool) {
14679 let g = y.graph().read().unwrap();
14680 let node = g.node(y.id());
14681 assert!(expect(&node.op), "wrong Op variant: {:?}", node.op);
14682 assert_eq!(node.inputs, vec![x_id]);
14683 assert_eq!(node.shape.dims(), &[8]);
14684 assert_eq!(node.dtype, DType::F32);
14685 }
14686 check(x.relu_inplace(), x.id(), |o| matches!(o, Op::ReluInplace));
14687 check(x.silu_inplace(), x.id(), |o| matches!(o, Op::SiluInplace));
14688 check(x.gelu_tanh_inplace(), x.id(), |o| {
14689 matches!(o, Op::GeluTanhInplace)
14690 });
14691 check(x.tanh_inplace(), x.id(), |o| matches!(o, Op::TanhInplace));
14692 check(x.sigmoid_inplace(), x.id(), |o| {
14693 matches!(o, Op::SigmoidInplace)
14694 });
14695 check(x.neg_inplace(), x.id(), |o| matches!(o, Op::NegInplace));
14696 check(x.abs_inplace(), x.id(), |o| matches!(o, Op::AbsInplace));
14697 check(x.sqr_inplace(), x.id(), |o| matches!(o, Op::SqrInplace));
14698 check(x.sqrt_inplace(), x.id(), |o| matches!(o, Op::SqrtInplace));
14699 check(x.rsqrt_inplace(), x.id(), |o| matches!(o, Op::RsqrtInplace));
14700 check(x.recip_inplace(), x.id(), |o| matches!(o, Op::RecipInplace));
14701 check(x.exp_inplace(), x.id(), |o| matches!(o, Op::ExpInplace));
14702 check(x.log_inplace(), x.id(), |o| matches!(o, Op::LogInplace));
14703 check(x.sin_inplace(), x.id(), |o| matches!(o, Op::SinInplace));
14704 check(x.cos_inplace(), x.id(), |o| matches!(o, Op::CosInplace));
14705 check(x.sign_inplace(), x.id(), |o| matches!(o, Op::SignInplace));
14706 check(x.floor_inplace(), x.id(), |o| matches!(o, Op::FloorInplace));
14707 check(x.ceil_inplace(), x.id(), |o| matches!(o, Op::CeilInplace));
14708 check(x.round_inplace(), x.id(), |o| matches!(o, Op::RoundInplace));
14709 check(x.erf_inplace(), x.id(), |o| matches!(o, Op::ErfInplace));
14710 check(x.gelu_inplace(), x.id(), |o| matches!(o, Op::GeluInplace));
14711 check(x.clamp_inplace(-1.0, 1.0), x.id(), |o| {
14712 matches!(o, Op::ClampInplace { .. })
14713 });
14714 check(x.powi_inplace(3), x.id(), |o| {
14715 matches!(o, Op::PowIInplace(3))
14716 });
14717 }
14718
14719 /// Backward smoke for the expanded in-place op family — each variant
14720 /// (except zero-grad ones) must produce a gradient node for x without
14721 /// panicking. Zero-grad variants (Sign/Floor/Ceil/Round) drop the
14722 /// gradient entirely (no entry in the GradMap), mirroring their
14723 /// non-inplace cousins.
14724 #[test]
14725 fn backward_through_expanded_inplace_unary_emits_grad() {
14726 fn check_emits_grad(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14727 let x =
14728 NodeHandle::from_f32(vec![0.5_f32, 1.5, 2.5], Shape::from_dims(&[3]), cpu_dev())
14729 .unwrap();
14730 let y = make(&x);
14731 let loss = y.sum_all();
14732 let grads = loss.backward();
14733 assert!(grads.get(&x).is_some(), "backward must emit gradient for x");
14734 }
14735 check_emits_grad(|x| x.neg_inplace());
14736 check_emits_grad(|x| x.abs_inplace());
14737 check_emits_grad(|x| x.sqr_inplace());
14738 check_emits_grad(|x| x.sqrt_inplace());
14739 check_emits_grad(|x| x.rsqrt_inplace());
14740 check_emits_grad(|x| x.recip_inplace());
14741 check_emits_grad(|x| x.exp_inplace());
14742 check_emits_grad(|x| x.log_inplace());
14743 check_emits_grad(|x| x.sin_inplace());
14744 check_emits_grad(|x| x.cos_inplace());
14745 check_emits_grad(|x| x.erf_inplace());
14746 check_emits_grad(|x| x.gelu_inplace());
14747 check_emits_grad(|x| x.clamp_inplace(-1.0, 2.0));
14748 check_emits_grad(|x| x.powi_inplace(3));
14749 }
14750
14751 #[test]
14752 fn backward_through_zero_grad_inplace_drops_gradient() {
14753 fn check_drops(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14754 let x =
14755 NodeHandle::from_f32(vec![1.5_f32, 2.5, -3.5], Shape::from_dims(&[3]), cpu_dev())
14756 .unwrap();
14757 let y = make(&x);
14758 let loss = y.sum_all();
14759 let grads = loss.backward();
14760 assert!(
14761 grads.get(&x).is_none(),
14762 "zero-grad in-place op must not emit gradient"
14763 );
14764 }
14765 check_drops(|x| x.sign_inplace());
14766 check_drops(|x| x.floor_inplace());
14767 check_drops(|x| x.ceil_inplace());
14768 check_drops(|x| x.round_inplace());
14769 }
14770
14771 #[test]
14772 fn inplace_unary_derives_ordering_after_non_destructive_readers() {
14773 // Graph:
14774 // x = const f32 [4]
14775 // y_a = x.relu() (non-destructive reader of x)
14776 // y_b = manually-pushed Op::ReluInplace on x (destructive)
14777 // Expected: y_b must run after y_a.
14778 let x = NodeHandle::from_f32(
14779 vec![1.0_f32, -1.0, 2.0, -2.0],
14780 Shape::from_dims(&[4]),
14781 cpu_dev(),
14782 )
14783 .unwrap();
14784 let y_a = x.relu();
14785 let y_b_id = x.graph().write().unwrap().push(Node {
14786 op: Op::ReluInplace,
14787 inputs: vec![x.id()],
14788 shape: Shape::from_dims(&[4]),
14789 dtype: DType::F32,
14790 });
14791 let ord = crate::opt::derive_ordering(&x.graph().read().unwrap(), &[y_a.id(), y_b_id]);
14792 let deps = ord.deps_of(y_b_id);
14793 assert_eq!(deps.len(), 1, "in-place unary should have one ordering dep");
14794 assert_eq!(
14795 deps[0],
14796 y_a.id(),
14797 "in-place unary must run after the non-destructive reader"
14798 );
14799 }
14800
14801 // ------------------------------------------------------------------
14802 // Multi-output nodes (Option C, Session 1)
14803 // ------------------------------------------------------------------
14804
14805 use fuel_backend_contract::storage::Storage as CoreStorage;
14806 use fuel_ir::storage::OutputView;
14807
14808 /// Build a real CPU `Storage` of `n` F32 zeros so `Storage`-level
14809 /// tests can attach + read bundle metadata against a live backend
14810 /// allocator. The dtype is fixed at F32 because every existing
14811 /// `OutputView` test below uses F32 for slot 0; bundle dtype is
14812 /// validated at `with_bundle` time against this primary dtype.
14813 fn cpu_f32_storage(n: usize) -> CoreStorage {
14814 let dev = cpu_dev();
14815 let buf = fuel_ir::HostBuffer::F32(vec![0.0_f32; n]);
14816 let inner = dev
14817 .storage_from_host_buffer_owned_dyn(buf)
14818 .expect("test fixture: F32 storage_from_host_buffer_owned_dyn failed");
14819 CoreStorage::from_dyn(inner)
14820 }
14821
14822 /// Build a 2-slot bundle: slot 0 `[2, 3]` F32 `y`-shape, slot 1
14823 /// `[2, 4]` F32 `last_state`-shape. Returns the views and the
14824 /// total element count (used to size the backing CPU buffer so
14825 /// slot 1's byte range stays inside the bundle's bytes).
14826 fn two_slot_views() -> (Vec<OutputView>, usize) {
14827 let s0 = Shape::from_dims(&[2, 3]);
14828 let s1 = Shape::from_dims(&[2, 4]);
14829 let v0 = OutputView {
14830 byte_offset: 0,
14831 len_elements: s0.elem_count(),
14832 dtype: DType::F32,
14833 shape: s0.clone(),
14834 layout: Layout::contiguous(s0),
14835 name: Some("y"),
14836 };
14837 let v1 = OutputView {
14838 byte_offset: v0.len_bytes(),
14839 len_elements: s1.elem_count(),
14840 dtype: DType::F32,
14841 shape: s1.clone(),
14842 layout: Layout::contiguous(s1),
14843 name: Some("last_state"),
14844 };
14845 let total = v0.len_elements + v1.len_elements;
14846 (vec![v0, v1], total)
14847 }
14848
14849 /// `Storage::is_bundled` is false by default; `slot_count` is 1;
14850 /// `bundle` / `bundle_arc` / `slot_view` / `slot_dtype` all return
14851 /// `None` for the non-multi-output case.
14852 #[test]
14853 fn storage_single_output_defaults() {
14854 let s = cpu_f32_storage(8);
14855 assert!(!s.is_bundled());
14856 assert_eq!(s.slot_count(), 1);
14857 assert!(s.bundle().is_none());
14858 assert!(s.bundle_arc().is_none());
14859 assert!(s.slot_view(0).is_none());
14860 assert_eq!(s.slot_dtype(0), None);
14861 assert_eq!(s.primary_dtype(), DType::F32);
14862 assert_eq!(s.dtype(), DType::F32);
14863 }
14864
14865 /// `Storage::with_bundle` attaches the side-table and per-slot
14866 /// lookups report the declared shape/dtype.
14867 #[test]
14868 fn storage_with_bundle_attaches_views() {
14869 let (views, total) = two_slot_views();
14870 let s = cpu_f32_storage(total)
14871 .with_bundle(views.clone().into())
14872 .expect("with_bundle should accept matching slot-0 dtype");
14873 assert!(s.is_bundled());
14874 assert_eq!(s.slot_count(), 2);
14875 let slot0 = s.slot_view(0).unwrap();
14876 assert_eq!(slot0.shape, Shape::from_dims(&[2, 3]));
14877 assert_eq!(slot0.dtype, DType::F32);
14878 assert_eq!(slot0.byte_offset, 0);
14879 assert_eq!(slot0.name, Some("y"));
14880 let slot1 = s.slot_view(1).unwrap();
14881 assert_eq!(slot1.shape, Shape::from_dims(&[2, 4]));
14882 assert_eq!(slot1.byte_offset, 24); // 6 F32s = 24 bytes
14883 assert_eq!(slot1.name, Some("last_state"));
14884 // Out-of-range slot reads `None`, doesn't panic.
14885 assert!(s.slot_view(2).is_none());
14886 assert_eq!(s.slot_dtype(2), None);
14887 }
14888
14889 /// `Storage::with_bundle` rejects an empty bundle slice (a
14890 /// zero-slot bundle is a contract bug — use a single-output
14891 /// Storage if there's nothing to project).
14892 #[test]
14893 fn storage_with_bundle_rejects_empty() {
14894 let s = cpu_f32_storage(1);
14895 let empty: Arc<[OutputView]> = Arc::from(Vec::<OutputView>::new().into_boxed_slice());
14896 let err = s
14897 .with_bundle(empty)
14898 .expect_err("empty bundle slice must error");
14899 let msg = format!("{err}");
14900 assert!(msg.contains("non-empty"), "error message: {msg}");
14901 }
14902
14903 /// `Storage::with_bundle` rejects slot 0 dtype that disagrees with
14904 /// the inner backend dtype — the bundle invariant "slot 0 dtype ==
14905 /// primary_dtype()" must hold.
14906 #[test]
14907 fn storage_with_bundle_rejects_dtype_mismatch() {
14908 let s = cpu_f32_storage(8);
14909 let bad = OutputView {
14910 byte_offset: 0,
14911 len_elements: 4,
14912 dtype: DType::F64,
14913 shape: Shape::from_dims(&[2, 2]),
14914 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
14915 name: None,
14916 };
14917 let err = s
14918 .with_bundle(Arc::from(vec![bad].into_boxed_slice()))
14919 .expect_err("slot 0 dtype mismatch must error");
14920 let msg = format!("{err}");
14921 assert!(msg.contains("dtype"), "error message: {msg}");
14922 }
14923
14924 /// `Graph::output_views` is `None` for ordinary single-output
14925 /// nodes; `multi_output_count` is 0.
14926 #[test]
14927 fn graph_output_views_defaults() {
14928 let mut g = Graph::new();
14929 let id = g.push(Node {
14930 op: Op::Const,
14931 inputs: vec![],
14932 shape: Shape::from_dims(&[2, 3]),
14933 dtype: DType::F32,
14934 });
14935 assert!(g.output_views(id).is_none());
14936 assert!(!g.is_multi_output(id));
14937 assert_eq!(g.multi_output_count(), 0);
14938 }
14939
14940 /// `Graph::set_output_views` round-trips: read returns what was
14941 /// written; `is_multi_output` flips.
14942 #[test]
14943 fn graph_set_output_views_roundtrip() {
14944 let mut g = Graph::new();
14945 let id = g.push(Node {
14946 op: Op::Const,
14947 inputs: vec![],
14948 shape: Shape::from_dims(&[2, 3]),
14949 dtype: DType::F32,
14950 });
14951 let (views, _) = two_slot_views();
14952 g.set_output_views(id, views.clone().into())
14953 .expect("valid 2-slot specs");
14954 assert!(g.is_multi_output(id));
14955 assert_eq!(g.multi_output_count(), 1);
14956 let read = g.output_views(id).expect("entry present");
14957 assert_eq!(read.len(), 2);
14958 assert_eq!(read[1].shape, Shape::from_dims(&[2, 4]));
14959 }
14960
14961 /// `Graph::set_output_views` rejects slot 0 dtype/shape that
14962 /// disagree with the producer node's primary shape/dtype.
14963 #[test]
14964 fn graph_set_output_views_validates_primary() {
14965 let mut g = Graph::new();
14966 let id = g.push(Node {
14967 op: Op::Const,
14968 inputs: vec![],
14969 shape: Shape::from_dims(&[2, 3]),
14970 dtype: DType::F32,
14971 });
14972 // dtype mismatch on slot 0
14973 let bad_dtype = OutputView {
14974 byte_offset: 0,
14975 len_elements: 6,
14976 dtype: DType::F64,
14977 shape: Shape::from_dims(&[2, 3]),
14978 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
14979 name: None,
14980 };
14981 let err = g
14982 .set_output_views(id, vec![bad_dtype].into())
14983 .expect_err("primary dtype mismatch must error");
14984 let msg = format!("{err}");
14985 assert!(msg.contains("dtype"), "error message: {msg}");
14986 // shape mismatch on slot 0
14987 let bad_shape = OutputView {
14988 byte_offset: 0,
14989 len_elements: 4,
14990 dtype: DType::F32,
14991 shape: Shape::from_dims(&[2, 2]),
14992 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
14993 name: None,
14994 };
14995 let err = g
14996 .set_output_views(id, vec![bad_shape].into())
14997 .expect_err("primary shape mismatch must error");
14998 let msg = format!("{err}");
14999 assert!(msg.contains("shape"), "error message: {msg}");
15000 }
15001
15002 /// `NodeHandle::view(slot)` against a producer that hasn't been
15003 /// declared multi-output returns Err — fails fast at build time.
15004 #[test]
15005 fn tensor_view_on_non_multi_output_errors() {
15006 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15007 let id = graph.write().unwrap().push(Node {
15008 op: Op::Const,
15009 inputs: vec![],
15010 shape: Shape::from_dims(&[2, 3]),
15011 dtype: DType::F32,
15012 });
15013 let producer = NodeHandle::from_existing(Arc::clone(&graph), id);
15014 let err = producer
15015 .view(0)
15016 .expect_err("view on non-multi-output producer must error");
15017 let msg = format!("{err}");
15018 assert!(msg.contains("multi-output"), "error message: {msg}");
15019 }
15020
15021 /// `NodeHandle::view(slot)` with slot OOB returns Err.
15022 #[test]
15023 fn tensor_view_oob_slot_errors() {
15024 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15025 let producer_id = {
15026 let mut g = graph.write().unwrap();
15027 let id = g.push(Node {
15028 op: Op::Const,
15029 inputs: vec![],
15030 shape: Shape::from_dims(&[2, 3]),
15031 dtype: DType::F32,
15032 });
15033 let (views, _) = two_slot_views();
15034 g.set_output_views(id, views.into())
15035 .expect("valid 2-slot specs");
15036 id
15037 };
15038 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15039 let err = producer
15040 .view(2)
15041 .expect_err("slot 2 of a 2-slot producer must error");
15042 let msg = format!("{err}");
15043 assert!(msg.contains("out of range"), "error message: {msg}");
15044 }
15045
15046 /// `NodeHandle::view(slot)` produces a tensor whose shape/dtype match
15047 /// the slot spec; producer's primary shape stays as slot 0's. The
15048 /// View node holds the producer in `inputs[0]`.
15049 #[test]
15050 fn tensor_view_shape_dtype_from_slot() {
15051 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15052 let producer_id = {
15053 let mut g = graph.write().unwrap();
15054 let id = g.push(Node {
15055 op: Op::Const,
15056 inputs: vec![],
15057 shape: Shape::from_dims(&[2, 3]),
15058 dtype: DType::F32,
15059 });
15060 let (views, _) = two_slot_views();
15061 g.set_output_views(id, views.into())
15062 .expect("valid 2-slot specs");
15063 id
15064 };
15065 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15066 let v0 = producer.view(0).expect("slot 0 view");
15067 assert_eq!(v0.shape(), Shape::from_dims(&[2, 3]));
15068 assert_eq!(v0.dtype(), DType::F32);
15069 let v1 = producer.view(1).expect("slot 1 view");
15070 assert_eq!(v1.shape(), Shape::from_dims(&[2, 4]));
15071 assert_eq!(v1.dtype(), DType::F32);
15072 // View node carries the producer in inputs[0] and the slot
15073 // index in the Op variant — verify the Graph state directly.
15074 let g = graph.read().unwrap();
15075 let v1_node = g.node(v1.id());
15076 assert_eq!(v1_node.inputs, vec![producer_id]);
15077 assert!(matches!(v1_node.op, Op::View { slot: 1 }));
15078 // Slot 0 starts at byte_offset 0 + contiguous → layout
15079 // matches Layout::contiguous(slot0.shape) → no side-table
15080 // entry (the contiguous fallback covers it).
15081 assert!(!g.has_explicit_layout(v0.id()));
15082 // Slot 1 starts at byte_offset 24 (= 6 F32 elements past
15083 // slot 0). Session 4 bakes that into the layout's
15084 // start_offset so a downstream kernel reading the producer's
15085 // bytes as F32 elements lands on slot 1's first byte. Side-
15086 // table entry is mandatory.
15087 assert!(g.has_explicit_layout(v1.id()));
15088 let l1 = g.layout(v1.id());
15089 assert_eq!(
15090 l1.start_offset(),
15091 6,
15092 "slot 1 byte_offset 24 / 4 = 6 F32 elements"
15093 );
15094 assert_eq!(l1.shape(), &Shape::from_dims(&[2, 4]));
15095 }
15096
15097 /// `NodeHandle::view(slot)` over a slot whose layout is non-contiguous
15098 /// (strided) populates the Graph's layout side-table with the
15099 /// slot's layout — so downstream consumers see the strided view.
15100 #[test]
15101 fn tensor_view_propagates_non_contiguous_slot_layout() {
15102 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15103 let strided_shape = Shape::from_dims(&[2, 3]);
15104 let strided_layout = Layout::contiguous(strided_shape.clone())
15105 .transpose(0, 1)
15106 .expect("transpose [2,3] -> [3,2]");
15107 // Slot 0 = primary (contiguous, matches producer's Node shape).
15108 let s0 = OutputView {
15109 byte_offset: 0,
15110 len_elements: strided_shape.elem_count(),
15111 dtype: DType::F32,
15112 shape: strided_shape.clone(),
15113 layout: Layout::contiguous(strided_shape.clone()),
15114 name: Some("primary"),
15115 };
15116 // Slot 1 = strided projection. Same byte range as slot 0; the
15117 // shape after transpose is [3, 2]; layout's start offset stays
15118 // within the slot.
15119 let s1 = OutputView {
15120 byte_offset: 0,
15121 len_elements: strided_shape.elem_count(),
15122 dtype: DType::F32,
15123 shape: Shape::from_dims(&[3, 2]),
15124 layout: strided_layout.clone(),
15125 name: Some("strided_view"),
15126 };
15127 let producer_id = {
15128 let mut g = graph.write().unwrap();
15129 let id = g.push(Node {
15130 op: Op::Const,
15131 inputs: vec![],
15132 shape: strided_shape.clone(),
15133 dtype: DType::F32,
15134 });
15135 g.set_output_views(id, vec![s0, s1].into())
15136 .expect("valid 2-slot strided spec");
15137 id
15138 };
15139 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15140 let v1 = producer.view(1).expect("strided slot view");
15141 let g = graph.read().unwrap();
15142 assert!(
15143 g.has_explicit_layout(v1.id()),
15144 "strided slot must populate Graph::layouts side-table",
15145 );
15146 let read_layout = g.layout(v1.id());
15147 assert_eq!(read_layout.shape(), strided_layout.shape());
15148 assert_eq!(read_layout.stride(), strided_layout.stride());
15149 }
15150
15151 /// `NodeHandle::view_owned(slot)` produces the same shape/dtype as
15152 /// `NodeHandle::view(slot)` but its output layout is ALWAYS contiguous
15153 /// — the forward memcpy produces a fresh standalone buffer, so
15154 /// the slot's (possibly strided) layout is not propagated.
15155 #[test]
15156 fn tensor_view_owned_layout_is_contiguous() {
15157 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15158 let strided_shape = Shape::from_dims(&[2, 3]);
15159 let strided_layout = Layout::contiguous(strided_shape.clone())
15160 .transpose(0, 1)
15161 .expect("transpose [2,3] -> [3,2]");
15162 let s0 = OutputView {
15163 byte_offset: 0,
15164 len_elements: strided_shape.elem_count(),
15165 dtype: DType::F32,
15166 shape: strided_shape.clone(),
15167 layout: Layout::contiguous(strided_shape.clone()),
15168 name: None,
15169 };
15170 let s1 = OutputView {
15171 byte_offset: 0,
15172 len_elements: strided_shape.elem_count(),
15173 dtype: DType::F32,
15174 shape: Shape::from_dims(&[3, 2]),
15175 layout: strided_layout,
15176 name: None,
15177 };
15178 let producer_id = {
15179 let mut g = graph.write().unwrap();
15180 let id = g.push(Node {
15181 op: Op::Const,
15182 inputs: vec![],
15183 shape: strided_shape,
15184 dtype: DType::F32,
15185 });
15186 g.set_output_views(id, vec![s0, s1].into())
15187 .expect("valid 2-slot specs");
15188 id
15189 };
15190 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15191 let v1 = producer.view_owned(1).expect("ViewOwned slot 1");
15192 assert_eq!(v1.shape(), Shape::from_dims(&[3, 2]));
15193 assert_eq!(v1.dtype(), DType::F32);
15194 let g = graph.read().unwrap();
15195 // ViewOwned is a fresh allocation — no explicit layout entry,
15196 // contiguous layout falls through.
15197 assert!(!g.has_explicit_layout(v1.id()));
15198 let owned_node = g.node(v1.id());
15199 assert!(matches!(owned_node.op, Op::ViewOwned { slot: 1 }));
15200 }
15201
15202 // ------------------------------------------------------------------
15203 // Session 2: bundled allocator + FusedOpEntry::output_views +
15204 // View-vs-ViewOwned planner pass. The tests use the bundled
15205 // storage allocator and a synthetic 2-output FusedOp entry — no
15206 // real fused-op author migrates in Session 2; the
15207 // selective-scan-ssd-chunk-multi-output-followup session lights
15208 // up the first real consumer.
15209 // ------------------------------------------------------------------
15210
15211 use fuel_backend_contract::storage::allocate_bundled_storage;
15212 use fuel_ir::storage::OutputViewSpec;
15213
15214 /// `allocate_bundled_storage` allocates one Storage on the device,
15215 /// attaches the bundle, and slot lookups report the spec-derived
15216 /// byte_offsets.
15217 #[test]
15218 fn allocate_bundled_storage_two_slot_roundtrip() {
15219 let dev = cpu_dev();
15220 let specs = vec![
15221 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15222 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15223 ];
15224 let s =
15225 allocate_bundled_storage(dev.as_ref(), &specs).expect("two-slot F32 alloc succeeds");
15226 assert!(s.is_bundled());
15227 assert_eq!(s.slot_count(), 2);
15228 assert_eq!(s.primary_dtype(), DType::F32);
15229 let v0 = s.slot_view(0).unwrap();
15230 let v1 = s.slot_view(1).unwrap();
15231 assert_eq!(v0.byte_offset, 0);
15232 assert_eq!(v0.shape, Shape::from_dims(&[2, 3]));
15233 assert_eq!(v1.byte_offset, 24);
15234 assert_eq!(v1.shape, Shape::from_dims(&[2, 4]));
15235 }
15236
15237 /// `allocate_bundled_storage` handles mixed F32 + F64 slots — slot
15238 /// 0 is primary (F32), slot 1's bytes are aligned to its F64
15239 /// boundary, and the underlying allocation has enough flat F32
15240 /// elements to cover the total bundle bytes.
15241 #[test]
15242 fn allocate_bundled_storage_mixed_dtype() {
15243 let dev = cpu_dev();
15244 let specs = vec![
15245 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[6])),
15246 OutputViewSpec::contiguous(DType::F64, Shape::from_dims(&[3])),
15247 ];
15248 let s = allocate_bundled_storage(dev.as_ref(), &specs).expect("mixed-dtype alloc succeeds");
15249 assert_eq!(s.primary_dtype(), DType::F32);
15250 let v0 = s.slot_view(0).unwrap();
15251 let v1 = s.slot_view(1).unwrap();
15252 assert_eq!(v0.dtype, DType::F32);
15253 assert_eq!(v1.dtype, DType::F64);
15254 assert_eq!(v0.byte_offset, 0);
15255 // F32[6] = 24 bytes; 24 is already multiple of 8, so v1
15256 // starts at 24 without further padding.
15257 assert_eq!(v1.byte_offset, 24);
15258 }
15259
15260 /// `allocate_bundled_storage` propagates compose_bundle errors —
15261 /// an empty spec list errors out before touching the device.
15262 #[test]
15263 fn allocate_bundled_storage_rejects_empty() {
15264 let dev = cpu_dev();
15265 let err = allocate_bundled_storage(dev.as_ref(), &[]).expect_err("empty specs error");
15266 assert!(format!("{err}").contains("non-empty"));
15267 }
15268
15269 /// The two SelectiveScan / SsdChunkScan migrations from item 3
15270 /// (2026-06-01) are the first `default_registry` entries to
15271 /// declare `output_views`. Any new multi-output op author should
15272 /// extend the expected set here.
15273 #[test]
15274 fn default_registry_multi_output_entries() {
15275 let reg = crate::registry::default_registry();
15276 let mut multi_out_names: Vec<&'static str> = reg
15277 .entries_iter()
15278 .filter(|e| e.output_views.is_some())
15279 .map(|e| e.name)
15280 .collect();
15281 multi_out_names.sort();
15282 assert_eq!(
15283 multi_out_names,
15284 vec!["SelectiveScan", "SsdChunkScan"],
15285 "the multi-output registry set should match the item-3 \
15286 migrations (SelectiveScan + SsdChunkScan); add new \
15287 multi-output ops to this list as they migrate",
15288 );
15289 }
15290
15291 /// Authoring-contract invariant: for every multi-output entry in
15292 /// the process-wide registry, `shape_rule(inputs)` MUST equal
15293 /// `output_views(inputs)[0].shape` and `dtype_rule(inputs)` MUST
15294 /// equal `output_views(inputs)[0].dtype`. Slot 0 is the primary
15295 /// and the bundled-allocation contract assumes the producer's
15296 /// `Node.shape`/`Node.dtype` reflect it.
15297 #[test]
15298 fn multi_output_entries_slot_0_matches_primary_rules() {
15299 use crate::registry::FusedOpParams;
15300 let reg = crate::registry::default_registry();
15301
15302 // Each multi-output entry needs a representative input batch
15303 // (shapes + dtypes + params) that satisfies its
15304 // shape_rule/dtype_rule preconditions. The check below runs
15305 // once per entry using these fixtures.
15306 struct Fixture {
15307 shapes: Vec<Shape>,
15308 dtypes: Vec<DType>,
15309 params: FusedOpParams,
15310 }
15311 fn selective_scan_fixture() -> Fixture {
15312 Fixture {
15313 shapes: vec![
15314 Shape::from_dims(&[2, 4, 8]), // u: [batch, seqlen, dim]
15315 Shape::from_dims(&[2, 4, 8]), // delta: same
15316 Shape::from_dims(&[8, 16]), // a: [dim, dstate]
15317 Shape::from_dims(&[2, 4, 16]), // b: [batch, seqlen, dstate]
15318 Shape::from_dims(&[2, 4, 16]), // c: same
15319 ],
15320 dtypes: vec![DType::F32; 5],
15321 params: FusedOpParams::SelectiveScan {
15322 delta_softplus: false,
15323 },
15324 }
15325 }
15326 fn ssd_chunk_scan_fixture() -> Fixture {
15327 Fixture {
15328 shapes: vec![
15329 Shape::from_dims(&[2, 4, 3, 8]), // x: [batch, seqlen, heads, head_dim]
15330 Shape::from_dims(&[2, 4, 3]), // dt: [batch, seqlen, heads]
15331 Shape::from_dims(&[3]), // a: [heads]
15332 Shape::from_dims(&[2, 4, 3, 16]), // b: [batch, seqlen, heads, state_dim]
15333 Shape::from_dims(&[2, 4, 3, 16]), // c: same
15334 ],
15335 dtypes: vec![DType::F32; 5],
15336 params: FusedOpParams::SsdChunkScan { chunk_size: 4 },
15337 }
15338 }
15339
15340 for entry in reg.entries_iter().filter(|e| e.output_views.is_some()) {
15341 let fx = match entry.name {
15342 "SelectiveScan" => selective_scan_fixture(),
15343 "SsdChunkScan" => ssd_chunk_scan_fixture(),
15344 other => panic!(
15345 "multi_output_entries_slot_0_matches_primary_rules: \
15346 no fixture for new multi-output entry {other:?}. \
15347 Add one to this test as you register a new op.",
15348 ),
15349 };
15350 let primary_shape = (entry.shape_rule)(&fx.shapes, &fx.params);
15351 let primary_dtype = (entry.dtype_rule)(&fx.dtypes, &fx.params);
15352 let specs = entry.output_views.unwrap()(&fx.shapes, &fx.dtypes, &fx.params);
15353 assert!(
15354 !specs.is_empty(),
15355 "{}: output_views returned empty Vec (multi-output ops \
15356 must have ≥ 1 slot)",
15357 entry.name,
15358 );
15359 assert_eq!(
15360 specs[0].shape, primary_shape,
15361 "{}: output_views[0].shape {:?} must equal shape_rule \
15362 {:?} (slot 0 is the primary; Node::shape reflects it)",
15363 entry.name, specs[0].shape, primary_shape,
15364 );
15365 assert_eq!(
15366 specs[0].dtype, primary_dtype,
15367 "{}: output_views[0].dtype {:?} must equal dtype_rule \
15368 {:?} (slot 0 is the primary; Node::dtype reflects it)",
15369 entry.name, specs[0].dtype, primary_dtype,
15370 );
15371 // Layout-shape coherence: each slot's layout shape must
15372 // equal its declared shape (the same invariant
15373 // set_output_views enforces at graph-build time).
15374 for (i, spec) in specs.iter().enumerate() {
15375 assert_eq!(
15376 spec.layout.shape(),
15377 &spec.shape,
15378 "{}: slot {i} layout.shape() {:?} disagrees with \
15379 declared spec.shape {:?}",
15380 entry.name,
15381 spec.layout.shape(),
15382 spec.shape,
15383 );
15384 }
15385 }
15386 }
15387
15388 /// Build a synthetic multi-output `FusedOpEntry` to exercise the
15389 /// authoring contract end-to-end without polluting the production
15390 /// registry. The output_views fn returns a 2-slot spec list whose
15391 /// slot 0 matches shape_rule / dtype_rule (the primary).
15392 fn synthetic_two_output_entry() -> crate::registry::FusedOpEntry {
15393 fn shape(_: &[Shape], _: &crate::registry::FusedOpParams) -> Shape {
15394 Shape::from_dims(&[2, 3])
15395 }
15396 fn dtype(_: &[DType], _: &crate::registry::FusedOpParams) -> DType {
15397 DType::F32
15398 }
15399 fn ovs(
15400 _: &[Shape],
15401 _: &[DType],
15402 _: &crate::registry::FusedOpParams,
15403 ) -> Vec<OutputViewSpec> {
15404 vec![
15405 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15406 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15407 ]
15408 }
15409 crate::registry::FusedOpEntry {
15410 destructive_input: None,
15411 id: crate::registry::FusedOps::SOFTMAX_LAST_DIM, // any id; not registered
15412 name: "<synthetic-2-output>",
15413 family: crate::registry::FusedOpFamily::Forward,
15414 pattern: crate::registry::SubgraphPattern::Callable(|_g, _id| None),
15415 decompose: |_g, id, _p| id,
15416 backward: crate::registry::BackwardKind::NotDifferentiable,
15417 shape_rule: shape,
15418 dtype_rule: dtype,
15419 output_views: Some(ovs),
15420 }
15421 }
15422
15423 /// The synthetic entry's `output_views` matches the
15424 /// `shape_rule`/`dtype_rule` contract on slot 0.
15425 #[test]
15426 fn synthetic_entry_output_views_matches_primary_contract() {
15427 let entry = synthetic_two_output_entry();
15428 let ovs_fn = entry.output_views.expect("synthetic entry is multi-output");
15429 let specs = ovs_fn(&[], &[], &crate::registry::FusedOpParams::SoftmaxLastDim);
15430 assert_eq!(specs.len(), 2);
15431 assert_eq!(
15432 specs[0].dtype,
15433 (entry.dtype_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15434 );
15435 assert_eq!(
15436 specs[0].shape,
15437 (entry.shape_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15438 );
15439 }
15440
15441 /// Build a producer Const node and declare it multi-output via
15442 /// `Graph::set_output_views`. Returns the producer's NodeId and a
15443 /// SharedGraph handle.
15444 fn multi_output_producer(slots: Vec<OutputView>) -> (SharedGraph, NodeId) {
15445 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15446 let id = {
15447 let mut g = graph.write().unwrap();
15448 let id = g.push(Node {
15449 op: Op::Const,
15450 inputs: vec![],
15451 shape: slots[0].shape.clone(),
15452 dtype: slots[0].dtype,
15453 });
15454 g.set_output_views(id, slots.into())
15455 .expect("valid synthetic specs");
15456 id
15457 };
15458 (graph, id)
15459 }
15460
15461 /// Two slots, both consumed at the same topo depth → planner does
15462 /// nothing (symmetric lifetimes, bundle drops naturally).
15463 #[test]
15464 fn promote_views_symmetric_lifetimes_is_noop() {
15465 let slot_specs = vec![
15466 OutputView {
15467 byte_offset: 0,
15468 len_elements: 6,
15469 dtype: DType::F32,
15470 shape: Shape::from_dims(&[2, 3]),
15471 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15472 name: Some("y"),
15473 },
15474 OutputView {
15475 byte_offset: 24,
15476 len_elements: 8,
15477 dtype: DType::F32,
15478 shape: Shape::from_dims(&[2, 4]),
15479 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15480 name: Some("state"),
15481 },
15482 ];
15483 let (graph, producer_id) = multi_output_producer(slot_specs);
15484 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15485 // Each slot has exactly one View, consumed at the same depth
15486 // (a no-op Relu downstream of each).
15487 let v0 = producer.view(0).expect("slot 0 view");
15488 let v1 = producer.view(1).expect("slot 1 view");
15489 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15490 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15491 let roots = {
15492 let mut g = graph.write().unwrap();
15493 let r0 = g.push(Node {
15494 op: Op::Relu,
15495 inputs: vec![v0_id],
15496 shape: v0_shape,
15497 dtype: v0_dtype,
15498 });
15499 let r1 = g.push(Node {
15500 op: Op::Relu,
15501 inputs: vec![v1_id],
15502 shape: v1_shape,
15503 dtype: v1_dtype,
15504 });
15505 vec![r0, r1]
15506 };
15507 let promotions = {
15508 let mut g = graph.write().unwrap();
15509 crate::opt::promote_views_for_liveness(&mut g, &roots)
15510 };
15511 assert_eq!(
15512 promotions, 0,
15513 "symmetric lifetimes shouldn't promote anything"
15514 );
15515 }
15516
15517 /// Asymmetric lifetimes: slot 0 consumed early, slot 1 consumed
15518 /// late → planner promotes slot 1's View to ViewOwned.
15519 #[test]
15520 fn promote_views_asymmetric_promotes_long_lived_slot() {
15521 let slot_specs = vec![
15522 OutputView {
15523 byte_offset: 0,
15524 len_elements: 6,
15525 dtype: DType::F32,
15526 shape: Shape::from_dims(&[2, 3]),
15527 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15528 name: Some("y"),
15529 },
15530 OutputView {
15531 byte_offset: 24,
15532 len_elements: 6,
15533 dtype: DType::F32,
15534 shape: Shape::from_dims(&[2, 3]),
15535 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15536 name: Some("state"),
15537 },
15538 ];
15539 let (graph, producer_id) = multi_output_producer(slot_specs);
15540 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15541 let v_y = producer.view(0).expect("slot 0 view");
15542 let v_state = producer.view(1).expect("slot 1 view");
15543 // Slot 0 ("y") consumed at depth 1 (single Relu).
15544 // Slot 1 ("state") consumed at a much deeper chain — Relu →
15545 // Relu → Relu. Topo positions push state's last-use later
15546 // than y's, triggering promotion of state's View.
15547 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15548 let (v_state_id, v_state_shape, v_state_dtype) =
15549 (v_state.id(), v_state.shape(), v_state.dtype());
15550 let roots = {
15551 let mut g = graph.write().unwrap();
15552 let y_relu = g.push(Node {
15553 op: Op::Relu,
15554 inputs: vec![v_y_id],
15555 shape: v_y_shape,
15556 dtype: v_y_dtype,
15557 });
15558 let s1 = g.push(Node {
15559 op: Op::Relu,
15560 inputs: vec![v_state_id],
15561 shape: v_state_shape.clone(),
15562 dtype: v_state_dtype,
15563 });
15564 let s2 = g.push(Node {
15565 op: Op::Relu,
15566 inputs: vec![s1],
15567 shape: v_state_shape.clone(),
15568 dtype: v_state_dtype,
15569 });
15570 let s3 = g.push(Node {
15571 op: Op::Relu,
15572 inputs: vec![s2],
15573 shape: v_state_shape,
15574 dtype: v_state_dtype,
15575 });
15576 vec![y_relu, s3]
15577 };
15578 let promotions = {
15579 let mut g = graph.write().unwrap();
15580 crate::opt::promote_views_for_liveness(&mut g, &roots)
15581 };
15582 assert_eq!(
15583 promotions, 1,
15584 "exactly the long-lived slot 1 View should promote"
15585 );
15586 // Slot 1's consumer (the first Relu in the long chain) now
15587 // reads a fresh Op::ViewOwned node, not the old Op::View.
15588 let g = graph.read().unwrap();
15589 // Find the new ViewOwned node — it was pushed AFTER the
15590 // existing nodes, so it's the last node in the arena. Its op
15591 // must be Op::ViewOwned { slot: 1 } and its input must be the
15592 // producer.
15593 let last_id = NodeId(g.len() - 1);
15594 let last_node = g.node(last_id);
15595 assert!(matches!(last_node.op, Op::ViewOwned { slot: 1 }));
15596 assert_eq!(last_node.inputs, vec![producer_id]);
15597 // The slot 0 View is untouched — still Op::View.
15598 let v_y_node = g.node(v_y_id);
15599 assert!(matches!(v_y_node.op, Op::View { slot: 0 }));
15600 // The old slot 1 View stays in the arena (orphaned). No
15601 // consumer points at it anymore.
15602 let v_state_node = g.node(v_state_id);
15603 assert!(matches!(v_state_node.op, Op::View { slot: 1 }));
15604 }
15605
15606 /// Running the pass twice on the same graph promotes nothing on
15607 /// the second call — `Op::ViewOwned` is a fixpoint (skipped by
15608 /// the planner because `is_owned` is true).
15609 #[test]
15610 fn promote_views_idempotent() {
15611 let slot_specs = vec![
15612 OutputView {
15613 byte_offset: 0,
15614 len_elements: 4,
15615 dtype: DType::F32,
15616 shape: Shape::from_dims(&[2, 2]),
15617 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15618 name: None,
15619 },
15620 OutputView {
15621 byte_offset: 16,
15622 len_elements: 4,
15623 dtype: DType::F32,
15624 shape: Shape::from_dims(&[2, 2]),
15625 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15626 name: None,
15627 },
15628 ];
15629 let (graph, producer_id) = multi_output_producer(slot_specs);
15630 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15631 let v_y = producer.view(0).expect("slot 0 view");
15632 let v_state = producer.view(1).expect("slot 1 view");
15633 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15634 let (v_state_id, v_state_shape, v_state_dtype) =
15635 (v_state.id(), v_state.shape(), v_state.dtype());
15636 let roots = {
15637 let mut g = graph.write().unwrap();
15638 let y_r = g.push(Node {
15639 op: Op::Relu,
15640 inputs: vec![v_y_id],
15641 shape: v_y_shape,
15642 dtype: v_y_dtype,
15643 });
15644 let s1 = g.push(Node {
15645 op: Op::Relu,
15646 inputs: vec![v_state_id],
15647 shape: v_state_shape.clone(),
15648 dtype: v_state_dtype,
15649 });
15650 let s2 = g.push(Node {
15651 op: Op::Relu,
15652 inputs: vec![s1],
15653 shape: v_state_shape,
15654 dtype: v_state_dtype,
15655 });
15656 vec![y_r, s2]
15657 };
15658 let first = {
15659 let mut g = graph.write().unwrap();
15660 crate::opt::promote_views_for_liveness(&mut g, &roots)
15661 };
15662 let second = {
15663 let mut g = graph.write().unwrap();
15664 crate::opt::promote_views_for_liveness(&mut g, &roots)
15665 };
15666 assert_eq!(first, 1, "first call promotes the long-lived slot");
15667 assert_eq!(
15668 second, 0,
15669 "second call is idempotent — no further promotions"
15670 );
15671 }
15672
15673 /// Graph with no multi-output producers: pass returns 0 and
15674 /// touches nothing.
15675 #[test]
15676 fn promote_views_noop_on_graph_without_multi_output() {
15677 let mut g = Graph::new();
15678 let a = g.push(Node {
15679 op: Op::Const,
15680 inputs: vec![],
15681 shape: Shape::from_dims(&[2, 3]),
15682 dtype: DType::F32,
15683 });
15684 let r = g.push(Node {
15685 op: Op::Relu,
15686 inputs: vec![a],
15687 shape: Shape::from_dims(&[2, 3]),
15688 dtype: DType::F32,
15689 });
15690 let n_before = g.len();
15691 let promotions = crate::opt::promote_views_for_liveness(&mut g, &[r]);
15692 assert_eq!(promotions, 0);
15693 assert_eq!(g.len(), n_before, "no node should have been added");
15694 }
15695
15696 // ------------------------------------------------------------------
15697 // Session 3: scheduler / destructive-cleanup integration —
15698 // bundle-aware liveness. A destructive op on a multi-output
15699 // producer (or any of its Views) must run after every reader of
15700 // every other View, because all Views share the bundle's storage
15701 // Arc. Op::ViewOwned is excluded — it forks a fresh standalone
15702 // Storage at execute time.
15703 // ------------------------------------------------------------------
15704
15705 /// Helper: build two contiguous slot specs for a producer of
15706 /// `Node::shape = [2, 3] F32`. Slot 0 is the primary (matches the
15707 /// producer's Node::shape/dtype, required by set_output_views);
15708 /// slot 1 carries a sibling shape that doesn't collide with the
15709 /// primary.
15710 fn two_slot_views_2x3_and_2x4() -> Vec<OutputView> {
15711 vec![
15712 OutputView {
15713 byte_offset: 0,
15714 len_elements: 6,
15715 dtype: DType::F32,
15716 shape: Shape::from_dims(&[2, 3]),
15717 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15718 name: Some("y"),
15719 },
15720 OutputView {
15721 byte_offset: 24,
15722 len_elements: 8,
15723 dtype: DType::F32,
15724 shape: Shape::from_dims(&[2, 4]),
15725 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15726 name: Some("state"),
15727 },
15728 ]
15729 }
15730
15731 /// Op::Release targeting a multi-output producer pins after every
15732 /// consumer of any View of that producer. Without bundle-aware
15733 /// aliasing the Views' downstream Relu nodes would be missed and
15734 /// could race the Release.
15735 #[test]
15736 fn derive_ordering_release_of_bundled_producer_pins_after_view_consumers() {
15737 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15738 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15739 let v0 = producer.view(0).expect("slot 0 view");
15740 let v1 = producer.view(1).expect("slot 1 view");
15741 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15742 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15743 let (r0, r1, release_id) = {
15744 let mut g = graph.write().unwrap();
15745 let r0 = g.push(Node {
15746 op: Op::Relu,
15747 inputs: vec![v0_id],
15748 shape: v0_shape,
15749 dtype: v0_dtype,
15750 });
15751 let r1 = g.push(Node {
15752 op: Op::Relu,
15753 inputs: vec![v1_id],
15754 shape: v1_shape,
15755 dtype: v1_dtype,
15756 });
15757 let release = g.push(Node {
15758 op: Op::Release,
15759 inputs: vec![producer_id],
15760 shape: Shape::from_dims(&[0]),
15761 dtype: DType::F32,
15762 });
15763 (r0, r1, release)
15764 };
15765 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r0, r1, release_id]);
15766 let deps = ord.deps_of(release_id);
15767 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15768 assert!(
15769 dep_set.contains(&r0),
15770 "Release must run after the slot-0 View's consumer (r0)",
15771 );
15772 assert!(
15773 dep_set.contains(&r1),
15774 "Release must run after the slot-1 View's consumer (r1) — \
15775 both Views share the bundle Arc",
15776 );
15777 }
15778
15779 /// Destructive op targeting one of a bundle's Op::View nodes
15780 /// pins after every sibling View's consumers too — every View
15781 /// of the producer shares the bundle's Arc, so writing through
15782 /// one of them clobbers the bytes the others read.
15783 #[test]
15784 fn derive_ordering_destructive_on_view_pins_sibling_view_consumers() {
15785 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15786 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15787 let v0 = producer.view(0).expect("slot 0 view");
15788 let v1 = producer.view(1).expect("slot 1 view");
15789 let (v0_id, _v0_shape, _v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15790 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15791 // Destructive op (Release) targets v0 directly — its
15792 // alias set must reach v1's consumer via the producer-sibling
15793 // hop in collect_alias_set.
15794 let (r1, release_id) = {
15795 let mut g = graph.write().unwrap();
15796 let r1 = g.push(Node {
15797 op: Op::Relu,
15798 inputs: vec![v1_id],
15799 shape: v1_shape,
15800 dtype: v1_dtype,
15801 });
15802 let release = g.push(Node {
15803 op: Op::Release,
15804 inputs: vec![v0_id],
15805 shape: Shape::from_dims(&[0]),
15806 dtype: DType::F32,
15807 });
15808 (r1, release)
15809 };
15810 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r1, release_id]);
15811 let deps = ord.deps_of(release_id);
15812 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15813 assert!(
15814 dep_set.contains(&r1),
15815 "Release targeting slot-0 View must pin after sibling slot-1 \
15816 View's consumer (r1) — both share the bundle's storage Arc",
15817 );
15818 }
15819
15820 /// Op::ViewOwned does NOT extend the alias set: its forward
15821 /// memcpy produces an independent Storage. derive_ordering must
15822 /// still pin Release after the ViewOwned itself (via the standard
15823 /// data-dependency: ViewOwned consumes the producer), but
15824 /// downstream consumers of the ViewOwned are NOT in the alias
15825 /// set's reader sweep — they read independent bytes and may run
15826 /// freely after the Release.
15827 #[test]
15828 fn derive_ordering_view_owned_is_not_alias_extending() {
15829 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15830 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15831 // Slot 0 → View (shared Arc); slot 1 → ViewOwned (independent).
15832 let v_view = producer.view(0).expect("slot 0 view");
15833 let v_owned = producer.view_owned(1).expect("slot 1 viewowned");
15834 let (v_view_id, _, _) = (v_view.id(), v_view.shape(), v_view.dtype());
15835 let (v_owned_id, v_owned_shape, v_owned_dtype) =
15836 (v_owned.id(), v_owned.shape(), v_owned.dtype());
15837 let (consumer_of_owned, release_id) = {
15838 let mut g = graph.write().unwrap();
15839 let consumer = g.push(Node {
15840 op: Op::Relu,
15841 inputs: vec![v_owned_id],
15842 shape: v_owned_shape,
15843 dtype: v_owned_dtype,
15844 });
15845 let release = g.push(Node {
15846 op: Op::Release,
15847 inputs: vec![producer_id],
15848 shape: Shape::from_dims(&[0]),
15849 dtype: DType::F32,
15850 });
15851 (consumer, release)
15852 };
15853 let ord =
15854 crate::opt::derive_ordering(&graph.read().unwrap(), &[consumer_of_owned, release_id]);
15855 let deps = ord.deps_of(release_id);
15856 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15857 // Release MUST wait for ViewOwned to run (ViewOwned reads
15858 // the producer's bytes during its memcpy).
15859 assert!(
15860 dep_set.contains(&v_owned_id),
15861 "Release must pin after ViewOwned — ViewOwned reads the \
15862 producer's bundle during its memcpy phase",
15863 );
15864 // Release must NOT depend on the ViewOwned's downstream
15865 // consumer — that consumer reads ViewOwned's independent
15866 // bytes, not the producer's bundle.
15867 assert!(
15868 !dep_set.contains(&consumer_of_owned),
15869 "Release must NOT pin after consumers of ViewOwned — \
15870 ViewOwned forks a fresh Storage; its consumers don't \
15871 read the producer's bundle",
15872 );
15873 // Op::View's consumers stay reached via the alias chain; here
15874 // there are none (v_view has no consumer), so v_view itself
15875 // is the only alias-set entry beyond the producer.
15876 let _ = v_view_id;
15877 }
15878
15879 /// Long-tail bundle-aware schedule: a producer with three Views,
15880 /// each consumed by a chain of different depth, and a destructive
15881 /// Release on the producer. The Release must end up after every
15882 /// terminal consumer of every chain — bundle-as-single-eviction-
15883 /// unit semantics fall out of derive_ordering's alias-set walk
15884 /// reaching each chain's leaf via the producer-then-View hop.
15885 #[test]
15886 fn derive_ordering_bundle_release_pins_after_all_chains() {
15887 // Build a 3-slot bundle. Slot 0 primary [2,3] F32 satisfies
15888 // the producer's Node::shape/dtype constraint; slots 1 + 2
15889 // add sibling shapes.
15890 let slot_specs = vec![
15891 OutputView {
15892 byte_offset: 0,
15893 len_elements: 6,
15894 dtype: DType::F32,
15895 shape: Shape::from_dims(&[2, 3]),
15896 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15897 name: Some("a"),
15898 },
15899 OutputView {
15900 byte_offset: 24,
15901 len_elements: 4,
15902 dtype: DType::F32,
15903 shape: Shape::from_dims(&[2, 2]),
15904 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15905 name: Some("b"),
15906 },
15907 OutputView {
15908 byte_offset: 40,
15909 len_elements: 8,
15910 dtype: DType::F32,
15911 shape: Shape::from_dims(&[2, 4]),
15912 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15913 name: Some("c"),
15914 },
15915 ];
15916 let (graph, producer_id) = multi_output_producer(slot_specs);
15917 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15918 let v0 = producer.view(0).unwrap();
15919 let v1 = producer.view(1).unwrap();
15920 let v2 = producer.view(2).unwrap();
15921 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15922 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15923 let (v2_id, v2_shape, v2_dtype) = (v2.id(), v2.shape(), v2.dtype());
15924 let (leaf_a, leaf_b, leaf_c, release_id) = {
15925 let mut g = graph.write().unwrap();
15926 let leaf_a = g.push(Node {
15927 op: Op::Relu,
15928 inputs: vec![v0_id],
15929 shape: v0_shape,
15930 dtype: v0_dtype,
15931 });
15932 let b1 = g.push(Node {
15933 op: Op::Relu,
15934 inputs: vec![v1_id],
15935 shape: v1_shape.clone(),
15936 dtype: v1_dtype,
15937 });
15938 let leaf_b = g.push(Node {
15939 op: Op::Relu,
15940 inputs: vec![b1],
15941 shape: v1_shape,
15942 dtype: v1_dtype,
15943 });
15944 let c1 = g.push(Node {
15945 op: Op::Relu,
15946 inputs: vec![v2_id],
15947 shape: v2_shape.clone(),
15948 dtype: v2_dtype,
15949 });
15950 let c2 = g.push(Node {
15951 op: Op::Relu,
15952 inputs: vec![c1],
15953 shape: v2_shape.clone(),
15954 dtype: v2_dtype,
15955 });
15956 let leaf_c = g.push(Node {
15957 op: Op::Relu,
15958 inputs: vec![c2],
15959 shape: v2_shape,
15960 dtype: v2_dtype,
15961 });
15962 let release = g.push(Node {
15963 op: Op::Release,
15964 inputs: vec![producer_id],
15965 shape: Shape::from_dims(&[0]),
15966 dtype: DType::F32,
15967 });
15968 (leaf_a, leaf_b, leaf_c, release)
15969 };
15970 let ord = crate::opt::derive_ordering(
15971 &graph.read().unwrap(),
15972 &[leaf_a, leaf_b, leaf_c, release_id],
15973 );
15974 let deps = ord.deps_of(release_id);
15975 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15976 // The direct readers of any View are the FIRST relu in each
15977 // chain — those are the nodes that read the bundle's bytes.
15978 // Every consumer further down reads its predecessor's
15979 // standalone output Storage, so they aren't in the alias-set
15980 // reader sweep. Verify the Release pins on the direct
15981 // readers — sufficient for bundle-single-eviction safety
15982 // because the chains are themselves data-dep ordered after
15983 // their direct readers.
15984 assert!(
15985 dep_set.contains(&leaf_a),
15986 "single-Relu chain a: leaf is the direct reader",
15987 );
15988 // For the b/c chains, the direct readers are the first Relus
15989 // (b1 / c1), not the leaves. The Release must include those.
15990 // Find them by walking inputs from leaves.
15991 let g = graph.read().unwrap();
15992 let b1 = g.node(leaf_b).inputs[0];
15993 let (c2, c1) = {
15994 let c2 = g.node(leaf_c).inputs[0];
15995 let c1 = g.node(c2).inputs[0];
15996 (c2, c1)
15997 };
15998 let _ = c2;
15999 assert!(
16000 dep_set.contains(&b1),
16001 "two-Relu chain b: first Relu is the direct bundle reader",
16002 );
16003 assert!(
16004 dep_set.contains(&c1),
16005 "three-Relu chain c: first Relu is the direct bundle reader",
16006 );
16007 }
16008
16009 // ------------------------------------------------------------------
16010 // Item 4 — Op::View / Op::ViewOwned autograd emits Op::ScatterIntoSlot
16011 // ------------------------------------------------------------------
16012
16013 /// The View's backward arm pushes an `Op::ScatterIntoSlot { slot }`
16014 /// node into the gradient graph as the producer's input gradient.
16015 /// Synthetic test: build a 2-slot producer + Op::View(slot 1) +
16016 /// a Relu downstream + invoke NodeHandle::backward + walk the produced
16017 /// gradient graph and assert a ScatterIntoSlot was emitted.
16018 #[test]
16019 fn op_view_backward_emits_scatter_into_slot() {
16020 let producer_t =
16021 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
16022 let graph: SharedGraph = Arc::clone(producer_t.graph());
16023 let producer_id = producer_t.id();
16024 let view_id = {
16025 let mut g = graph.write().unwrap();
16026 let specs = two_slot_views_2x3_and_2x4();
16027 g.set_output_views(producer_id, specs.into())
16028 .expect("output_views");
16029 drop(g);
16030 let v1 = producer_t.view(1).expect("slot 1 view");
16031 v1.id()
16032 };
16033 // Build a tiny tape-tracked loss = sum(relu(v1)).
16034 let v1_tensor = NodeHandle::from_existing(Arc::clone(&graph), view_id);
16035 let relu_t = v1_tensor.relu();
16036 let loss_t = relu_t.sum_all();
16037
16038 // Take backward — exercises the View's backward arm.
16039 let grads = loss_t.backward();
16040
16041 // The producer's input gradient should be reachable via a
16042 // chain that includes an Op::ScatterIntoSlot { slot: 1 } node.
16043 let producer_tensor = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16044 let grad_for_producer = grads
16045 .get(&producer_tensor)
16046 .expect("producer has an accumulated gradient");
16047 let grad_id = grad_for_producer.id();
16048 let g = graph.read().unwrap();
16049 let scatter_present = matches!(g.node(grad_id).op, Op::ScatterIntoSlot { slot: 1 }) || {
16050 // Walk one hop back through `Op::Add` accumulations
16051 // if any.
16052 let n = g.node(grad_id);
16053 n.inputs
16054 .iter()
16055 .any(|inp| matches!(g.node(*inp).op, Op::ScatterIntoSlot { slot: 1 }))
16056 };
16057 assert!(
16058 scatter_present,
16059 "View(slot=1) backward must emit an Op::ScatterIntoSlot {{ slot: 1 }} \
16060 into the gradient graph; got grad node op = {:?}",
16061 g.node(grad_id).op,
16062 );
16063 }
16064
16065 // ----- Op::Branch inert scaffold (Phase A PR-A0 of the
16066 // "plan IS the graph" rebuild) -----
16067
16068 /// Back-compat by construction: a graph with ZERO `Op::Branch`
16069 /// nodes builds with exactly the arena it had before the variant
16070 /// existed. The locked design guarantees "a graph with zero
16071 /// Op::Branch nodes is exactly today's single-route graph" — this
16072 /// test pins that: the same builder calls produce the same node
16073 /// count, the same topo order, and not a single `Op::Branch` node.
16074 /// GAP-003 STEP 1: the panic IS reachable from the public API today.
16075 ///
16076 /// `NodeHandle::from_f32` returns `Self`, so a length/shape mismatch has
16077 /// nowhere to go but `assert_eq!` inside `from_host_buffer_on`. This test
16078 /// PASSES today and is deleted by the fix -- it exists to prove the defect
16079 /// is live from a caller's seat, not merely present in the source.
16080 /// GAP-003: a length/shape mismatch DECLINES instead of panicking.
16081 ///
16082 /// ⚠️ This started life as a `#[should_panic]` probe proving the defect was
16083 /// reachable from the public API. The bulk `.unwrap()` pass then appended
16084 /// `.unwrap()` to it, and it KEPT PASSING -- for the wrong reason: unwrapping
16085 /// an `Err` panics, and the `Err` message contains the expected substring, so
16086 /// the assertion could no longer tell "the API panics" from "I unwrapped a
16087 /// Result". A vacuous green produced by the very edit that fixed the defect.
16088 ///
16089 /// It now asserts the `Err` DIRECTLY, with no `unwrap`, and matches on the
16090 /// LENGTH-MISMATCH message specifically -- not merely on `is_err()`. That
16091 /// distinction is load-bearing: `from_host_buffer_on` has a second failure
16092 /// path (`storage_from_host_buffer_owned_dyn`), so a bare `is_err()` could
16093 /// not tell this decline from that one.
16094 #[test]
16095 fn gap003_from_f32_declines_a_length_mismatch() {
16096 // 2 elements declared as a 3-element shape.
16097 let err = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[3]), cpu_dev())
16098 .expect_err("a length/shape mismatch must DECLINE, not construct");
16099 let msg = err.to_string();
16100 assert!(
16101 msg.contains("does not match shape element count"),
16102 "the decline must name the LENGTH MISMATCH specifically, got: {msg}"
16103 );
16104 assert!(
16105 msg.contains('2') && msg.contains('3'),
16106 "and both operands: {msg}"
16107 );
16108
16109 // CONTROL: a MATCHING length still constructs, so the guard is not
16110 // "this constructor always fails".
16111 assert!(
16112 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).is_ok()
16113 );
16114 }
16115
16116 #[test]
16117 fn zero_branch_graph_builds_unchanged() {
16118 // Build: c = (a + b) * a — the same DAG the topo-order tests
16119 // use, exercised here purely to prove the arena is untouched by
16120 // the new variant.
16121 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
16122 let b = a
16123 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
16124 .unwrap();
16125 let sum = a.add(&b);
16126 let c = sum.mul(&a);
16127
16128 let g = c.graph();
16129 let guard = g.read().unwrap();
16130
16131 // Exactly four nodes (a, b, sum, c) — no implicit Branch
16132 // anywhere.
16133 assert_eq!(
16134 guard.len(),
16135 4,
16136 "zero-Branch graph must have the same node count as before"
16137 );
16138
16139 // Topo order is unchanged and contains zero Branch nodes.
16140 let order = topo_order(&guard, c.id());
16141 assert_eq!(order.len(), 4);
16142 let branch_count = order
16143 .iter()
16144 .filter(|&&id| matches!(guard.node(id).op, Op::Branch { .. }))
16145 .count();
16146 assert_eq!(branch_count, 0, "no builder constructs Op::Branch in PR-A0");
16147
16148 // The ops are exactly the ones the builders emitted (no
16149 // structural rewrite slipped in a merge node).
16150 assert!(matches!(guard.node(a.id()).op, Op::Const));
16151 assert!(matches!(guard.node(b.id()).op, Op::Const));
16152 assert!(matches!(guard.node(sum.id()).op, Op::Add));
16153 assert!(matches!(guard.node(c.id()).op, Op::Mul));
16154 }
16155
16156 /// The variant exists and its infallible accessor behaves: a
16157 /// hand-constructed `Op::Branch` reports `short_name() == "Branch"`,
16158 /// and the multi-path encoding (arms = `inputs`, explicit
16159 /// `reconverge_at`) round-trips through the arena. This is the only
16160 /// place in PR-A0 that constructs the variant — the production
16161 /// builders land in PR-A1.
16162 #[test]
16163 fn branch_variant_exists_and_short_name_works() {
16164 // short_name / the Op::short_name() facade both return the
16165 // stable "Branch" constant.
16166 let reconverge = NodeId(7);
16167 let branch_op = Op::Branch {
16168 reconverge_at: reconverge,
16169 };
16170 assert_eq!(branch_op.short_name(), "Branch");
16171 assert_eq!(op_short_name(&branch_op), "Branch");
16172
16173 // Structural nodes carry no destructive input (matches the
16174 // other structural ops: Const / View / ScatterIntoSlot).
16175 assert_eq!(branch_op.destructive_input(), None);
16176
16177 // Encode a 2-arm merge directly on the arena: two route exits
16178 // as `inputs`, the reconvergence node named explicitly. Prove
16179 // the encoding survives a push + read-back unchanged.
16180 let mut g = Graph::new();
16181 let arm0 = g.push(Node {
16182 op: Op::Const,
16183 inputs: vec![],
16184 shape: Shape::from_dims(&[2]),
16185 dtype: DType::F32,
16186 });
16187 let arm1 = g.push(Node {
16188 op: Op::Const,
16189 inputs: vec![],
16190 shape: Shape::from_dims(&[2]),
16191 dtype: DType::F32,
16192 });
16193 let merged = g.push(Node {
16194 op: Op::Const,
16195 inputs: vec![],
16196 shape: Shape::from_dims(&[2]),
16197 dtype: DType::F32,
16198 });
16199 let branch = g.push(Node {
16200 op: Op::Branch {
16201 reconverge_at: merged,
16202 },
16203 inputs: vec![arm0, arm1],
16204 shape: Shape::from_dims(&[2]),
16205 dtype: DType::F32,
16206 });
16207
16208 let node = g.node(branch);
16209 assert_eq!(node.op.short_name(), "Branch");
16210 // Arms are the node's inputs (each input = one route's exit).
16211 assert_eq!(node.inputs, vec![arm0, arm1]);
16212 // The explicit reconvergence node is carried on the op.
16213 match node.op {
16214 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, merged),
16215 ref other => panic!("expected Op::Branch, got {other:?}"),
16216 }
16217 }
16218
16219 // ----- Op::Branch builders + build-time validation
16220 // (Phase A PR-A1 of the "plan IS the graph" rebuild) -----
16221
16222 /// Hand-build a 2-arm diamond directly on the arena and return the
16223 /// pieces the branch builders will stitch together:
16224 /// `diverge` → {`arm0`, `arm1`} → `reconverge`. The reconverge node
16225 /// already reads arm0 as input 0, which is exactly the runnability
16226 /// invariant the builders must preserve (a finalized-but-unpicked
16227 /// branch still realizes on arm 0). Every node is `[2] f32` so the
16228 /// cast-to-uniform check has agreeing shape/dtype across arms.
16229 fn diamond_2arm() -> (Graph, NodeId, NodeId, NodeId, NodeId) {
16230 let mut g = Graph::new();
16231 let diverge = g.push(Node {
16232 op: Op::Const,
16233 inputs: vec![],
16234 shape: Shape::from_dims(&[2]),
16235 dtype: DType::F32,
16236 });
16237 // arm0 = relu(diverge), arm1 = silu(diverge): two interior nodes,
16238 // each reachable only through its own arm from the diverge point.
16239 let arm0 = g.push(Node {
16240 op: Op::Relu,
16241 inputs: vec![diverge],
16242 shape: Shape::from_dims(&[2]),
16243 dtype: DType::F32,
16244 });
16245 let arm1 = g.push(Node {
16246 op: Op::Silu,
16247 inputs: vec![diverge],
16248 shape: Shape::from_dims(&[2]),
16249 dtype: DType::F32,
16250 });
16251 // reconverge reads arm0 (runnability: arm 0 is always input 0).
16252 let reconverge = g.push(Node {
16253 op: Op::Relu,
16254 inputs: vec![arm0],
16255 shape: Shape::from_dims(&[2]),
16256 dtype: DType::F32,
16257 });
16258 (g, diverge, arm0, arm1, reconverge)
16259 }
16260
16261 /// (a) A 2-arm diamond round-trips through
16262 /// `open_branch`/`add_arm`/`finalize_branches`: it produces exactly
16263 /// one valid `Op::Branch` node whose `inputs` are the arm exits in
16264 /// order and whose `reconverge_at` is the named merge node.
16265 #[test]
16266 fn two_arm_diamond_round_trips_to_branch_node() {
16267 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16268 let before = g.len();
16269
16270 let mut b = g.open_branch(diverge);
16271 b.add_arm(arm0);
16272 b.add_arm(arm1);
16273 let branch = b
16274 .finalize_branches(&mut g, reconverge)
16275 .expect("well-formed 2-arm branch must finalize")
16276 .expect("2 arms survive — not collapsed to a single arm");
16277
16278 // Exactly one node was appended (the Branch); no orphan debris.
16279 assert_eq!(g.len(), before + 1);
16280
16281 let node = g.node(branch);
16282 assert!(matches!(node.op, Op::Branch { .. }));
16283 // Arms are the node's inputs, in add order: arm0 first.
16284 assert_eq!(node.inputs, vec![arm0, arm1]);
16285 match node.op {
16286 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, reconverge),
16287 ref other => panic!("expected Op::Branch, got {other:?}"),
16288 }
16289 // The merge node still carries arm0's shape/dtype (cast-to-uniform
16290 // validated, not rewritten).
16291 assert_eq!(node.shape, g.node(arm0).shape);
16292 assert_eq!(node.dtype, g.node(arm0).dtype);
16293 }
16294
16295 /// (b) A `reconverge_at` that is NOT a descendant of the diverge
16296 /// point returns `Error::InvalidBranch` — never a panic.
16297 #[test]
16298 fn reconverge_not_descendant_of_diverge_is_typed_err() {
16299 let (mut g, diverge, arm0, arm1, _reconverge) = diamond_2arm();
16300 // A sibling node that does NOT descend from `diverge`.
16301 let unrelated = g.push(Node {
16302 op: Op::Const,
16303 inputs: vec![],
16304 shape: Shape::from_dims(&[2]),
16305 dtype: DType::F32,
16306 });
16307
16308 let mut b = g.open_branch(diverge);
16309 b.add_arm(arm0);
16310 b.add_arm(arm1);
16311 let err = b
16312 .finalize_branches(&mut g, unrelated)
16313 .expect_err("reconverge that doesn't descend from diverge must be rejected");
16314 assert!(
16315 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16316 "expected InvalidBranch, got {err:?}",
16317 );
16318 }
16319
16320 /// (c) A non-disjoint arm — an arm interior node reachable from
16321 /// outside that arm (shared with the rest of the graph) — returns
16322 /// `Error::InvalidBranch`.
16323 #[test]
16324 fn non_disjoint_arm_is_typed_err() {
16325 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16326 // Add a reader OUTSIDE the branch that consumes arm0's interior.
16327 // arm0 is now reachable from a node that isn't part of the merge,
16328 // so the arm is not internally disjoint.
16329 let _external_reader = g.push(Node {
16330 op: Op::Relu,
16331 inputs: vec![arm0],
16332 shape: Shape::from_dims(&[2]),
16333 dtype: DType::F32,
16334 });
16335
16336 let mut b = g.open_branch(diverge);
16337 b.add_arm(arm0);
16338 b.add_arm(arm1);
16339 let err = b
16340 .finalize_branches(&mut g, reconverge)
16341 .expect_err("an arm interior read from outside the branch must be rejected");
16342 assert!(
16343 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16344 "expected InvalidBranch, got {err:?}",
16345 );
16346 }
16347
16348 /// (c') Arms that disagree on shape/dtype at their exits violate
16349 /// cast-to-uniform and return `Error::InvalidBranch` (validate-and-Err
16350 /// — no implicit Cast insertion in PR-A1).
16351 #[test]
16352 fn arms_disagreeing_on_dtype_is_typed_err() {
16353 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16354 // A second arm with a DIFFERENT dtype than arm0.
16355 let arm1_f16 = g.push(Node {
16356 op: Op::Silu,
16357 inputs: vec![diverge],
16358 shape: Shape::from_dims(&[2]),
16359 dtype: DType::F16,
16360 });
16361
16362 let mut b = g.open_branch(diverge);
16363 b.add_arm(arm0);
16364 b.add_arm(arm1_f16);
16365 let err = b
16366 .finalize_branches(&mut g, reconverge)
16367 .expect_err("arms with mismatched dtype must be rejected (cast-to-uniform)");
16368 assert!(
16369 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16370 "expected InvalidBranch, got {err:?}",
16371 );
16372 }
16373
16374 /// (d) `finalize_branches` drops a single-arm branch: with only one
16375 /// surviving arm there is no real decision point, so no `Op::Branch`
16376 /// node is emitted (`Ok(None)`), the arena is left untouched, and the
16377 /// graph collapses back to that arm.
16378 #[test]
16379 fn single_arm_branch_is_dropped() {
16380 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16381 let before = g.len();
16382
16383 let mut b = g.open_branch(diverge);
16384 b.add_arm(arm0);
16385 let result = b
16386 .finalize_branches(&mut g, reconverge)
16387 .expect("a single-arm branch is valid — it just collapses");
16388 assert!(
16389 result.is_none(),
16390 "single-arm branch must NOT emit an Op::Branch"
16391 );
16392 // No node appended: the lone arm is the graph, unchanged.
16393 assert_eq!(
16394 g.len(),
16395 before,
16396 "dropping a single-arm branch leaves the arena untouched"
16397 );
16398 let branch_count = (0..g.len())
16399 .filter(|&i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }))
16400 .count();
16401 assert_eq!(branch_count, 0);
16402 }
16403
16404 /// (e) The runnability invariant: the emitted `Op::Branch`'s inputs
16405 /// always include arm-0's exit as input 0, so a finalized-but-not-yet-
16406 /// route-picked graph still realizes on arm 0 (a graph with a
16407 /// finalized branch must still be executable). The named reconverge
16408 /// node reads arm-0's exit, so realizing on arm 0 alone produces a
16409 /// defined value at the merge.
16410 #[test]
16411 fn finalized_branch_preserves_arm0_runnability() {
16412 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16413
16414 let mut b = g.open_branch(diverge);
16415 b.add_arm(arm0);
16416 b.add_arm(arm1);
16417 let branch = b
16418 .finalize_branches(&mut g, reconverge)
16419 .expect("well-formed branch finalizes")
16420 .expect("2 arms survive");
16421
16422 // arm 0 is input 0 of the Branch — the always-realizable route.
16423 assert_eq!(g.node(branch).inputs.first().copied(), Some(arm0));
16424 // And the named reconverge node reads arm0, so realizing on
16425 // arm 0 alone produces a defined value at the merge.
16426 assert!(
16427 g.node(reconverge).inputs.contains(&arm0),
16428 "reconverge must read arm-0's exit so the unpicked graph runs on arm 0",
16429 );
16430 }
16431
16432 // ===================================================================
16433 // PR-B4: required compaction of the append-only arena.
16434 // ===================================================================
16435
16436 use crate::run::{extract_runs, lower_runs_arm0};
16437
16438 /// Build the same 2-arm diamond the run.rs tests use, finalized into a
16439 /// real `Op::Branch`. Returns `(g, diverge, arm0, arm1, reconverge,
16440 /// branch, post)`. `post` reads `reconverge`, so the post-merge region
16441 /// is a non-empty run and `post` is a stable root.
16442 fn diamond_with_branch_b4() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
16443 let mk = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
16444 g.push(Node {
16445 op,
16446 inputs,
16447 shape: Shape::from_dims(&[2]),
16448 dtype: DType::F32,
16449 })
16450 };
16451 let mut g = Graph::new();
16452 let pre = mk(&mut g, Op::Const, vec![]);
16453 let diverge = mk(&mut g, Op::Relu, vec![pre]);
16454 let arm0 = mk(&mut g, Op::Silu, vec![diverge]);
16455 let arm1 = mk(&mut g, Op::GeluTanh, vec![diverge]);
16456 let reconverge = mk(&mut g, Op::Relu, vec![arm0]);
16457 let mut b = g.open_branch(diverge);
16458 b.add_arm(arm0);
16459 b.add_arm(arm1);
16460 let branch = b
16461 .finalize_branches(&mut g, reconverge)
16462 .expect("well-formed 2-arm branch finalizes")
16463 .expect("2 arms survive");
16464 let post = mk(&mut g, Op::Tanh, vec![reconverge]);
16465 (g, diverge, arm0, arm1, reconverge, branch, post)
16466 }
16467
16468 /// PR-D1 storage-class substrate: the op-inferred class is correct
16469 /// (`Op::Const` → Shared, `Op::WriteSlice` → SessionState, other →
16470 /// Transient), an explicit override beats the inferred default (a
16471 /// KV-cache placeholder `Op::Const` marked SessionState), and `compact`
16472 /// carries the override to the node's new id while inferred defaults
16473 /// still hold. Born-red: fails if classification, override precedence,
16474 /// or the compaction remap is wrong.
16475 #[test]
16476 fn storage_class_inference_override_and_compaction() {
16477 let mut g = Graph::new();
16478 // A shared weight Const, a session-state KV placeholder Const, a
16479 // transient activation, and an in-place cache-write target.
16480 let weight = g.push(Node {
16481 op: Op::Const,
16482 inputs: vec![],
16483 shape: Shape::from_dims(&[2]),
16484 dtype: DType::F32,
16485 });
16486 let kv = g.push(Node {
16487 op: Op::Const,
16488 inputs: vec![],
16489 shape: Shape::from_dims(&[2]),
16490 dtype: DType::F32,
16491 });
16492 let act = g.push(Node {
16493 op: Op::Relu,
16494 inputs: vec![weight],
16495 shape: Shape::from_dims(&[2]),
16496 dtype: DType::F32,
16497 });
16498 let write = g.push(Node {
16499 op: Op::WriteSlice {
16500 ranges: vec![(0, 2)],
16501 dyn_offset: None,
16502 },
16503 inputs: vec![kv, act],
16504 shape: Shape::from_dims(&[2]),
16505 dtype: DType::F32,
16506 });
16507
16508 // Op-inferred defaults.
16509 assert_eq!(
16510 g.storage_class(weight),
16511 StorageClass::Shared,
16512 "Const → Shared"
16513 );
16514 assert_eq!(
16515 g.storage_class(act),
16516 StorageClass::Transient,
16517 "activation → Transient"
16518 );
16519 assert_eq!(
16520 g.storage_class(write),
16521 StorageClass::SessionState,
16522 "WriteSlice → SessionState"
16523 );
16524 // No overrides set yet.
16525 assert_eq!(
16526 g.storage_class(kv),
16527 StorageClass::Shared,
16528 "KV placeholder Const infers Shared before override"
16529 );
16530 assert!(!g.has_storage_class_override(kv));
16531 assert_eq!(g.storage_class_override_count(), 0);
16532
16533 // Explicit override: the KV placeholder is session state, not a
16534 // shared weight.
16535 g.set_storage_class(kv, StorageClass::SessionState);
16536 assert_eq!(
16537 g.storage_class(kv),
16538 StorageClass::SessionState,
16539 "override beats inferred default"
16540 );
16541 assert!(g.has_storage_class_override(kv));
16542 assert_eq!(g.storage_class_override_count(), 1);
16543
16544 // Compaction carries the override to the new id; inferred defaults
16545 // (no side-table entry) still resolve from the op.
16546 let remap = compact(&mut g, &[write]);
16547 let n_kv = remap.get(kv).expect("kv survives (input of write)");
16548 let n_weight = remap
16549 .get(weight)
16550 .expect("weight survives (transitively under act)");
16551 let n_write = remap.get(write).expect("write is the root");
16552 assert_eq!(
16553 g.storage_class(n_kv),
16554 StorageClass::SessionState,
16555 "override remapped by compact"
16556 );
16557 assert!(g.has_storage_class_override(n_kv));
16558 assert_eq!(
16559 g.storage_class_override_count(),
16560 1,
16561 "exactly the one override survives"
16562 );
16563 assert_eq!(
16564 g.storage_class(n_weight),
16565 StorageClass::Shared,
16566 "inferred Shared still holds post-compact"
16567 );
16568 assert_eq!(
16569 g.storage_class(n_write),
16570 StorageClass::SessionState,
16571 "inferred SessionState still holds post-compact"
16572 );
16573 assert!(g.verify_no_dangling().is_ok());
16574 }
16575
16576 /// (a) A deliberately-orphaned node (pushed, referenced by nothing) is
16577 /// dropped by `compact`; the node count shrinks by exactly the orphan
16578 /// count, and every still-reachable node survives.
16579 #[test]
16580 fn compact_drops_orphan_debris() {
16581 let mut g = Graph::new();
16582 let a = g.push(Node {
16583 op: Op::Const,
16584 inputs: vec![],
16585 shape: Shape::from_dims(&[2]),
16586 dtype: DType::F32,
16587 });
16588 let b = g.push(Node {
16589 op: Op::Relu,
16590 inputs: vec![a],
16591 shape: Shape::from_dims(&[2]),
16592 dtype: DType::F32,
16593 });
16594 let c = g.push(Node {
16595 op: Op::Silu,
16596 inputs: vec![b],
16597 shape: Shape::from_dims(&[2]),
16598 dtype: DType::F32,
16599 });
16600 // Two pieces of exploration debris: reachable from nothing in the
16601 // live structure (no root, no side-effect, no branch references them).
16602 let _orphan0 = g.push(Node {
16603 op: Op::Const,
16604 inputs: vec![],
16605 shape: Shape::from_dims(&[2]),
16606 dtype: DType::F32,
16607 });
16608 let _orphan1 = g.push(Node {
16609 op: Op::Tanh,
16610 inputs: vec![_orphan0],
16611 shape: Shape::from_dims(&[2]),
16612 dtype: DType::F32,
16613 });
16614
16615 let before = g.len();
16616 let remap = compact(&mut g, &[c]);
16617
16618 assert_eq!(
16619 g.len(),
16620 before - 2,
16621 "compaction drops exactly the two orphan-debris nodes",
16622 );
16623 // The three reachable nodes all survived (have new ids).
16624 assert!(remap.get(a).is_some());
16625 assert!(remap.get(b).is_some());
16626 assert!(remap.get(c).is_some());
16627 // The orphans are gone.
16628 assert!(remap.get(_orphan0).is_none());
16629 assert!(remap.get(_orphan1).is_none());
16630 // The surviving chain still resolves: c' reads b' reads a'.
16631 let (na, nb, nc) = (
16632 remap.get(a).unwrap(),
16633 remap.get(b).unwrap(),
16634 remap.get(c).unwrap(),
16635 );
16636 assert_eq!(g.node(nc).inputs, vec![nb]);
16637 assert_eq!(g.node(nb).inputs, vec![na]);
16638 assert_eq!(g.node(na).inputs, Vec::<NodeId>::new());
16639 assert_no_dangling(&g);
16640 }
16641
16642 /// (b) Branches preserved: a graph with a finalized `Op::Branch` keeps
16643 /// every arm + `reconverge_at` after compaction (remapped), and the
16644 /// arm-0 lowering yields the same logical route.
16645 #[test]
16646 fn compact_preserves_branch_arms_and_reconverge() {
16647 let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch_b4();
16648
16649 // Inject orphan debris so compaction has something to drop and the
16650 // surviving-branch claim is non-trivial.
16651 let _debris = g.push(Node {
16652 op: Op::Const,
16653 inputs: vec![],
16654 shape: Shape::from_dims(&[2]),
16655 dtype: DType::F32,
16656 });
16657
16658 // Baseline arm-0 route over old ids, mapped to the op sequence.
16659 let before_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16660 .iter()
16661 .map(|&id| g.node(id).op.short_name())
16662 .collect();
16663
16664 let remap = compact(&mut g, &[post]);
16665
16666 // Every branch participant survived.
16667 let narm0 = remap.get(arm0).expect("arm0 survives");
16668 let narm1 = remap
16669 .get(arm1)
16670 .expect("arm1 (the non-fallback arm) survives");
16671 let nrecon = remap.get(reconverge).expect("reconverge survives");
16672 let nbranch = remap.get(branch).expect("the Branch node itself survives");
16673 let npost = remap.get(post).expect("post survives");
16674
16675 // The Branch's inputs are the remapped arm exits (arm0 first), and
16676 // its reconverge_at is the remapped reconverge — it still resolves.
16677 let bn = g.node(nbranch);
16678 assert!(matches!(bn.op, Op::Branch { .. }));
16679 assert_eq!(
16680 bn.inputs,
16681 vec![narm0, narm1],
16682 "arm exits remapped, arm0 first"
16683 );
16684 match bn.op {
16685 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, nrecon),
16686 ref other => panic!("expected Op::Branch, got {other:?}"),
16687 }
16688 // reconverge still reads arm0 (runnability preserved through remap).
16689 assert!(g.node(nrecon).inputs.contains(&narm0));
16690 // The arm-0 route is logically identical (same op sequence).
16691 let after_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16692 .iter()
16693 .map(|&id| g.node(id).op.short_name())
16694 .collect();
16695 assert_eq!(before_ops, after_ops, "arm-0 route is logically unchanged");
16696 assert_no_dangling(&g);
16697 }
16698
16699 /// (c) Base map preserved: a branchless, fully-reachable graph compacts
16700 /// to itself — no node dropped; ids may renumber but the structure is
16701 /// identical.
16702 #[test]
16703 fn compact_branchless_reachable_is_identity_in_structure() {
16704 let mut g = Graph::new();
16705 let a = g.push(Node {
16706 op: Op::Const,
16707 inputs: vec![],
16708 shape: Shape::from_dims(&[2]),
16709 dtype: DType::F32,
16710 });
16711 let b = g.push(Node {
16712 op: Op::Relu,
16713 inputs: vec![a],
16714 shape: Shape::from_dims(&[2]),
16715 dtype: DType::F32,
16716 });
16717 let c = g.push(Node {
16718 op: Op::Silu,
16719 inputs: vec![b],
16720 shape: Shape::from_dims(&[2]),
16721 dtype: DType::F32,
16722 });
16723 let d = g.push(Node {
16724 op: Op::Tanh,
16725 inputs: vec![c],
16726 shape: Shape::from_dims(&[2]),
16727 dtype: DType::F32,
16728 });
16729
16730 let before_ops: Vec<&'static str> = extract_runs(&g, d)
16731 .iter()
16732 .flat_map(|r| {
16733 r.members
16734 .iter()
16735 .map(|&id| g.node(id).op.short_name())
16736 .collect::<Vec<_>>()
16737 })
16738 .collect();
16739 let before_len = g.len();
16740
16741 let remap = compact(&mut g, &[d]);
16742
16743 assert_eq!(g.len(), before_len, "a fully-reachable graph drops nothing");
16744 for n in [a, b, c, d] {
16745 assert!(remap.get(n).is_some(), "every node survives");
16746 }
16747 // Structure identical: same op sequence over the compacted graph.
16748 let nd = remap.get(d).unwrap();
16749 let after_ops: Vec<&'static str> = extract_runs(&g, nd)
16750 .iter()
16751 .flat_map(|r| {
16752 r.members
16753 .iter()
16754 .map(|&id| g.node(id).op.short_name())
16755 .collect::<Vec<_>>()
16756 })
16757 .collect();
16758 assert_eq!(before_ops, after_ops);
16759 assert_no_dangling(&g);
16760 }
16761
16762 /// (d) No dangling + round-trip: after `compact`, NO NodeId reference
16763 /// (node inputs, op-carried `reconverge_at`, or any side-table) points
16764 /// outside the new arena, AND `extract_runs` / arm-0 lowering on the
16765 /// compacted graph yields the identical logical result, including for
16766 /// graphs carrying every side-table (placements, target_backends,
16767 /// layouts, storage_map, node_output_views, side_effect_roots).
16768 #[test]
16769 fn compact_no_dangling_and_round_trip_with_side_tables() {
16770 let (mut g, diverge, arm0, _arm1, reconverge, _branch, post) = diamond_with_branch_b4();
16771
16772 // Populate side-tables on surviving nodes so the remap must carry
16773 // them. (target_backend on a couple nodes; placement on one.)
16774 g.set_target_backend(arm0, BackendId::Cpu);
16775 g.set_target_backend(reconverge, BackendId::Cpu);
16776 g.set_placement(diverge, DeviceLocation::Cpu);
16777 // A side-effect root that is itself orphan-from-roots: a Release-like
16778 // op the executor must keep even though no output reads it.
16779 let se = g.push(Node {
16780 op: Op::Const,
16781 inputs: vec![post],
16782 shape: Shape::from_dims(&[2]),
16783 dtype: DType::F32,
16784 });
16785 g.add_side_effect_root(se);
16786
16787 // Orphan debris (referenced by nothing live) to force a real drop.
16788 let _debris = g.push(Node {
16789 op: Op::Const,
16790 inputs: vec![],
16791 shape: Shape::from_dims(&[2]),
16792 dtype: DType::F32,
16793 });
16794
16795 let before_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16796 .iter()
16797 .map(|&id| g.node(id).op.short_name())
16798 .collect();
16799
16800 let remap = compact(&mut g, &[post]);
16801
16802 // No dangling references anywhere.
16803 assert_no_dangling(&g);
16804
16805 // The side-effect root survived (a side-effect-only node is a
16806 // reachability seed) and its side-table entry was remapped.
16807 let nse = remap.get(se).expect("side-effect root survives compaction");
16808 assert!(
16809 g.side_effect_roots().contains(&nse),
16810 "the remapped side-effect root is registered post-compaction",
16811 );
16812 // The surviving target_backend side-table is keyed by the new ids.
16813 assert_eq!(
16814 g.target_backend(remap.get(arm0).unwrap()),
16815 Some(BackendId::Cpu)
16816 );
16817 assert_eq!(
16818 g.target_backend(remap.get(reconverge).unwrap()),
16819 Some(BackendId::Cpu)
16820 );
16821 assert_eq!(
16822 g.placement(remap.get(diverge).unwrap()),
16823 Some(DeviceLocation::Cpu)
16824 );
16825
16826 // Round-trip: the arm-0 route is logically identical.
16827 let npost = remap.get(post).unwrap();
16828 let after_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16829 .iter()
16830 .map(|&id| g.node(id).op.short_name())
16831 .collect();
16832 assert_eq!(
16833 before_run_ops, after_run_ops,
16834 "compaction preserves the realized arm-0 route exactly",
16835 );
16836 }
16837
16838 /// Helper: assert NO NodeId reference in the graph points outside the
16839 /// arena. Covers node `inputs`, the op-carried `Op::Branch.reconverge_at`,
16840 /// every NodeId-keyed side-table, and the `side_effect_roots` vec — the
16841 /// exhaustive no-dangling safety net for a missed remap.
16842 fn assert_no_dangling(g: &Graph) {
16843 let n = g.len();
16844 let ok = |id: NodeId| id.0 < n;
16845 for i in 0..n {
16846 let node = g.node(NodeId(i));
16847 for &inp in &node.inputs {
16848 assert!(ok(inp), "Node#{i} input {:?} dangles (len={n})", inp);
16849 }
16850 if let Op::Branch { reconverge_at } = node.op {
16851 assert!(
16852 ok(reconverge_at),
16853 "Node#{i} Branch.reconverge_at {:?} dangles (len={n})",
16854 reconverge_at
16855 );
16856 }
16857 }
16858 for &r in g.side_effect_roots() {
16859 assert!(ok(r), "side_effect_root {:?} dangles (len={n})", r);
16860 }
16861 // Use the graph's own verification entry point as the load-bearing
16862 // assert (it covers every side-table by reading the private fields).
16863 assert!(
16864 g.verify_no_dangling().is_ok(),
16865 "Graph::verify_no_dangling found a dangling reference: {:?}",
16866 g.verify_no_dangling().err(),
16867 );
16868 }
16869
16870 #[test]
16871 fn scan_variants_construct_and_name() {
16872 use crate::{Graph, Node, Op, ScanEmit, ScanPredicate, ScanRole};
16873 use fuel_ir::{DType, Shape};
16874 let mut g = Graph::new();
16875 let s = Shape::from_dims(&[1, 1, 1]);
16876 let carry = g.push(Node {
16877 op: Op::Const,
16878 inputs: vec![],
16879 shape: s.clone(),
16880 dtype: DType::F32,
16881 });
16882 // A ScanPlaceholder leaf (the per-step carry hole).
16883 let hole = g.push(Node {
16884 op: Op::ScanPlaceholder {
16885 role: ScanRole::Carry,
16886 index: 0,
16887 },
16888 inputs: vec![],
16889 shape: s.clone(),
16890 dtype: DType::F32,
16891 });
16892 // A trivial body: new_carry = hole (identity); body_y = hole.
16893 // Op::Scan node: inputs = [init_carry, <no xs>, <no consts>, body_new_carry, body_y].
16894 let scan = g.push(Node {
16895 op: Op::Scan {
16896 n_carries: 1,
16897 n_xs: 0,
16898 bound: 1,
16899 emit: ScanEmit::All,
16900 early_exit: None,
16901 },
16902 inputs: vec![carry, hole, hole],
16903 shape: s.clone(),
16904 dtype: DType::F32,
16905 });
16906 assert_eq!(g.node(scan).op.short_name(), "Scan");
16907 assert_eq!(g.node(hole).op.short_name(), "ScanPlaceholder");
16908 // early_exit is constructible (guarded elsewhere) but never Some on a live path.
16909 let _guarded = Op::Scan {
16910 n_carries: 1,
16911 n_xs: 0,
16912 bound: 1,
16913 emit: ScanEmit::Final,
16914 early_exit: Some(ScanPredicate),
16915 };
16916 // derive_view_output_layout: Scan is NOT a view op -> Err (handled by the catch-all).
16917 let lay = fuel_ir::Layout::contiguous(s.clone());
16918 let derived = crate::derive_view_output_layout(
16919 &Op::Scan {
16920 n_carries: 1,
16921 n_xs: 0,
16922 bound: 1,
16923 emit: ScanEmit::All,
16924 early_exit: None,
16925 },
16926 &lay,
16927 );
16928 assert!(
16929 derived.is_err(),
16930 "Op::Scan must not be treated as a view op"
16931 );
16932 let _ = scan;
16933 }
16934
16935 #[test]
16936 fn scan_builder_all_and_final_shapes() {
16937 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
16938 use fuel_ir::{DType, Shape};
16939 use std::sync::{Arc, RwLock};
16940 let graph = Arc::new(RwLock::new(Graph::new()));
16941 let cs = Shape::from_dims(&[2]); // carry shape
16942 let ys = Shape::from_dims(&[2]); // per-step y shape
16943 let (carry, hole, new_carry, body_y) = {
16944 let mut g = graph.write().unwrap();
16945 let carry = g.push(Node {
16946 op: Op::Const,
16947 inputs: vec![],
16948 shape: cs.clone(),
16949 dtype: DType::F32,
16950 });
16951 let hole = g.push(Node {
16952 op: Op::ScanPlaceholder {
16953 role: ScanRole::Carry,
16954 index: 0,
16955 },
16956 inputs: vec![],
16957 shape: cs.clone(),
16958 dtype: DType::F32,
16959 });
16960 let new_carry = g.push(Node {
16961 op: Op::MulScalar(2.0),
16962 inputs: vec![hole],
16963 shape: cs.clone(),
16964 dtype: DType::F32,
16965 });
16966 let body_y = g.push(Node {
16967 op: Op::AddScalar(1.0),
16968 inputs: vec![new_carry],
16969 shape: ys.clone(),
16970 dtype: DType::F32,
16971 });
16972 (carry, hole, new_carry, body_y)
16973 };
16974 let t = |id| NodeHandle {
16975 graph: graph.clone(),
16976 id,
16977 }; // same-crate access to private fields
16978 let init = t(carry);
16979 let (nc, by) = (t(new_carry), t(body_y));
16980 let bound = 4usize;
16981
16982 let all = init
16983 .scan(&[], &[], &nc, &by, bound, ScanEmit::All)
16984 .expect("scan All");
16985 assert_eq!(
16986 all.shape().dims(),
16987 &[bound, 2],
16988 "emit=All -> [bound] ++ body_y"
16989 );
16990
16991 // Structural guard (Task-2 review finding): the Op::Scan node's
16992 // inputs MUST end with [.., body_new_carry, body_y] in that
16993 // order — base_map_hash recurses into the last two inputs to
16994 // hash the body, so a reordering would silently hash the wrong
16995 // subgraph. `all` is a View(0) over the producer; its own
16996 // single input is the producer NodeId.
16997 {
16998 let g = graph.read().unwrap();
16999 let producer_id = g.node(all.id()).inputs[0];
17000 let producer_inputs = &g.node(producer_id).inputs;
17001 assert_eq!(
17002 producer_inputs[producer_inputs.len() - 2],
17003 nc.id(),
17004 "Op::Scan inputs[len-2] must be body_new_carry",
17005 );
17006 assert_eq!(
17007 producer_inputs[producer_inputs.len() - 1],
17008 by.id(),
17009 "Op::Scan inputs[len-1] must be body_y",
17010 );
17011 }
17012
17013 let fin = init
17014 .scan(&[], &[], &nc, &by, bound, ScanEmit::Final)
17015 .expect("scan Final");
17016 assert_eq!(fin.shape().dims(), &[2], "emit=Final -> carry shape");
17017 let _ = hole;
17018 }
17019
17020 #[test]
17021 fn scan_builder_rejects_zero_bound() {
17022 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17023 use fuel_ir::{DType, Shape};
17024 use std::sync::{Arc, RwLock};
17025 let graph = Arc::new(RwLock::new(Graph::new()));
17026 let cs = Shape::from_dims(&[1]);
17027 let (carry, new_carry, body_y) = {
17028 let mut g = graph.write().unwrap();
17029 let carry = g.push(Node {
17030 op: Op::Const,
17031 inputs: vec![],
17032 shape: cs.clone(),
17033 dtype: DType::F32,
17034 });
17035 let hole = g.push(Node {
17036 op: Op::ScanPlaceholder {
17037 role: ScanRole::Carry,
17038 index: 0,
17039 },
17040 inputs: vec![],
17041 shape: cs.clone(),
17042 dtype: DType::F32,
17043 });
17044 let nc = g.push(Node {
17045 op: Op::MulScalar(2.0),
17046 inputs: vec![hole],
17047 shape: cs.clone(),
17048 dtype: DType::F32,
17049 });
17050 (carry, nc, nc)
17051 };
17052 let t = |id| NodeHandle {
17053 graph: graph.clone(),
17054 id,
17055 };
17056 let r = t(carry).scan(&[], &[], &t(new_carry), &t(body_y), 0, ScanEmit::All);
17057 assert!(r.is_err(), "bound == 0 must be a typed Err, not a panic");
17058 }
17059
17060 /// Task 5 (C6): every "opt-in" classifier/dispatch site over `Op` must
17061 /// treat the new `Op::Scan` / `Op::ScanPlaceholder` variants via its
17062 /// existing safe-conservative wildcard/allow-list — no site should need
17063 /// a bespoke Scan arm in Phase 1. This is a regression LOCK, not a
17064 /// born-red test: every assertion here is expected to pass immediately
17065 /// because the wildcards already exist; a red assertion means that site
17066 /// silently mishandles Scan and needs a conservative arm added.
17067 ///
17068 /// Also confirms reachability: `Op::Scan`'s body lives in its own
17069 /// `inputs` (like `Op::Branch`'s arms), so the ordinary input-closure
17070 /// walk (`topo_order_multi`) sees body nodes for free — no
17071 /// `effective_roots` / `live_set` edit is needed.
17072 #[test]
17073 fn scan_opt_in_sites_are_safe_defaults() {
17074 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
17075 use fuel_ir::{DType, Shape};
17076 let scan = Op::Scan {
17077 n_carries: 1,
17078 n_xs: 0,
17079 bound: 2,
17080 emit: ScanEmit::All,
17081 early_exit: None,
17082 };
17083 let hole = Op::ScanPlaceholder {
17084 role: ScanRole::Carry,
17085 index: 0,
17086 };
17087 // Classifier defaults.
17088 assert_eq!(scan.destructive_input(), None);
17089 assert_eq!(hole.destructive_input(), None);
17090 assert!(!scan.is_view_op());
17091 assert!(!hole.is_view_op());
17092 assert_eq!(
17093 crate::infer_storage_class(&scan),
17094 crate::StorageClass::Transient
17095 );
17096 assert_eq!(crate::jit::op_to_tag(&scan), None);
17097 // Reachability: build a graph with an Op::Scan whose body references a hole;
17098 // the hole (a body node) is reachable from the Scan via inputs, no seeding.
17099 let mut g = Graph::new();
17100 let s = Shape::from_dims(&[1]);
17101 let carry = g.push(Node {
17102 op: Op::Const,
17103 inputs: vec![],
17104 shape: s.clone(),
17105 dtype: DType::F32,
17106 });
17107 let h = g.push(Node {
17108 op: hole.clone(),
17109 inputs: vec![],
17110 shape: s.clone(),
17111 dtype: DType::F32,
17112 });
17113 let nc = g.push(Node {
17114 op: Op::MulScalar(2.0),
17115 inputs: vec![h],
17116 shape: s.clone(),
17117 dtype: DType::F32,
17118 });
17119 let sc = g.push(Node {
17120 op: scan.clone(),
17121 inputs: vec![carry, nc, nc],
17122 shape: Shape::from_dims(&[2, 1]),
17123 dtype: DType::F32,
17124 });
17125 let reachable = crate::topo_order_multi(&g, &[sc]);
17126 assert!(
17127 reachable.contains(&nc) && reachable.contains(&h),
17128 "body nodes must be reachable from Op::Scan via inputs (no effective_roots edit needed)"
17129 );
17130 }
17131}