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`. Its backward is the same as `Op::GeluTanh`'s.
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 pub fn paged_attn(
4741 &self,
4742 k_cache: &NodeHandle,
4743 v_cache: &NodeHandle,
4744 block_table: &NodeHandle,
4745 context_lens: &NodeHandle,
4746 alibi_slopes: Option<&NodeHandle>,
4747 softmax_scale: f32,
4748 block_size: usize,
4749 softcap: Option<f32>,
4750 ) -> NodeHandle {
4751 let g = &self.graph;
4752 assert!(
4753 Arc::ptr_eq(g, &k_cache.graph),
4754 "paged_attn: q + k_cache must share graph"
4755 );
4756 assert!(
4757 Arc::ptr_eq(g, &v_cache.graph),
4758 "paged_attn: q + v_cache must share graph"
4759 );
4760 assert!(
4761 Arc::ptr_eq(g, &block_table.graph),
4762 "paged_attn: q + block_table must share graph"
4763 );
4764 assert!(
4765 Arc::ptr_eq(g, &context_lens.graph),
4766 "paged_attn: q + context_lens must share graph"
4767 );
4768 if let Some(a) = alibi_slopes {
4769 assert!(
4770 Arc::ptr_eq(g, &a.graph),
4771 "paged_attn: alibi_slopes must share graph"
4772 );
4773 }
4774 assert!(block_size >= 1, "paged_attn: block_size must be ≥ 1");
4775
4776 let q_dims = self.shape();
4777 let q_dims = q_dims.dims();
4778 let kc_dims = k_cache.shape();
4779 let kc_dims = kc_dims.dims();
4780 let vc_dims = v_cache.shape();
4781 let vc_dims = vc_dims.dims();
4782 let bt_dims = block_table.shape();
4783 let bt_dims = bt_dims.dims();
4784 let cl_dims = context_lens.shape();
4785 let cl_dims = cl_dims.dims();
4786 assert_eq!(
4787 q_dims.len(),
4788 4,
4789 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
4790 );
4791 assert_eq!(
4792 kc_dims.len(),
4793 4,
4794 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}"
4795 );
4796 assert_eq!(
4797 vc_dims.len(),
4798 4,
4799 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}"
4800 );
4801 assert_eq!(
4802 bt_dims.len(),
4803 2,
4804 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}"
4805 );
4806 assert_eq!(
4807 cl_dims.len(),
4808 1,
4809 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}"
4810 );
4811 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
4812 assert_eq!(
4813 kc_dims[1], block_size,
4814 "paged_attn: k_cache block dim {} != block_size {block_size}",
4815 kc_dims[1]
4816 );
4817 assert_eq!(
4818 vc_dims[1], block_size,
4819 "paged_attn: v_cache block dim {} != block_size {block_size}",
4820 vc_dims[1]
4821 );
4822 let hkv = kc_dims[2];
4823 assert_eq!(
4824 vc_dims[2], hkv,
4825 "paged_attn: Hkv mismatch k_cache vs v_cache"
4826 );
4827 assert_eq!(kc_dims[3], d, "paged_attn: D mismatch q vs k_cache");
4828 assert_eq!(vc_dims[3], d, "paged_attn: D mismatch q vs v_cache");
4829 assert_eq!(
4830 hq % hkv,
4831 0,
4832 "paged_attn: Hq={hq} must be a multiple of Hkv={hkv}"
4833 );
4834 assert_eq!(
4835 bt_dims[0], b,
4836 "paged_attn: block_table batch dim {} != B={b}",
4837 bt_dims[0]
4838 );
4839 assert_eq!(
4840 cl_dims[0], b,
4841 "paged_attn: context_lens len {} != B={b}",
4842 cl_dims[0]
4843 );
4844 assert_eq!(
4845 block_table.dtype(),
4846 crate::DType::U32,
4847 "paged_attn: block_table must be U32"
4848 );
4849 assert_eq!(
4850 context_lens.dtype(),
4851 crate::DType::U32,
4852 "paged_attn: context_lens must be U32"
4853 );
4854 if let Some(a) = alibi_slopes {
4855 let ad = a.shape();
4856 let ad = ad.dims();
4857 assert_eq!(
4858 ad,
4859 &[hq],
4860 "paged_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
4861 );
4862 }
4863
4864 let dtype = self.dtype();
4865 let mut inputs = vec![
4866 self.id,
4867 k_cache.id,
4868 v_cache.id,
4869 block_table.id,
4870 context_lens.id,
4871 ];
4872 if let Some(a) = alibi_slopes {
4873 inputs.push(a.id);
4874 }
4875 // Phase 7.6 step 4 (final): emits Op::Fused(PAGED_ATTN, _).
4876 let id = self.graph.write().unwrap().push(Node {
4877 op: Op::Fused(
4878 crate::registry::FusedOps::PAGED_ATTN,
4879 crate::registry::FusedOpParams::PagedAttn {
4880 softmax_scale,
4881 block_size,
4882 softcap,
4883 },
4884 ),
4885 inputs,
4886 shape: Shape::from_dims(q_dims),
4887 dtype,
4888 });
4889 Self {
4890 graph: self.graph.clone(),
4891 id,
4892 }
4893 }
4894
4895 /// Append an [`Op::Fused`] node carrying
4896 /// [`crate::registry::FusedOpParams::ConvTranspose2D`]. `self` must be
4897 /// `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
4898 /// (note transposed channel order vs `conv2d`). Returns a rank-4
4899 /// tensor `[N, Cout, Hout, Wout]`.
4900 ///
4901 /// Panics if ranks don't match, channel counts are inconsistent
4902 /// with `groups`, or output spatial dims would be non-positive.
4903 ///
4904 /// # Panics
4905 ///
4906 /// Panics if any operand belongs to a different [`Graph`] than the one this
4907 /// builder is building into. Operand identity is graph-scoped and checked by
4908 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4909 /// deliberate and replaces the hang a cross-graph handle used to produce.
4910 /// Build every operand from one graph, or use a `Result`-returning entry
4911 /// point where one exists.
4912 pub fn conv_transpose2d(
4913 &self,
4914 weight: &NodeHandle,
4915 stride: (usize, usize),
4916 padding: (usize, usize),
4917 output_padding: (usize, usize),
4918 dilation: (usize, usize),
4919 groups: usize,
4920 ) -> NodeHandle {
4921 assert!(
4922 Arc::ptr_eq(&self.graph, &weight.graph),
4923 "conv_transpose2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4924 );
4925 assert!(
4926 groups >= 1,
4927 "conv_transpose2d: groups must be ≥ 1, got {groups}"
4928 );
4929 let x_dims = self.shape();
4930 let x_dims = x_dims.dims();
4931 let w_dims = weight.shape();
4932 let w_dims = w_dims.dims();
4933 assert_eq!(
4934 x_dims.len(),
4935 4,
4936 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4937 );
4938 assert_eq!(
4939 w_dims.len(),
4940 4,
4941 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
4942 );
4943 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4944 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4945 assert_eq!(
4946 cin, cin_w,
4947 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
4948 );
4949 assert_eq!(
4950 cin % groups,
4951 0,
4952 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
4953 );
4954 let cout = cout_per_g * groups;
4955 let (stride_h, stride_w) = stride;
4956 let (pad_h, pad_w) = padding;
4957 let (out_pad_h, out_pad_w) = output_padding;
4958 let (dil_h, dil_w) = dilation;
4959 assert!(
4960 stride_h >= 1 && stride_w >= 1,
4961 "conv_transpose2d: stride must be ≥ 1"
4962 );
4963 assert!(
4964 dil_h >= 1 && dil_w >= 1,
4965 "conv_transpose2d: dilation must be ≥ 1"
4966 );
4967 // Hout = (Hin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1
4968 let h_out = (h_in.saturating_sub(1)) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
4969 let w_out = (w_in.saturating_sub(1)) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
4970 assert!(
4971 h_out > 2 * pad_h && w_out > 2 * pad_w,
4972 "conv_transpose2d: padding ({pad_h}×{pad_w}) is larger than the produced output dims",
4973 );
4974 let h_out = h_out - 2 * pad_h;
4975 let w_out = w_out - 2 * pad_w;
4976 let dtype = self.dtype();
4977 // Phase 7.6 step 4 (final): emits Op::Fused(CONV_TRANSPOSE2D, _).
4978 let id = self.graph.write().unwrap().push(Node {
4979 op: Op::Fused(
4980 crate::registry::FusedOps::CONV_TRANSPOSE2D,
4981 crate::registry::FusedOpParams::ConvTranspose2D {
4982 stride,
4983 padding,
4984 output_padding,
4985 dilation,
4986 groups,
4987 },
4988 ),
4989 inputs: vec![self.id, weight.id],
4990 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4991 dtype,
4992 });
4993 Self {
4994 graph: self.graph.clone(),
4995 id,
4996 }
4997 }
4998
4999 /// Append a transposed 1D convolution by lifting `self` and
5000 /// `weight` into the rank-4 path and dispatching through
5001 /// [`Self::conv_transpose2d`]. `self` is `[N, Cin, Lin]`;
5002 /// `weight` is `[Cin, Cout/groups, K]` (transposed channel
5003 /// order, matches PyTorch). Returns `[N, Cout, Lout]` where
5004 /// `Lout = (Lin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1`.
5005 ///
5006 /// Used by audio codec models (DAC / EnCodec / SNAC / Mimi /
5007 /// Parler-TTS / MetaVoice / CSM) where the decoder upsamples
5008 /// quantized latents back to waveform with strided transposed
5009 /// convs.
5010 ///
5011 /// # Panics
5012 ///
5013 /// Panics if any operand belongs to a different [`Graph`] than the one this
5014 /// builder is building into. Operand identity is graph-scoped and checked by
5015 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5016 /// deliberate and replaces the hang a cross-graph handle used to produce.
5017 /// Build every operand from one graph, or use a `Result`-returning entry
5018 /// point where one exists.
5019 pub fn conv_transpose1d(
5020 &self,
5021 weight: &NodeHandle,
5022 stride: usize,
5023 padding: usize,
5024 output_padding: usize,
5025 dilation: usize,
5026 groups: usize,
5027 ) -> NodeHandle {
5028 self.assert_same_graph(weight, "conv_transpose1d", "weight");
5029 let x_dims = self.shape();
5030 let x_dims = x_dims.dims();
5031 let w_dims = weight.shape();
5032 let w_dims = w_dims.dims();
5033 assert_eq!(
5034 x_dims.len(),
5035 3,
5036 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
5037 );
5038 assert_eq!(
5039 w_dims.len(),
5040 3,
5041 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
5042 );
5043 let (n, cin, l_in) = (x_dims[0], x_dims[1], x_dims[2]);
5044 let (cin_w, cout_per_g, k) = (w_dims[0], w_dims[1], w_dims[2]);
5045 let x4 = self.reshape(Shape::from_dims(&[n, cin, 1, l_in]));
5046 let w4 = weight.reshape(Shape::from_dims(&[cin_w, cout_per_g, 1, k]));
5047 let y4 = x4.conv_transpose2d(
5048 &w4,
5049 (1, stride),
5050 (0, padding),
5051 (0, output_padding),
5052 (1, dilation),
5053 groups,
5054 );
5055 let y_dims = y4.shape();
5056 let y_dims = y_dims.dims();
5057 let (n_o, cout, _h_one, l_out) = (y_dims[0], y_dims[1], y_dims[2], y_dims[3]);
5058 y4.reshape(Shape::from_dims(&[n_o, cout, l_out]))
5059 }
5060
5061 /// Append an [`Op::Fused`] node carrying
5062 /// [`crate::registry::FusedOpParams::FlashAttn`]. `self` is `q` of shape
5063 /// `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]` with
5064 /// `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional) is
5065 /// `[Hq]`. Returns a tensor with `q`'s shape.
5066 /// Build the `flash_attn` node.
5067 ///
5068 /// # Panics
5069 ///
5070 /// Panics if any operand belongs to a different [`Graph`] than the one this
5071 /// builder is building into. Operand identity is graph-scoped and checked by
5072 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5073 /// deliberate and replaces the hang a cross-graph handle used to produce.
5074 /// Build every operand from one graph, or use a `Result`-returning entry
5075 /// point where one exists.
5076 pub fn flash_attn(
5077 &self,
5078 k: &NodeHandle,
5079 v: &NodeHandle,
5080 alibi_slopes: Option<&NodeHandle>,
5081 softmax_scale: f32,
5082 causal: bool,
5083 window_size_left: Option<usize>,
5084 window_size_right: Option<usize>,
5085 softcap: Option<f32>,
5086 ) -> NodeHandle {
5087 assert!(
5088 Arc::ptr_eq(&self.graph, &k.graph),
5089 "flash_attn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5090 );
5091 assert!(
5092 Arc::ptr_eq(&self.graph, &v.graph),
5093 "flash_attn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5094 );
5095 if let Some(a) = alibi_slopes {
5096 assert!(
5097 Arc::ptr_eq(&self.graph, &a.graph),
5098 "flash_attn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5099 );
5100 }
5101 let q_dims = self.shape();
5102 let q_dims = q_dims.dims();
5103 let k_dims = k.shape();
5104 let k_dims = k_dims.dims();
5105 let v_dims = v.shape();
5106 let v_dims = v_dims.dims();
5107 assert_eq!(
5108 q_dims.len(),
5109 4,
5110 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5111 );
5112 assert_eq!(
5113 k_dims.len(),
5114 4,
5115 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}"
5116 );
5117 assert_eq!(
5118 v_dims.len(),
5119 4,
5120 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}"
5121 );
5122 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5123 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5124 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5125 assert_eq!(b, bk, "flash_attn: B mismatch q vs k ({b} vs {bk})");
5126 assert_eq!(b, bv, "flash_attn: B mismatch q vs v");
5127 assert_eq!(hkv, hkv_v, "flash_attn: Hkv mismatch k vs v");
5128 assert_eq!(sk, sk_v, "flash_attn: Sk mismatch k vs v");
5129 assert_eq!(d, dk, "flash_attn: head_dim mismatch q vs k");
5130 assert_eq!(d, dv, "flash_attn: head_dim mismatch q vs v");
5131 assert_eq!(
5132 hq % hkv,
5133 0,
5134 "flash_attn: Hq={hq} must be a multiple of Hkv={hkv}"
5135 );
5136 if let Some(a) = alibi_slopes {
5137 let ad = a.shape();
5138 let ad = ad.dims();
5139 assert_eq!(
5140 ad,
5141 &[hq],
5142 "flash_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5143 );
5144 }
5145 let dtype = self.dtype();
5146 let mut inputs = vec![self.id, k.id, v.id];
5147 if let Some(a) = alibi_slopes {
5148 inputs.push(a.id);
5149 }
5150 // Phase 7.6 step 4 (final): emits Op::Fused(FLASH_ATTN, _).
5151 let id = self.graph.write().unwrap().push(Node {
5152 op: Op::Fused(
5153 crate::registry::FusedOps::FLASH_ATTN,
5154 crate::registry::FusedOpParams::FlashAttn {
5155 softmax_scale,
5156 causal,
5157 window_size_left,
5158 window_size_right,
5159 softcap,
5160 k_len: None,
5161 },
5162 ),
5163 inputs,
5164 shape: Shape::from_dims(&[b, hq, sq, d]),
5165 dtype,
5166 });
5167 Self {
5168 graph: self.graph.clone(),
5169 id,
5170 }
5171 }
5172
5173 /// Append an [`Op::Fused`] node carrying
5174 /// [`crate::registry::FusedOpParams::FlashAttn`] over a fixed-**capacity** K/V whose
5175 /// attended length is a **runtime** value (`k_len`) resolved through
5176 /// the per-pass [`fuel_ir::SymEnv`] at realize, decoupled
5177 /// from K's allocated shape.
5178 ///
5179 /// `self` is `q` of shape `[B, Hq, Sq, D]`; `k`/`v` are the capacity
5180 /// buffers `[B, Hkv, max_seq, D]` (GQA: `Hq % Hkv == 0`). Only the
5181 /// first `k_len.resolve(env)` rows along the K/V length axis are
5182 /// attended; the causal mask (when `causal`) is bottom-right-aligned
5183 /// at offset `k_len - Sq` — the standard FlashAttention-2 convention,
5184 /// equal to `cached_len` in autoregressive decode. Returns a tensor
5185 /// with `q`'s shape.
5186 ///
5187 /// This is the flash counterpart of [`Self::write_slice_dyn`]: the
5188 /// decode KV-cache write appends at the runtime offset and flash
5189 /// attends the runtime prefix, so the graph structure stays
5190 /// identical across tokens (Phase D symbolic extents).
5191 ///
5192 /// # Panics
5193 ///
5194 /// Panics if any operand belongs to a different [`Graph`] than the one this
5195 /// builder is building into. Operand identity is graph-scoped and checked by
5196 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5197 /// deliberate and replaces the hang a cross-graph handle used to produce.
5198 /// Build every operand from one graph, or use a `Result`-returning entry
5199 /// point where one exists.
5200 pub fn flash_attn_dyn(
5201 &self,
5202 k: &NodeHandle,
5203 v: &NodeHandle,
5204 alibi_slopes: Option<&NodeHandle>,
5205 softmax_scale: f32,
5206 causal: bool,
5207 window_size_left: Option<usize>,
5208 window_size_right: Option<usize>,
5209 softcap: Option<f32>,
5210 k_len: fuel_ir::DynScalar,
5211 ) -> NodeHandle {
5212 assert!(
5213 Arc::ptr_eq(&self.graph, &k.graph),
5214 "flash_attn_dyn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5215 );
5216 assert!(
5217 Arc::ptr_eq(&self.graph, &v.graph),
5218 "flash_attn_dyn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5219 );
5220 if let Some(a) = alibi_slopes {
5221 assert!(
5222 Arc::ptr_eq(&self.graph, &a.graph),
5223 "flash_attn_dyn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5224 );
5225 }
5226 let q_dims = self.shape();
5227 let q_dims = q_dims.dims();
5228 let k_dims = k.shape();
5229 let k_dims = k_dims.dims();
5230 let v_dims = v.shape();
5231 let v_dims = v_dims.dims();
5232 assert_eq!(
5233 q_dims.len(),
5234 4,
5235 "flash_attn_dyn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5236 );
5237 assert_eq!(
5238 k_dims.len(),
5239 4,
5240 "flash_attn_dyn: k must be rank 4 [B, Hkv, max_seq, D], got {k_dims:?}"
5241 );
5242 assert_eq!(
5243 v_dims.len(),
5244 4,
5245 "flash_attn_dyn: v must be rank 4 [B, Hkv, max_seq, D], got {v_dims:?}"
5246 );
5247 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5248 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5249 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5250 assert_eq!(b, bk, "flash_attn_dyn: B mismatch q vs k ({b} vs {bk})");
5251 assert_eq!(b, bv, "flash_attn_dyn: B mismatch q vs v");
5252 assert_eq!(hkv, hkv_v, "flash_attn_dyn: Hkv mismatch k vs v");
5253 assert_eq!(
5254 sk, sk_v,
5255 "flash_attn_dyn: capacity (max_seq) mismatch k vs v ({sk} vs {sk_v})"
5256 );
5257 assert_eq!(d, dk, "flash_attn_dyn: head_dim mismatch q vs k");
5258 assert_eq!(d, dv, "flash_attn_dyn: head_dim mismatch q vs v");
5259 assert_eq!(
5260 hq % hkv,
5261 0,
5262 "flash_attn_dyn: Hq={hq} must be a multiple of Hkv={hkv}"
5263 );
5264 // A build-time constant k_len must fit the capacity and cover Sq.
5265 if let fuel_ir::DynScalar::Concrete(kl) = k_len {
5266 assert!(
5267 kl <= sk,
5268 "flash_attn_dyn: k_len ({kl}) exceeds K capacity ({sk})"
5269 );
5270 assert!(
5271 kl >= sq,
5272 "flash_attn_dyn: k_len ({kl}) must be >= Sq ({sq}) for a valid causal prefix"
5273 );
5274 }
5275 if let Some(a) = alibi_slopes {
5276 let ad = a.shape();
5277 let ad = ad.dims();
5278 assert_eq!(
5279 ad,
5280 &[hq],
5281 "flash_attn_dyn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5282 );
5283 }
5284 let dtype = self.dtype();
5285 let mut inputs = vec![self.id, k.id, v.id];
5286 if let Some(a) = alibi_slopes {
5287 inputs.push(a.id);
5288 }
5289 let id = self.graph.write().unwrap().push(Node {
5290 op: Op::Fused(
5291 crate::registry::FusedOps::FLASH_ATTN,
5292 crate::registry::FusedOpParams::FlashAttn {
5293 softmax_scale,
5294 causal,
5295 window_size_left,
5296 window_size_right,
5297 softcap,
5298 k_len: Some(k_len),
5299 },
5300 ),
5301 inputs,
5302 shape: Shape::from_dims(&[b, hq, sq, d]),
5303 dtype,
5304 });
5305 Self {
5306 graph: self.graph.clone(),
5307 id,
5308 }
5309 }
5310
5311 /// Append a `Relu` node `max(0, self)`.
5312 pub fn relu(&self) -> NodeHandle {
5313 self.unary_op(Op::Relu)
5314 }
5315
5316 /// Append a `Sqr` node `self * self`.
5317 pub fn sqr(&self) -> NodeHandle {
5318 self.unary_op(Op::Sqr)
5319 }
5320
5321 /// Append an `Exp` node `e^self`.
5322 pub fn exp(&self) -> NodeHandle {
5323 self.unary_op(Op::Exp)
5324 }
5325
5326 /// Append a `Permute` node rearranging the axes according to `axes`.
5327 /// `out.shape[i] = self.shape[axes[i]]`. The axes vector must be a
5328 /// permutation of `0..rank`. For a rank-3 input with `axes = [2, 0, 1]`,
5329 /// the shape transform is `[a, b, c] → [c, a, b]`.
5330 pub fn permute(&self, axes: &[usize]) -> NodeHandle {
5331 let in_shape = self.shape();
5332 let in_dims = in_shape.dims();
5333 let rank = in_dims.len();
5334 assert_eq!(
5335 axes.len(),
5336 rank,
5337 "permute: axes length {} must equal tensor rank {}",
5338 axes.len(),
5339 rank,
5340 );
5341 // Validate that axes is a permutation of 0..rank.
5342 let mut seen = vec![false; rank];
5343 for &ax in axes {
5344 assert!(
5345 ax < rank,
5346 "permute: axis {ax} out of bounds for rank {rank}"
5347 );
5348 assert!(!seen[ax], "permute: duplicate axis {ax} in axes");
5349 seen[ax] = true;
5350 }
5351 let out_dims: Vec<usize> = axes.iter().map(|&ax| in_dims[ax]).collect();
5352 let dtype = self.dtype();
5353 let id = self.graph.write().unwrap().push(Node {
5354 op: Op::Permute(axes.to_vec()),
5355 inputs: vec![self.id],
5356 shape: Shape::from_dims(&out_dims),
5357 dtype,
5358 });
5359 Self {
5360 graph: self.graph.clone(),
5361 id,
5362 }
5363 }
5364
5365 /// Result-returning sibling of [`Self::permute`]. Surfaces bad
5366 /// axes (wrong length, out-of-bounds entry, or duplicate) as a
5367 /// typed error rather than panicking.
5368 pub fn try_permute(&self, axes: &[usize]) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5369 let in_shape = self.shape();
5370 let rank = in_shape.dims().len();
5371 if axes.len() != rank {
5372 return Err(fuel_ir::Error::Msg(format!(
5373 "permute: axes length {} must equal tensor rank {}",
5374 axes.len(),
5375 rank,
5376 ))
5377 .bt());
5378 }
5379 let mut seen = vec![false; rank];
5380 for &ax in axes {
5381 if ax >= rank {
5382 return Err(fuel_ir::Error::Msg(format!(
5383 "permute: axis {ax} out of bounds for rank {rank}",
5384 ))
5385 .bt());
5386 }
5387 if seen[ax] {
5388 return Err(
5389 fuel_ir::Error::Msg(format!("permute: duplicate axis {ax} in axes",)).bt(),
5390 );
5391 }
5392 seen[ax] = true;
5393 }
5394 let op = Op::Permute(axes.to_vec());
5395 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5396 let id = self.graph.write().unwrap().push(Node {
5397 op,
5398 inputs: vec![self.id],
5399 shape,
5400 dtype,
5401 });
5402 Ok(Self {
5403 graph: self.graph.clone(),
5404 id,
5405 })
5406 }
5407
5408 /// Append a `Transpose` node that swaps the last two dimensions of a
5409 /// tensor of rank ≥ 2. Leading dims are unchanged. For a rank-2
5410 /// tensor this is the ordinary matrix transpose; for higher ranks,
5411 /// every batch slice is transposed independently.
5412 pub fn transpose(&self) -> NodeHandle {
5413 let in_shape = self.shape();
5414 assert!(
5415 in_shape.dims().len() >= 2,
5416 "transpose: input must be rank ≥ 2, got shape {:?}",
5417 in_shape.dims(),
5418 );
5419 let op = Op::Transpose;
5420 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
5421 .expect("transpose: rank validated above");
5422 let id = self.graph.write().unwrap().push(Node {
5423 op,
5424 inputs: vec![self.id],
5425 shape,
5426 dtype,
5427 });
5428 Self {
5429 graph: self.graph.clone(),
5430 id,
5431 }
5432 }
5433
5434 /// Result-returning sibling of [`Self::transpose`]. Surfaces
5435 /// rank < 2 as a typed error rather than panicking.
5436 pub fn try_transpose(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5437 let in_shape = self.shape();
5438 if in_shape.dims().len() < 2 {
5439 return Err(fuel_ir::Error::Msg(format!(
5440 "transpose: input must be rank ≥ 2, got shape {:?}",
5441 in_shape.dims(),
5442 ))
5443 .bt());
5444 }
5445 let op = Op::Transpose;
5446 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5447 let id = self.graph.write().unwrap().push(Node {
5448 op,
5449 inputs: vec![self.id],
5450 shape,
5451 dtype,
5452 });
5453 Ok(Self {
5454 graph: self.graph.clone(),
5455 id,
5456 })
5457 }
5458
5459 // --- additional element-wise binary ops ---
5460
5461 /// Append a `Sub` node `self - other`. Requires matching shapes and dtypes.
5462 ///
5463 /// # Panics
5464 ///
5465 /// Panics if any operand belongs to a different [`Graph`] than the one this
5466 /// builder is building into. Operand identity is graph-scoped and checked by
5467 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5468 /// deliberate and replaces the hang a cross-graph handle used to produce.
5469 /// Build every operand from one graph, or use a `Result`-returning entry
5470 /// point where one exists.
5471 pub fn sub(&self, other: &NodeHandle) -> NodeHandle {
5472 self.binary_op("sub", Op::Sub, other, self.shape())
5473 }
5474
5475 /// Append a `Div` node `self / other`. Requires matching shapes and dtypes.
5476 ///
5477 /// # Panics
5478 ///
5479 /// Panics if any operand belongs to a different [`Graph`] than the one this
5480 /// builder is building into. Operand identity is graph-scoped and checked by
5481 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5482 /// deliberate and replaces the hang a cross-graph handle used to produce.
5483 /// Build every operand from one graph, or use a `Result`-returning entry
5484 /// point where one exists.
5485 pub fn div(&self, other: &NodeHandle) -> NodeHandle {
5486 self.binary_op("div", Op::Div, other, self.shape())
5487 }
5488
5489 // --- additional element-wise unary ops ---
5490
5491 /// Append a `Neg` node `-self`.
5492 pub fn neg(&self) -> NodeHandle {
5493 self.unary_op(Op::Neg)
5494 }
5495
5496 /// Append a `Sqrt` node `sqrt(self)`.
5497 pub fn sqrt(&self) -> NodeHandle {
5498 self.unary_op(Op::Sqrt)
5499 }
5500
5501 /// Append a `Log` node `ln(self)`.
5502 pub fn log(&self) -> NodeHandle {
5503 self.unary_op(Op::Log)
5504 }
5505
5506 /// Append a `Sin` node.
5507 pub fn sin(&self) -> NodeHandle {
5508 self.unary_op(Op::Sin)
5509 }
5510
5511 /// Append a `Cos` node.
5512 pub fn cos(&self) -> NodeHandle {
5513 self.unary_op(Op::Cos)
5514 }
5515
5516 /// Append a `Tanh` node.
5517 pub fn tanh(&self) -> NodeHandle {
5518 self.unary_op(Op::Tanh)
5519 }
5520
5521 /// Append a `Sigmoid` node.
5522 pub fn sigmoid(&self) -> NodeHandle {
5523 self.unary_op(Op::Sigmoid)
5524 }
5525
5526 /// Append a `Silu` node (SiLU/Swish activation: `x · sigmoid(x)`).
5527 pub fn silu(&self) -> NodeHandle {
5528 self.unary_op(Op::Silu)
5529 }
5530
5531 /// Append a `GeluTanh` node (tanh-approximation GELU).
5532 pub fn gelu_tanh(&self) -> NodeHandle {
5533 self.unary_op(Op::GeluTanh)
5534 }
5535
5536 /// Append a `Step` node (Heaviside step: `1` where `x > 0`, else `0`).
5537 pub fn step(&self) -> NodeHandle {
5538 self.unary_op(Op::Step)
5539 }
5540
5541 /// Append a `Recip` node (`1 / self`).
5542 pub fn recip(&self) -> NodeHandle {
5543 self.unary_op(Op::Recip)
5544 }
5545
5546 /// Append an `Abs` node (`|self|`).
5547 pub fn abs(&self) -> NodeHandle {
5548 self.unary_op(Op::Abs)
5549 }
5550
5551 // ---- In-place unary builders (Phase 2 of the in-place ops
5552 // infrastructure) ----
5553 //
5554 // Each emits an `Op::*Inplace` node whose input is `self`. The
5555 // returned `NodeHandle` shares the underlying graph and is the new
5556 // root; subsequent ops should use the returned handle to make the
5557 // mutation-after-read ordering observable to `derive_ordering`.
5558 //
5559 // Phase 4 (the mutation-safety pass) is what makes these safe to
5560 // call on tape-tracked tensors. Until Phase 4 lands, calling these
5561 // on a tensor that's been saved for backward will panic at
5562 // `NodeHandle::backward` time (clear error, no silent gradient
5563 // corruption).
5564
5565 /// Append a `ReluInplace` node — mutates `self`'s storage with
5566 /// `max(0, self)`. See `NodeHandle::relu` for the functional variant.
5567 pub fn relu_inplace(&self) -> NodeHandle {
5568 self.unary_op(Op::ReluInplace)
5569 }
5570
5571 /// Append a `SiluInplace` node — mutates `self`'s storage with
5572 /// `self * sigmoid(self)`. See `NodeHandle::silu` for the functional
5573 /// variant.
5574 pub fn silu_inplace(&self) -> NodeHandle {
5575 self.unary_op(Op::SiluInplace)
5576 }
5577
5578 /// Append a `GeluTanhInplace` node — mutates `self`'s storage with
5579 /// the tanh-approximation GELU. See `NodeHandle::gelu_tanh` for the
5580 /// functional variant.
5581 pub fn gelu_tanh_inplace(&self) -> NodeHandle {
5582 self.unary_op(Op::GeluTanhInplace)
5583 }
5584
5585 /// Append a `TanhInplace` node — mutates `self`'s storage with
5586 /// `tanh(self)`. See `NodeHandle::tanh` for the functional variant.
5587 pub fn tanh_inplace(&self) -> NodeHandle {
5588 self.unary_op(Op::TanhInplace)
5589 }
5590
5591 /// Append a `SigmoidInplace` node — mutates `self`'s storage
5592 /// with `sigmoid(self)`. See `NodeHandle::sigmoid` for the functional
5593 /// variant.
5594 pub fn sigmoid_inplace(&self) -> NodeHandle {
5595 self.unary_op(Op::SigmoidInplace)
5596 }
5597
5598 /// Append a `NegInplace` node — mutates `self`'s storage with
5599 /// `-self`. See `NodeHandle::neg` for the functional variant.
5600 pub fn neg_inplace(&self) -> NodeHandle {
5601 self.unary_op(Op::NegInplace)
5602 }
5603
5604 /// Append an `AbsInplace` node — mutates `self`'s storage with
5605 /// `|self|`. See `NodeHandle::abs` for the functional variant.
5606 pub fn abs_inplace(&self) -> NodeHandle {
5607 self.unary_op(Op::AbsInplace)
5608 }
5609
5610 /// Append a `SqrInplace` node — mutates `self`'s storage with
5611 /// `self²`. See `NodeHandle::sqr` for the functional variant.
5612 pub fn sqr_inplace(&self) -> NodeHandle {
5613 self.unary_op(Op::SqrInplace)
5614 }
5615
5616 /// Append a `SqrtInplace` node — mutates `self`'s storage with
5617 /// `√self`. See `NodeHandle::sqrt` for the functional variant.
5618 pub fn sqrt_inplace(&self) -> NodeHandle {
5619 self.unary_op(Op::SqrtInplace)
5620 }
5621
5622 /// Append a `RsqrtInplace` node — mutates `self`'s storage with
5623 /// `1/√self`. See `NodeHandle::rsqrt` for the functional variant.
5624 pub fn rsqrt_inplace(&self) -> NodeHandle {
5625 self.unary_op(Op::RsqrtInplace)
5626 }
5627
5628 /// Append a `RecipInplace` node — mutates `self`'s storage with
5629 /// `1/self`. See `NodeHandle::recip` for the functional variant.
5630 pub fn recip_inplace(&self) -> NodeHandle {
5631 self.unary_op(Op::RecipInplace)
5632 }
5633
5634 /// Append an `ExpInplace` node — mutates `self`'s storage with
5635 /// `exp(self)`. See `NodeHandle::exp` for the functional variant.
5636 pub fn exp_inplace(&self) -> NodeHandle {
5637 self.unary_op(Op::ExpInplace)
5638 }
5639
5640 /// Append a `LogInplace` node — mutates `self`'s storage with
5641 /// `ln(self)`. See `NodeHandle::log` for the functional variant.
5642 pub fn log_inplace(&self) -> NodeHandle {
5643 self.unary_op(Op::LogInplace)
5644 }
5645
5646 /// Append a `SinInplace` node — mutates `self`'s storage with
5647 /// `sin(self)`. See `NodeHandle::sin` for the functional variant.
5648 pub fn sin_inplace(&self) -> NodeHandle {
5649 self.unary_op(Op::SinInplace)
5650 }
5651
5652 /// Append a `CosInplace` node — mutates `self`'s storage with
5653 /// `cos(self)`. See `NodeHandle::cos` for the functional variant.
5654 pub fn cos_inplace(&self) -> NodeHandle {
5655 self.unary_op(Op::CosInplace)
5656 }
5657
5658 /// Append a `SignInplace` node — mutates `self`'s storage with
5659 /// `sign(self)`. See `NodeHandle::sign` for the functional variant.
5660 pub fn sign_inplace(&self) -> NodeHandle {
5661 self.unary_op(Op::SignInplace)
5662 }
5663
5664 /// Append a `FloorInplace` node — mutates `self`'s storage with
5665 /// `⌊self⌋`. See `NodeHandle::floor` for the functional variant.
5666 pub fn floor_inplace(&self) -> NodeHandle {
5667 self.unary_op(Op::FloorInplace)
5668 }
5669
5670 /// Append a `CeilInplace` node — mutates `self`'s storage with
5671 /// `⌈self⌉`. See `NodeHandle::ceil` for the functional variant.
5672 pub fn ceil_inplace(&self) -> NodeHandle {
5673 self.unary_op(Op::CeilInplace)
5674 }
5675
5676 /// Append a `RoundInplace` node — mutates `self`'s storage with
5677 /// `round(self)`. See `NodeHandle::round` for the functional variant.
5678 pub fn round_inplace(&self) -> NodeHandle {
5679 self.unary_op(Op::RoundInplace)
5680 }
5681
5682 /// Append an `ErfInplace` node — mutates `self`'s storage with
5683 /// `erf(self)`. See `NodeHandle::erf` for the functional variant.
5684 pub fn erf_inplace(&self) -> NodeHandle {
5685 self.unary_op(Op::ErfInplace)
5686 }
5687
5688 /// Append a `GeluInplace` node — mutates `self`'s storage
5689 /// with the exact-GeLU formula. See `NodeHandle::gelu` for the
5690 /// functional variant.
5691 pub fn gelu_inplace(&self) -> NodeHandle {
5692 self.unary_op(Op::GeluInplace)
5693 }
5694
5695 /// Append a `ClampInplace { min, max }` node — mutates `self`'s
5696 /// storage with `clamp(self, min, max)`. See `NodeHandle::clamp` for
5697 /// the functional variant.
5698 pub fn clamp_inplace(&self, min: f64, max: f64) -> NodeHandle {
5699 self.unary_op(Op::ClampInplace { min, max })
5700 }
5701
5702 /// Append a `PowIInplace(exp)` node — mutates `self`'s storage
5703 /// with `self.powi(exp)`. See `NodeHandle::powi` for the functional
5704 /// variant.
5705 pub fn powi_inplace(&self, exp: i32) -> NodeHandle {
5706 self.unary_op(Op::PowIInplace(exp))
5707 }
5708
5709 /// Append an `Op::Fused(INPLACE_AFFINE, ...)` node — mutates
5710 /// `self`'s storage with `self = mul · self + add`. Single-input
5711 /// fused op (no functional `Op::Affine` exists on
5712 /// `fuel-graph::Op`; the non-inplace equivalent is `self
5713 /// .mul_scalar(mul).add_scalar(add)`). Wired to baracuda's
5714 /// `affine_inplace_*` symbol on CUDA when Phase 3 lands.
5715 pub fn affine_inplace(&self, mul: f64, add: f64) -> NodeHandle {
5716 let shape = self.shape();
5717 let dtype = self.dtype();
5718 let id = self.graph.write().unwrap().push(Node {
5719 op: Op::Fused(
5720 crate::registry::FusedOps::INPLACE_AFFINE,
5721 crate::registry::FusedOpParams::InplaceAffine { mul, add },
5722 ),
5723 inputs: vec![self.id],
5724 shape,
5725 dtype,
5726 });
5727 Self {
5728 graph: self.graph.clone(),
5729 id,
5730 }
5731 }
5732
5733 /// Append a `Floor` node (`⌊self⌋`). Output dtype = input dtype.
5734 /// Backward is the zero distribution almost everywhere; gradient
5735 /// is dropped silently.
5736 pub fn floor(&self) -> NodeHandle {
5737 self.unary_op(Op::Floor)
5738 }
5739
5740 /// Append a `Ceil` node (`⌈self⌉`). Output dtype = input dtype.
5741 /// Backward drops gradient (non-differentiable almost everywhere).
5742 pub fn ceil(&self) -> NodeHandle {
5743 self.unary_op(Op::Ceil)
5744 }
5745
5746 /// Append a `Round` node — banker's rounding (round-half-to-even,
5747 /// IEEE 754 roundeven). 0.5 → 0, 1.5 → 2, 2.5 → 2, 3.5 → 4.
5748 /// Output dtype = input dtype. Backward drops gradient.
5749 pub fn round(&self) -> NodeHandle {
5750 self.unary_op(Op::Round)
5751 }
5752
5753 /// Append a `Sign` node (`-1` / `0` / `1`). `sign(0) = 0` by
5754 /// subgradient convention. Output dtype = input dtype. Backward
5755 /// drops gradient.
5756 pub fn sign(&self) -> NodeHandle {
5757 self.unary_op(Op::Sign)
5758 }
5759
5760 /// Append an `Erf` node (Gauss error function). Output dtype =
5761 /// input dtype. Differentiable.
5762 pub fn erf(&self) -> NodeHandle {
5763 self.unary_op(Op::Erf)
5764 }
5765
5766 /// Append a `Gelu` node — exact-erf formulation of GELU
5767 /// (`0.5 * x * (1 + erf(x/√2))`). Distinct from [`Self::gelu_tanh`]
5768 /// (tanh approximation). Output dtype = input dtype.
5769 /// Differentiable.
5770 pub fn gelu(&self) -> NodeHandle {
5771 self.unary_op(Op::Gelu)
5772 }
5773
5774 /// Append a `Pow` node `pow(self, other)` element-wise (real
5775 /// exponent). Both operands must share dtype and shape. Distinct
5776 /// from [`Self::powi`] (scalar `i32` exponent). NaN follows
5777 /// IEEE-754 (`pow(-2, 0.5) = NaN`).
5778 ///
5779 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5780 /// typed error, not a panic.
5781 pub fn pow(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5782 let out_shape = self.shape();
5783 self.try_binary_op("pow", Op::Pow, other, out_shape)
5784 }
5785
5786 /// Append an `Rsqrt` node (`1 / sqrt(self)`). Same dtype as
5787 /// input. Single op rather than `sqrt(x).recip()` — one kernel
5788 /// launch and matches RMSNorm's `x * rsqrt(...)` shape.
5789 /// Differentiable.
5790 pub fn rsqrt(&self) -> NodeHandle {
5791 self.unary_op(Op::Rsqrt)
5792 }
5793
5794 /// Append a `Rem` node `self % other` element-wise (PyTorch
5795 /// convention: `a - floor(a/b) * b`, sign of result matches
5796 /// divisor). Both operands must share dtype and shape.
5797 /// Differentiable.
5798 ///
5799 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5800 /// typed error, not a panic.
5801 pub fn rem(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5802 let out_shape = self.shape();
5803 self.try_binary_op("rem", Op::Rem, other, out_shape)
5804 }
5805
5806 /// Append a `Flip` node — reverses element order along `dim`.
5807 /// Output shape == input shape. Materializing op (real byte
5808 /// shuffle; not a metadata-only view). Differentiable
5809 /// (involutive: backward is another Flip on the same dim).
5810 ///
5811 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5812 pub fn flip(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5813 let in_shape = self.shape();
5814 let rank = in_shape.dims().len();
5815 if dim >= rank {
5816 return Err(fuel_ir::Error::Msg(format!(
5817 "flip: dim {dim} out of bounds for rank {rank}",
5818 ))
5819 .bt());
5820 }
5821 let op = Op::Flip { dim };
5822 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5823 let id = self.graph.write().unwrap().push(Node {
5824 op,
5825 inputs: vec![self.id],
5826 shape,
5827 dtype,
5828 });
5829 Ok(Self {
5830 graph: self.graph.clone(),
5831 id,
5832 })
5833 }
5834
5835 /// Append a `Roll` node — cyclic shift along `dim` by `shift`
5836 /// positions. Positive `shift` moves elements to higher indices
5837 /// (wrapping); negative the opposite. Output shape == input
5838 /// shape. Differentiable (backward is `Roll { dim, -shift }`).
5839 ///
5840 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5841 pub fn roll(&self, dim: usize, shift: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5842 let in_shape = self.shape();
5843 let rank = in_shape.dims().len();
5844 if dim >= rank {
5845 return Err(fuel_ir::Error::Msg(format!(
5846 "roll: dim {dim} out of bounds for rank {rank}",
5847 ))
5848 .bt());
5849 }
5850 let op = Op::Roll { dim, shift };
5851 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5852 let id = self.graph.write().unwrap().push(Node {
5853 op,
5854 inputs: vec![self.id],
5855 shape,
5856 dtype,
5857 });
5858 Ok(Self {
5859 graph: self.graph.clone(),
5860 id,
5861 })
5862 }
5863
5864 /// Append a `CumSum` node — running cumulative sum along `dim`.
5865 /// Output shape == input shape. Differentiable; backward is
5866 /// reverse-cumsum (`Flip → CumSum → Flip`).
5867 ///
5868 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5869 pub fn cumsum(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5870 let in_shape = self.shape();
5871 let rank = in_shape.dims().len();
5872 if dim >= rank {
5873 return Err(fuel_ir::Error::Msg(format!(
5874 "cumsum: dim {dim} out of bounds for rank {rank}",
5875 ))
5876 .bt());
5877 }
5878 let dtype = self.dtype();
5879 let id = self.graph.write().unwrap().push(Node {
5880 op: Op::CumSum { dim },
5881 inputs: vec![self.id],
5882 shape: in_shape,
5883 dtype,
5884 });
5885 Ok(Self {
5886 graph: self.graph.clone(),
5887 id,
5888 })
5889 }
5890
5891 /// Append a `Triu` node — upper-triangular mask along the last two
5892 /// dims. `diagonal = 0` keeps the main diagonal and above; positive
5893 /// values shift the cutoff up (keeping less); negative shift down
5894 /// (keeping more, including subdiagonals).
5895 ///
5896 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
5897 pub fn triu(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5898 let in_shape = self.shape();
5899 let rank = in_shape.dims().len();
5900 if rank < 2 {
5901 return Err(fuel_ir::Error::Msg(format!(
5902 "triu: input must have rank >= 2, got {rank}",
5903 ))
5904 .bt());
5905 }
5906 let dtype = self.dtype();
5907 let id = self.graph.write().unwrap().push(Node {
5908 op: Op::Triu { diagonal },
5909 inputs: vec![self.id],
5910 shape: in_shape,
5911 dtype,
5912 });
5913 Ok(Self {
5914 graph: self.graph.clone(),
5915 id,
5916 })
5917 }
5918
5919 /// Append an [`Op::Scan`] node — a bounded `lax.scan` recurrence.
5920 /// `self` is the `init_carry`. The body must already be built in the same
5921 /// graph, referencing `Op::ScanPlaceholder{Carry,0}` for the per-step
5922 /// carry and `Op::ScanPlaceholder{Elem,i}` for the per-step slice of
5923 /// `xs[i]`; `consts` are referenced by real NodeId. `body_new_carry` /
5924 /// `body_y` are the body's two exit nodes. Always a 2-slot bundle
5925 /// (slot 0 = stacked `ys` `[bound] ++ body_y`, slot 1 = final carry);
5926 /// `emit` selects which slot this call projects. `early_exit` is Phase 2
5927 /// (always `None` here).
5928 ///
5929 /// **Returns `Result`**: a malformed body/carry/bound surfaces as a typed
5930 /// error — never a panic.
5931 pub fn scan(
5932 &self,
5933 xs: &[NodeHandle],
5934 consts: &[NodeHandle],
5935 body_new_carry: &NodeHandle,
5936 body_y: &NodeHandle,
5937 bound: usize,
5938 emit: ScanEmit,
5939 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5940 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
5941 if !same_graph(body_new_carry)
5942 || !same_graph(body_y)
5943 || !xs.iter().all(same_graph)
5944 || !consts.iter().all(same_graph)
5945 {
5946 return Err(fuel_ir::Error::Msg(
5947 "scan: init_carry, xs, consts, and body exits must live on one graph".into(),
5948 )
5949 .bt());
5950 }
5951 if bound == 0 {
5952 return Err(fuel_ir::Error::Msg("scan: bound must be >= 1".into()).bt());
5953 }
5954 let carry_shape = self.shape();
5955 if body_new_carry.shape().dims() != carry_shape.dims() {
5956 return Err(fuel_ir::Error::Msg(format!(
5957 "scan: body_new_carry shape {:?} must equal init_carry shape {:?}",
5958 body_new_carry.shape().dims(),
5959 carry_shape.dims(),
5960 ))
5961 .bt());
5962 }
5963 // Validate body placeholders at graph-build time (single-carry; every
5964 // Elem index < n_xs) so a malformed body is a typed Err here, not a
5965 // later `elem[index]` panic on the unroll / forward-driver path.
5966 {
5967 let g = self.graph.read().unwrap();
5968 crate::scan::validate_scan_body_placeholders(
5969 &g,
5970 &[body_new_carry.id, body_y.id],
5971 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
5972 // construction below); the IR and the unroll are not.
5973 1,
5974 xs.len(),
5975 )?;
5976 }
5977 let carry_dtype = self.dtype();
5978 let y_dtype = body_y.dtype();
5979
5980 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
5981 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
5982 ys_dims.push(bound);
5983 ys_dims.extend_from_slice(body_y.shape().dims());
5984 let ys_shape = Shape::from_dims(&ys_dims);
5985 let specs = vec![
5986 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
5987 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
5988 ];
5989 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs)
5990 .map_err(|e| fuel_ir::Error::Msg(format!("scan: compose_bundle failed: {e}")).bt())?;
5991
5992 let mut inputs: Vec<NodeId> = Vec::with_capacity(2 + xs.len() + consts.len() + 2);
5993 inputs.push(self.id);
5994 inputs.extend(xs.iter().map(|t| t.id));
5995 inputs.extend(consts.iter().map(|t| t.id));
5996 inputs.push(body_new_carry.id);
5997 inputs.push(body_y.id);
5998
5999 let id = {
6000 let mut g = self.graph.write().unwrap();
6001 // Node.shape/dtype are the PRIMARY (slot-0) shape/dtype per the
6002 // multi-output authoring contract.
6003 let id = g.push(Node {
6004 op: Op::Scan {
6005 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6006 // `parse_scan_layout` and `build_scan_step` all handle N
6007 // carries. This BUILDER deliberately still constructs ONE.
6008 //
6009 // Widening it means N+1 output-view specs through
6010 // `compose_bundle` below -- i.e. the bundle arity -- which is
6011 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6012 // is NOT this change. A reader must not read "the builder makes
6013 // one" as "multi-carry does not work".
6014 n_carries: 1,
6015 n_xs: xs.len(),
6016 bound,
6017 emit,
6018 early_exit: None,
6019 },
6020 inputs,
6021 shape: ys_shape,
6022 dtype: y_dtype,
6023 });
6024 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6025 .map_err(|e| {
6026 fuel_ir::Error::Msg(format!("scan: set_output_views failed: {e}")).bt()
6027 })?;
6028 id
6029 };
6030 let producer = Self {
6031 graph: self.graph.clone(),
6032 id,
6033 };
6034 match emit {
6035 ScanEmit::All => producer.view(0),
6036 ScanEmit::Final => producer.view(1),
6037 }
6038 }
6039
6040 /// Append an early-exit [`Op::Scan`] node — the `Result`-returning sibling
6041 /// of [`NodeHandle::scan`] that carries a convergence predicate as the extra
6042 /// trailing input (`early_exit = Some(ScanPredicate)`). `self` is the
6043 /// `init_carry`; `pred_exit` is a scalar-`U8` sub-DAG over the carry
6044 /// (`Op::ScanPlaceholder{Carry,0}` for the pre-step carry, and the shared
6045 /// `body_new_carry` node for the post-step carry) that stops iteration when
6046 /// it fires. The runtime stop count is data-dependent under the static
6047 /// capacity `bound`.
6048 ///
6049 /// **`consts` must include every const referenced by the body OR the
6050 /// predicate** — the clone/unroll machinery shares only `consts`; a
6051 /// predicate const outside `consts` would be re-cloned dataless and fail at
6052 /// realize.
6053 ///
6054 /// **Returns `Result`**: a malformed body/carry/bound, or a non-scalar /
6055 /// non-`U8` / `Elem`-referencing predicate, surfaces as a typed error —
6056 /// never a panic (validated at graph-build time).
6057 pub fn scan_until(
6058 &self,
6059 xs: &[NodeHandle],
6060 consts: &[NodeHandle],
6061 body_new_carry: &NodeHandle,
6062 body_y: &NodeHandle,
6063 pred_exit: &NodeHandle,
6064 bound: usize,
6065 emit: ScanEmit,
6066 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6067 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6068 if !same_graph(body_new_carry)
6069 || !same_graph(body_y)
6070 || !same_graph(pred_exit)
6071 || !xs.iter().all(same_graph)
6072 || !consts.iter().all(same_graph)
6073 {
6074 return Err(fuel_ir::Error::Msg(
6075 "scan_until: init_carry, xs, consts, body exits, and pred_exit must live on one graph".into(),
6076 ).bt());
6077 }
6078 if bound == 0 {
6079 return Err(fuel_ir::Error::Msg("scan_until: bound must be >= 1".into()).bt());
6080 }
6081 let carry_shape = self.shape();
6082 if body_new_carry.shape().dims() != carry_shape.dims() {
6083 return Err(fuel_ir::Error::Msg(format!(
6084 "scan_until: body_new_carry shape {:?} must equal init_carry shape {:?}",
6085 body_new_carry.shape().dims(),
6086 carry_shape.dims(),
6087 ))
6088 .bt());
6089 }
6090 // Validate body placeholders at graph-build time (single-carry; every
6091 // Elem index < n_xs) so a malformed body is a typed Err here, not a
6092 // later `elem[index]` panic in the forward driver's build_scan_step.
6093 {
6094 let g = self.graph.read().unwrap();
6095 crate::scan::validate_scan_body_placeholders(
6096 &g,
6097 &[body_new_carry.id, body_y.id],
6098 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6099 // construction below); the IR and the unroll are not.
6100 1,
6101 xs.len(),
6102 )?;
6103 }
6104 // Predicate must be a scalar Bool (shape [] or product == 1) — a
6105 // convergence flag, not a per-element mask. Validate at build time.
6106 // GAP-168(c): Bool, not U8. A predicate's natural producer is a
6107 // comparison, and those now yield Bool, so requiring U8 here would make
6108 // the ordinary `carry.ge(&thr)` path unusable as a predicate.
6109 if pred_exit.dtype() != fuel_ir::DType::Bool {
6110 return Err(fuel_ir::Error::Msg(format!(
6111 "scan_until: pred_exit must be Bool (a boolean flag), got {:?}",
6112 pred_exit.dtype(),
6113 ))
6114 .bt());
6115 }
6116 let pred_dims = pred_exit.shape();
6117 let pred_numel: usize = pred_dims.dims().iter().product();
6118 if pred_numel != 1 {
6119 return Err(fuel_ir::Error::Msg(format!(
6120 "scan_until: pred_exit must be a scalar (shape [] or [1]/all-ones), got {:?}",
6121 pred_dims.dims(),
6122 ))
6123 .bt());
6124 }
6125 // Every ScanPlaceholder reachable from pred_exit must be Carry{0} — the
6126 // predicate is over the carry, never a per-step Elem slice.
6127 {
6128 let g = self.graph.read().unwrap();
6129 for &id in &crate::topo_order_multi(&g, &[pred_exit.id]) {
6130 if let Op::ScanPlaceholder { role, index } = &g.node(id).op {
6131 let bad = matches!(role, ScanRole::Elem) || *index != 0;
6132 if bad {
6133 return Err(fuel_ir::Error::Msg(format!(
6134 "scan_until: pred_exit references ScanPlaceholder{{{role:?}, {index}}} — \
6135 the predicate may only read the carry (Carry, index 0)",
6136 )).bt());
6137 }
6138 }
6139 }
6140 }
6141 let carry_dtype = self.dtype();
6142 let y_dtype = body_y.dtype();
6143
6144 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6145 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6146 ys_dims.push(bound);
6147 ys_dims.extend_from_slice(body_y.shape().dims());
6148 let ys_shape = Shape::from_dims(&ys_dims);
6149 let specs = vec![
6150 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6151 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6152 ];
6153 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs).map_err(|e| {
6154 fuel_ir::Error::Msg(format!("scan_until: compose_bundle failed: {e}")).bt()
6155 })?;
6156
6157 let mut inputs: Vec<NodeId> = Vec::with_capacity(3 + xs.len() + consts.len());
6158 inputs.push(self.id);
6159 inputs.extend(xs.iter().map(|t| t.id));
6160 inputs.extend(consts.iter().map(|t| t.id));
6161 inputs.push(body_new_carry.id);
6162 inputs.push(body_y.id);
6163 inputs.push(pred_exit.id); // <-- the C1 trailing predicate
6164
6165 let id = {
6166 let mut g = self.graph.write().unwrap();
6167 let id = g.push(Node {
6168 op: Op::Scan {
6169 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6170 // `parse_scan_layout` and `build_scan_step` all handle N
6171 // carries. This BUILDER deliberately still constructs ONE.
6172 //
6173 // Widening it means N+1 output-view specs through
6174 // `compose_bundle` below -- i.e. the bundle arity -- which is
6175 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6176 // is NOT this change. A reader must not read "the builder makes
6177 // one" as "multi-carry does not work".
6178 n_carries: 1,
6179 n_xs: xs.len(),
6180 bound,
6181 emit,
6182 early_exit: Some(ScanPredicate),
6183 },
6184 inputs,
6185 shape: ys_shape,
6186 dtype: y_dtype,
6187 });
6188 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6189 .map_err(|e| {
6190 fuel_ir::Error::Msg(format!("scan_until: set_output_views failed: {e}")).bt()
6191 })?;
6192 id
6193 };
6194 let producer = Self {
6195 graph: self.graph.clone(),
6196 id,
6197 };
6198 match emit {
6199 ScanEmit::All => producer.view(0),
6200 ScanEmit::Final => producer.view(1),
6201 }
6202 }
6203
6204 /// Append a `Tril` node — lower-triangular mask along the last two
6205 /// dims. `diagonal = 0` keeps the main diagonal and below.
6206 /// `tril(diagonal = 0)` is the canonical causal-attention mask.
6207 ///
6208 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6209 pub fn tril(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6210 let in_shape = self.shape();
6211 let rank = in_shape.dims().len();
6212 if rank < 2 {
6213 return Err(fuel_ir::Error::Msg(format!(
6214 "tril: input must have rank >= 2, got {rank}",
6215 ))
6216 .bt());
6217 }
6218 let dtype = self.dtype();
6219 let id = self.graph.write().unwrap().push(Node {
6220 op: Op::Tril { diagonal },
6221 inputs: vec![self.id],
6222 shape: in_shape,
6223 dtype,
6224 });
6225 Ok(Self {
6226 graph: self.graph.clone(),
6227 id,
6228 })
6229 }
6230
6231 /// Append a `LogSoftmaxLastDim` node. Output shape == input shape.
6232 /// Numerically stable (max-subtracting formula) — preferred over
6233 /// `log(softmax(x))` for NLL / cross-entropy loss.
6234 ///
6235 /// **Returns `Result`**: rank < 1 surfaces as a typed error.
6236 pub fn log_softmax_last_dim(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6237 let in_shape = self.shape();
6238 if in_shape.dims().is_empty() {
6239 return Err(fuel_ir::Error::Msg(
6240 "log_softmax_last_dim: input must have rank >= 1".to_string(),
6241 )
6242 .bt());
6243 }
6244 let dtype = self.dtype();
6245 let id = self.graph.write().unwrap().push(Node {
6246 op: Op::LogSoftmaxLastDim,
6247 inputs: vec![self.id],
6248 shape: in_shape,
6249 dtype,
6250 });
6251 Ok(Self {
6252 graph: self.graph.clone(),
6253 id,
6254 })
6255 }
6256
6257 /// Append a `MaskedFill` node. `mask` must be `Bool` (GAP-168(c)) and have
6258 /// the same shape as `self`. Every position where `mask` is true gets `value`;
6259 /// every position where `mask == 0` passes `self` through. `value`
6260 /// is a scalar of `self`'s dtype.
6261 ///
6262 /// **Returns `Result`**: shape or dtype mismatches surface as typed
6263 /// errors.
6264 pub fn masked_fill(
6265 &self,
6266 mask: &NodeHandle,
6267 value: Scalar,
6268 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6269 self.require_same_graph(mask, "masked_fill", "mask")?;
6270 if self.shape().dims() != mask.shape().dims() {
6271 return Err(fuel_ir::Error::Msg(format!(
6272 "masked_fill: x.shape={:?} != mask.shape={:?}",
6273 self.shape().dims(),
6274 mask.shape().dims(),
6275 ))
6276 .bt());
6277 }
6278 if mask.dtype() != DType::Bool {
6279 return Err(fuel_ir::Error::Msg(format!(
6280 "masked_fill: mask dtype must be Bool, got {:?} — cast a numeric \
6281 mask to Bool explicitly (GAP-168(c))",
6282 mask.dtype(),
6283 ))
6284 .bt());
6285 }
6286 // GAP-002 (D5) / GAP-075 (fix B): classify EVERY dtype explicitly — no
6287 // wildcard default. The guard is SEMANTIC: masked_fill needs a
6288 // representable fill value AND a zero (the backward fills with zero), so
6289 // it rejects the packed formats (F4/F6*, no scalar fill) and the
6290 // block-scales (F8E8M0/F8E6M2, no zero), and permits the ordinary
6291 // numeric dtypes. Rejecting on the guard's own terms also keeps the
6292 // `Scalar::zero` Err branch in the MaskedFill `backward` arm provably
6293 // unreachable in a well-formed graph.
6294 //
6295 // Under the OLD denylist (`matches!(reject-set)`, else allow) a FUTURE
6296 // dtype fell through to "permitted" SILENTLY. With new dtypes scheduled
6297 // (GAP-097: e5m2, complex, sub-byte int, …) that would silently accept
6298 // masked_fill on formats whose fill semantics are unsettled. An
6299 // exhaustive match makes a new dtype a COMPILE ERROR here, forcing the
6300 // person who adds it to decide its permission consciously — the compiler
6301 // is the real guard; the tests below protect the existing classification.
6302 //
6303 // NOTE: "permitted" is a graph-build PERMISSION (is masked_fill
6304 // semantically well-defined?), NOT a promise a backend can allocate/run
6305 // the dtype. An unimplemented storage still declines loudly downstream
6306 // (typed `UnsupportedDTypeForOp` at allocation), which is the sound
6307 // composition — a semantically-true guard upstream, a loud capability
6308 // decline downstream.
6309 match self.dtype() {
6310 DType::F4 | DType::F6E2M3 | DType::F6E3M2 | DType::F8E8M0 | DType::F8E6M2 => {
6311 return Err(
6312 fuel_ir::Error::UnsupportedDTypeForOp(self.dtype(), "masked_fill").bt(),
6313 );
6314 }
6315 DType::U8
6316 | DType::I8
6317 | DType::U32
6318 | DType::I16
6319 | DType::I32
6320 | DType::I64
6321 | DType::BF16
6322 | DType::F16
6323 | DType::F32
6324 | DType::F64
6325 | DType::F8E4M3
6326 // GAP-097: F8E5M2 is PERMITTED, on the guard's own semantic terms.
6327 //
6328 // The reject set above is not "exotic dtypes" — it is two distinct
6329 // NON-VALUE categories: the block-scales (F8E8M0/F8E6M2) ride as
6330 // sibling operands and are not element value dtypes at all, and the
6331 // block-scoped elements (F4/F6*) have no standalone byte layout, so
6332 // a single element is not addressable without its block. Neither has
6333 // a well-defined fill-one-element operation, which is what this op
6334 // needs. F8E5M2 is a value dtype in exactly the way F8E4M3 (already
6335 // permitted, directly above) is: sign + exponent + mantissa, a
6336 // standalone byte layout, a representable zero for the backward, and
6337 // a representable fill value. So permitting it CONTINUES the
6338 // existing classification; rejecting would be the exception.
6339 //
6340 // Weighed and rejected as grounds for the opposite call: F8E5M2
6341 // currently has NO host or CUDA storage (fuel-cpu-backend and
6342 // fuel-cuda-backend both decline it), so this permits a graph the
6343 // backends cannot yet allocate — GAP(GAP-161) tracks that storage
6344 // decline and its expiry. That is the NOTE above working as
6345 // designed — permission is semantic, allocation is a capability, and
6346 // they are different questions. Writing REJECT here would encode the
6347 // claim "F8E5M2 has no representable fill value", which is FALSE and
6348 // would outlive the storage gap that motivated it.
6349 | DType::F8E5M2
6350 // GAP-168(c): Bool is a value dtype with a representable fill value
6351 // (true/false) and a zero for the backward (false) — permitted on
6352 // this guard's own semantic terms, exactly as the FP8 value dtypes
6353 // are. (This is the FILLED tensor's dtype; the MASK dtype is checked
6354 // separately above.)
6355 | DType::Bool => {}
6356 }
6357 if value.dtype() != self.dtype() {
6358 return Err(fuel_ir::Error::Msg(format!(
6359 "masked_fill: value dtype {:?} != x dtype {:?}",
6360 value.dtype(),
6361 self.dtype(),
6362 ))
6363 .bt());
6364 }
6365 let op = Op::MaskedFill { value };
6366 let (shape, dtype) = crate::shape::primitive_shape(
6367 &op,
6368 &[self.shape(), mask.shape()],
6369 &[self.dtype(), mask.dtype()],
6370 )
6371 .expect("masked_fill: shapes/dtypes validated above");
6372 let id = self.graph.write().unwrap().push(Node {
6373 op,
6374 inputs: vec![self.id, mask.id],
6375 shape,
6376 dtype,
6377 });
6378 Ok(Self {
6379 graph: self.graph.clone(),
6380 id,
6381 })
6382 }
6383
6384 /// Append a `Pad` node — multi-dim padding. `padding[i] = (before, after)`
6385 /// for axis `i`; `padding.len()` must equal `self.rank()`.
6386 /// Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
6387 /// `value` is the fill constant for [`PadMode::Constant`]
6388 /// (ignored for other modes).
6389 ///
6390 /// Only Constant mode is wired through the executor in the v1
6391 /// cut; the other modes produce a clean error at realize time.
6392 /// Differentiable for Constant (backward slices the gradient
6393 /// along each padded axis to restore the input shape).
6394 ///
6395 /// **Returns `Result`**: rank mismatch surfaces as a typed error.
6396 pub fn pad(
6397 &self,
6398 padding: Vec<(usize, usize)>,
6399 mode: PadMode,
6400 value: f64,
6401 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6402 let in_shape = self.shape();
6403 let rank = in_shape.dims().len();
6404 if padding.len() != rank {
6405 return Err(fuel_ir::Error::Msg(format!(
6406 "pad: padding.len() ({}) must equal tensor rank ({rank})",
6407 padding.len(),
6408 ))
6409 .bt());
6410 }
6411 let op = Op::Pad {
6412 padding,
6413 mode,
6414 value,
6415 };
6416 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6417 let id = self.graph.write().unwrap().push(Node {
6418 op,
6419 inputs: vec![self.id],
6420 shape,
6421 dtype,
6422 });
6423 Ok(Self {
6424 graph: self.graph.clone(),
6425 id,
6426 })
6427 }
6428
6429 /// Append an `Equal` node (`self == other`) producing a `Bool` mask.
6430 /// Both operands must share dtype and shape; output dtype is `Bool`
6431 /// (`1` where equal, `0` otherwise). NaN follows IEEE-754
6432 /// (`NaN == NaN` is false). Non-differentiable.
6433 ///
6434 /// # Panics
6435 ///
6436 /// Panics if any operand belongs to a different [`Graph`] than the one this
6437 /// builder is building into. Operand identity is graph-scoped and checked by
6438 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6439 /// deliberate and replaces the hang a cross-graph handle used to produce.
6440 /// Build every operand from one graph, or use a `Result`-returning entry
6441 /// point where one exists.
6442 pub fn eq(&self, other: &NodeHandle) -> NodeHandle {
6443 self.binary_compare_op("eq", Op::Equal, other)
6444 }
6445
6446 /// Append a `Ne` node (`self != other`) producing a `Bool` mask.
6447 /// Same shape/dtype contract as [`Self::eq`]. NaN follows
6448 /// IEEE-754 (`NaN != NaN` is true → `1`). Non-differentiable.
6449 ///
6450 /// # Panics
6451 ///
6452 /// Panics if any operand belongs to a different [`Graph`] than the one this
6453 /// builder is building into. Operand identity is graph-scoped and checked by
6454 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6455 /// deliberate and replaces the hang a cross-graph handle used to produce.
6456 /// Build every operand from one graph, or use a `Result`-returning entry
6457 /// point where one exists.
6458 pub fn ne(&self, other: &NodeHandle) -> NodeHandle {
6459 self.binary_compare_op("ne", Op::Ne, other)
6460 }
6461
6462 /// Append an `Lt` node (`self < other`) producing a `Bool` mask.
6463 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6464 /// is always `0` (IEEE-754 unordered). Non-differentiable.
6465 ///
6466 /// # Panics
6467 ///
6468 /// Panics if any operand belongs to a different [`Graph`] than the one this
6469 /// builder is building into. Operand identity is graph-scoped and checked by
6470 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6471 /// deliberate and replaces the hang a cross-graph handle used to produce.
6472 /// Build every operand from one graph, or use a `Result`-returning entry
6473 /// point where one exists.
6474 pub fn lt(&self, other: &NodeHandle) -> NodeHandle {
6475 self.binary_compare_op("lt", Op::Lt, other)
6476 }
6477
6478 /// Append an `Le` node (`self <= other`) producing a `Bool` mask.
6479 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6480 /// is always `0`. Non-differentiable.
6481 ///
6482 /// # Panics
6483 ///
6484 /// Panics if any operand belongs to a different [`Graph`] than the one this
6485 /// builder is building into. Operand identity is graph-scoped and checked by
6486 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6487 /// deliberate and replaces the hang a cross-graph handle used to produce.
6488 /// Build every operand from one graph, or use a `Result`-returning entry
6489 /// point where one exists.
6490 pub fn le(&self, other: &NodeHandle) -> NodeHandle {
6491 self.binary_compare_op("le", Op::Le, other)
6492 }
6493
6494 /// Append a `Gt` node (`self > other`) producing a `Bool` mask.
6495 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6496 /// is always `0`. Non-differentiable.
6497 ///
6498 /// # Panics
6499 ///
6500 /// Panics if any operand belongs to a different [`Graph`] than the one this
6501 /// builder is building into. Operand identity is graph-scoped and checked by
6502 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6503 /// deliberate and replaces the hang a cross-graph handle used to produce.
6504 /// Build every operand from one graph, or use a `Result`-returning entry
6505 /// point where one exists.
6506 pub fn gt(&self, other: &NodeHandle) -> NodeHandle {
6507 self.binary_compare_op("gt", Op::Gt, other)
6508 }
6509
6510 /// Append a `Ge` node (`self >= other`) producing a `Bool` mask.
6511 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6512 /// is always `0`. Non-differentiable.
6513 ///
6514 /// # Panics
6515 ///
6516 /// Panics if any operand belongs to a different [`Graph`] than the one this
6517 /// builder is building into. Operand identity is graph-scoped and checked by
6518 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6519 /// deliberate and replaces the hang a cross-graph handle used to produce.
6520 /// Build every operand from one graph, or use a `Result`-returning entry
6521 /// point where one exists.
6522 pub fn ge(&self, other: &NodeHandle) -> NodeHandle {
6523 self.binary_compare_op("ge", Op::Ge, other)
6524 }
6525
6526 /// Ternary select: `result[i] = if self[i] { a[i] } else { b[i] }`.
6527 /// Receiver is the `cond` mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
6528 /// must share dtype with each other and shape with `self`. Output
6529 /// dtype matches `a`/`b`. Returning a new tensor where each slot is
6530 /// picked from `a` (cond=1) or `b` (cond=0).
6531 ///
6532 /// Named `where_cond` because `where` is a Rust reserved keyword.
6533 /// Common spelling in Candle/PyTorch families.
6534 ///
6535 /// Differentiable through `a` and `b` only; gradient through the
6536 /// cond mask is `None` (registered in
6537 /// [`crate::grad::WhereRule`]).
6538 ///
6539 /// # Panics
6540 ///
6541 /// Panics if any operand belongs to a different [`Graph`] than the one this
6542 /// builder is building into. Operand identity is graph-scoped and checked by
6543 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6544 /// deliberate and replaces the hang a cross-graph handle used to produce.
6545 /// Build every operand from one graph, or use a `Result`-returning entry
6546 /// point where one exists.
6547 pub fn where_cond(&self, a: &NodeHandle, b: &NodeHandle) -> NodeHandle {
6548 assert!(
6549 Arc::ptr_eq(&self.graph, &a.graph) && Arc::ptr_eq(&self.graph, &b.graph),
6550 "where_cond: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
6551 );
6552 assert_eq!(
6553 self.dtype(),
6554 DType::Bool,
6555 "where_cond: cond must be Bool (GAP-168(c)), got {:?} — cast a numeric \
6556 mask to Bool explicitly",
6557 self.dtype(),
6558 );
6559 assert_eq!(
6560 a.dtype(),
6561 b.dtype(),
6562 "where_cond: a/b dtype mismatch: a={:?}, b={:?}",
6563 a.dtype(),
6564 b.dtype(),
6565 );
6566 assert_eq!(
6567 self.shape().dims(),
6568 a.shape().dims(),
6569 "where_cond: cond/a shape mismatch: cond={:?}, a={:?}",
6570 self.shape().dims(),
6571 a.shape().dims(),
6572 );
6573 assert_eq!(
6574 self.shape().dims(),
6575 b.shape().dims(),
6576 "where_cond: cond/b shape mismatch: cond={:?}, b={:?}",
6577 self.shape().dims(),
6578 b.shape().dims(),
6579 );
6580 let (shape, dtype) = crate::shape::primitive_shape(
6581 &Op::Where,
6582 &[self.shape(), a.shape(), b.shape()],
6583 &[self.dtype(), a.dtype(), b.dtype()],
6584 )
6585 .expect("where_cond: shapes/dtypes validated above");
6586 let id = self.graph.write().unwrap().push(Node {
6587 op: Op::Where,
6588 inputs: vec![self.id, a.id, b.id],
6589 shape,
6590 dtype,
6591 });
6592 Self {
6593 graph: self.graph.clone(),
6594 id,
6595 }
6596 }
6597
6598 // --- dtype and broadcasting ---
6599
6600 /// Append a `Cast` node converting this tensor's element type to
6601 /// `target`. Shape is preserved. An identity cast (`target` equals the
6602 /// current dtype) is a no-op that the optimizer elides (see
6603 /// `opt::optimize`'s identity-`Cast` rule) — kept here rather than
6604 /// special-cased at construction so every identity cast, however it
6605 /// arises (decompose, autograd, user), is removed in one place.
6606 pub fn cast(&self, target: DType) -> NodeHandle {
6607 let op = Op::Cast(target);
6608 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6609 .expect("cast: single input, dtype change always infers");
6610 let id = self.graph.write().unwrap().push(Node {
6611 op,
6612 inputs: vec![self.id],
6613 shape,
6614 dtype,
6615 });
6616 Self {
6617 graph: self.graph.clone(),
6618 id,
6619 }
6620 }
6621
6622 /// Append a `BroadcastTo` node that expands `self` to the given target
6623 /// shape using NumPy broadcasting rules (right-align, pad with 1s,
6624 /// expand size-1 dims). The new tensor has the target shape and the
6625 /// same dtype as `self`.
6626 pub fn broadcast_to(&self, target: impl Into<Shape>) -> NodeHandle {
6627 let target = target.into();
6628 let src_dims = self.shape();
6629 // Validate broadcast compatibility up front so users hear about
6630 // bad target shapes at build time, not realize time.
6631 check_broadcast_compatible(src_dims.dims(), target.dims());
6632 let op = Op::BroadcastTo(target);
6633 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6634 .expect("broadcast_to: compatibility validated above");
6635 let id = self.graph.write().unwrap().push(Node {
6636 op,
6637 inputs: vec![self.id],
6638 shape,
6639 dtype,
6640 });
6641 Self {
6642 graph: self.graph.clone(),
6643 id,
6644 }
6645 }
6646
6647 /// Result-returning sibling of [`Self::broadcast_to`]. Surfaces
6648 /// shape incompatibility as a typed error rather than panicking.
6649 pub fn try_broadcast_to(
6650 &self,
6651 target: impl Into<Shape>,
6652 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6653 let target = target.into();
6654 let src_dims = self.shape();
6655 try_check_broadcast_compatible(src_dims.dims(), target.dims())?;
6656 let op = Op::BroadcastTo(target);
6657 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6658 let id = self.graph.write().unwrap().push(Node {
6659 op,
6660 inputs: vec![self.id],
6661 shape,
6662 dtype,
6663 });
6664 Ok(Self {
6665 graph: self.graph.clone(),
6666 id,
6667 })
6668 }
6669
6670 /// Append an `Unsqueeze` node that inserts a size-1 dimension at
6671 /// position `dim`. `dim` must be in `0..=rank` (where `dim == rank`
6672 /// appends to the end). Pure metadata — the output shares bytes
6673 /// with `self`, with a new size-1 axis layered into the Layout
6674 /// side-table. Strictly more efficient than `reshape` for the
6675 /// size-1-insertion case because non-contiguous (e.g. transposed
6676 /// or broadcast) inputs flow through without auto-Contiguize.
6677 pub fn unsqueeze(&self, dim: usize) -> NodeHandle {
6678 let in_shape = self.shape();
6679 let rank = in_shape.dims().len();
6680 assert!(
6681 dim <= rank,
6682 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6683 );
6684 let op = Op::Unsqueeze { dim };
6685 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6686 .expect("unsqueeze: dim validated above");
6687 let id = self.graph.write().unwrap().push(Node {
6688 op,
6689 inputs: vec![self.id],
6690 shape,
6691 dtype,
6692 });
6693 Self {
6694 graph: self.graph.clone(),
6695 id,
6696 }
6697 }
6698
6699 /// Result-returning sibling of [`Self::unsqueeze`]. Surfaces
6700 /// `dim > rank` as a typed error rather than panicking.
6701 pub fn try_unsqueeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6702 let in_shape = self.shape();
6703 let rank = in_shape.dims().len();
6704 if dim > rank {
6705 return Err(fuel_ir::Error::Msg(format!(
6706 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6707 ))
6708 .bt());
6709 }
6710 let op = Op::Unsqueeze { dim };
6711 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6712 let id = self.graph.write().unwrap().push(Node {
6713 op,
6714 inputs: vec![self.id],
6715 shape,
6716 dtype,
6717 });
6718 Ok(Self {
6719 graph: self.graph.clone(),
6720 id,
6721 })
6722 }
6723
6724 /// Append a `Squeeze` node that drops the size-1 dimension at
6725 /// position `dim` (range `0..rank`). Inverse of [`Self::unsqueeze`].
6726 /// Metadata-only view: the output shares bytes with `self`, with
6727 /// the named dim pruned from the Layout side-table.
6728 ///
6729 /// **Returns `Result`** rather than panicking — production paths
6730 /// can recover from a bad `dim` instead of crashing. Bad `dim`
6731 /// (out of bounds OR `shape[dim] != 1`) surfaces as a typed error.
6732 pub fn squeeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6733 let in_shape = self.shape();
6734 let rank = in_shape.dims().len();
6735 if dim >= rank {
6736 return Err(fuel_ir::Error::Msg(format!(
6737 "squeeze: dim {dim} out of bounds for rank {rank} (must be < rank)",
6738 ))
6739 .bt());
6740 }
6741 if in_shape.dims()[dim] != 1 {
6742 return Err(fuel_ir::Error::Msg(format!(
6743 "squeeze: dim {dim} has size {}, expected 1",
6744 in_shape.dims()[dim],
6745 ))
6746 .bt());
6747 }
6748 let op = Op::Squeeze { dim };
6749 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6750 let id = self.graph.write().unwrap().push(Node {
6751 op,
6752 inputs: vec![self.id],
6753 shape,
6754 dtype,
6755 });
6756 Ok(Self {
6757 graph: self.graph.clone(),
6758 id,
6759 })
6760 }
6761
6762 /// Append an `Op::Contiguize` node that materializes a
6763 /// contiguous copy of `self`. Output shape and dtype match the
6764 /// input; only the layout changes to contiguous + zero-offset.
6765 /// Zero-copy when the input is already contiguous + zero-offset
6766 /// (the executor adopts the input Storage Arc unchanged).
6767 ///
6768 /// First-class IR node so the optimizer (Phase 2.2) can insert
6769 /// layout-fixups before kernels that don't advertise
6770 /// `crate::KernelCaps::strided_input` without overloading
6771 /// [`Self::reshape`]'s "change shape" semantics.
6772 pub fn contiguize(&self) -> NodeHandle {
6773 let shape = self.shape().clone();
6774 let dtype = self.dtype();
6775 let id = self.graph.write().unwrap().push(Node {
6776 op: Op::Contiguize,
6777 inputs: vec![self.id],
6778 shape,
6779 dtype,
6780 });
6781 Self {
6782 graph: self.graph.clone(),
6783 id,
6784 }
6785 }
6786
6787 /// Append a `Reshape` node producing `self`'s data under a new shape.
6788 /// The new shape must have the same total element count as the
6789 /// current shape.
6790 pub fn reshape(&self, target: impl Into<Shape>) -> NodeHandle {
6791 let target = target.into();
6792 assert_eq!(
6793 self.shape().elem_count(),
6794 target.elem_count(),
6795 "reshape: element count mismatch: from {} to {}",
6796 self.shape().elem_count(),
6797 target.elem_count(),
6798 );
6799 let op = Op::Reshape(target);
6800 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6801 .expect("reshape: element count validated above");
6802 let id = self.graph.write().unwrap().push(Node {
6803 op,
6804 inputs: vec![self.id],
6805 shape,
6806 dtype,
6807 });
6808 Self {
6809 graph: self.graph.clone(),
6810 id,
6811 }
6812 }
6813
6814 /// Result-returning sibling of [`Self::reshape`]. Surfaces
6815 /// element-count mismatch as a typed error rather than panicking.
6816 pub fn try_reshape(
6817 &self,
6818 target: impl Into<Shape>,
6819 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6820 let target = target.into();
6821 let from = self.shape().elem_count();
6822 let to = target.elem_count();
6823 if from != to {
6824 return Err(fuel_ir::Error::Msg(format!(
6825 "reshape: element count mismatch: from {from} to {to}",
6826 ))
6827 .bt());
6828 }
6829 let op = Op::Reshape(target);
6830 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6831 let id = self.graph.write().unwrap().push(Node {
6832 op,
6833 inputs: vec![self.id],
6834 shape,
6835 dtype,
6836 });
6837 Ok(Self {
6838 graph: self.graph.clone(),
6839 id,
6840 })
6841 }
6842
6843 /// Append a `ReduceSumTo` node that sum-reduces `self` to a smaller
6844 /// shape. The target must be reachable from `self.shape()` via
6845 /// reduction of dims (i.e. `self.shape()` could be produced from
6846 /// `target` by broadcasting).
6847 pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> NodeHandle {
6848 let target = target.into();
6849 // Symmetric check: self must be broadcast-compatible FROM the
6850 // smaller target. That is, the target must be broadcast-ready to
6851 // self.shape().
6852 check_broadcast_compatible(target.dims(), self.shape().dims());
6853 let op = Op::ReduceSumTo(target);
6854 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6855 .expect("reduce_sum_to: compatibility validated above");
6856 let id = self.graph.write().unwrap().push(Node {
6857 op,
6858 inputs: vec![self.id],
6859 shape,
6860 dtype,
6861 });
6862 Self {
6863 graph: self.graph.clone(),
6864 id,
6865 }
6866 }
6867
6868 /// Append a `ReduceMaxTo` node that max-reduces `self` to a smaller
6869 /// shape — the max-symmetric counterpart of [`Self::reduce_sum_to`].
6870 /// The target must be reachable from `self.shape()` via reduction
6871 /// of dims (i.e. `self.shape()` could be produced from `target` by
6872 /// broadcasting).
6873 pub fn reduce_max_to(&self, target: impl Into<Shape>) -> NodeHandle {
6874 let target = target.into();
6875 check_broadcast_compatible(target.dims(), self.shape().dims());
6876 let op = Op::ReduceMaxTo(target);
6877 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6878 .expect("reduce_max_to: compatibility validated above");
6879 let id = self.graph.write().unwrap().push(Node {
6880 op,
6881 inputs: vec![self.id],
6882 shape,
6883 dtype,
6884 });
6885 Self {
6886 graph: self.graph.clone(),
6887 id,
6888 }
6889 }
6890
6891 // --- reductions to a scalar ---
6892
6893 /// Append a `SumAll` node reducing every element to a scalar (rank-0).
6894 pub fn sum_all(&self) -> NodeHandle {
6895 self.scalar_reduction(Op::SumAll)
6896 }
6897
6898 /// Append a `MaxAll` node producing the max element as a scalar.
6899 pub fn max_all(&self) -> NodeHandle {
6900 self.scalar_reduction(Op::MaxAll)
6901 }
6902
6903 /// Append a `MinAll` node producing the min element as a scalar.
6904 pub fn min_all(&self) -> NodeHandle {
6905 self.scalar_reduction(Op::MinAll)
6906 }
6907
6908 /// Append a `MeanAll` node producing the arithmetic mean as a scalar.
6909 pub fn mean_all(&self) -> NodeHandle {
6910 self.scalar_reduction(Op::MeanAll)
6911 }
6912
6913 // --- reductions along one dimension ---
6914
6915 /// Append a `SumDim(dim)` node. Reduces along `dim`; output rank is
6916 /// `input rank - 1` (the reduced dim is removed).
6917 pub fn sum_dim(&self, dim: usize) -> NodeHandle {
6918 self.axis_reduction("sum_dim", Op::SumDim(dim), dim)
6919 }
6920
6921 /// Append a `MaxDim(dim)` node.
6922 pub fn max_dim(&self, dim: usize) -> NodeHandle {
6923 self.axis_reduction("max_dim", Op::MaxDim(dim), dim)
6924 }
6925
6926 /// Append a `MinDim(dim)` node.
6927 pub fn min_dim(&self, dim: usize) -> NodeHandle {
6928 self.axis_reduction("min_dim", Op::MinDim(dim), dim)
6929 }
6930
6931 /// Append a `MeanDim(dim)` node.
6932 pub fn mean_dim(&self, dim: usize) -> NodeHandle {
6933 self.axis_reduction("mean_dim", Op::MeanDim(dim), dim)
6934 }
6935
6936 /// Append an `ArgMaxDim(dim)` node. Produces a U32 tensor with the
6937 /// reduced dim removed, whose values are the index of the maximum
6938 /// along that dim. Non-differentiable — trying to run `backward()`
6939 /// through an ArgMax node will panic.
6940 pub fn argmax_dim(&self, dim: usize) -> NodeHandle {
6941 self.index_reduction("argmax_dim", Op::ArgMaxDim(dim), dim)
6942 }
6943
6944 /// Append an `ArgMinDim(dim)` node. Same semantics as `argmax_dim`
6945 /// but for the minimum.
6946 pub fn argmin_dim(&self, dim: usize) -> NodeHandle {
6947 self.index_reduction("argmin_dim", Op::ArgMinDim(dim), dim)
6948 }
6949
6950 /// Internal helper for index-producing reductions. Validates the
6951 /// dim, builds the reduced shape, and stamps the output with
6952 /// `DType::U32` regardless of the input dtype.
6953 fn index_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
6954 let in_shape = self.shape();
6955 assert!(
6956 dim < in_shape.dims().len(),
6957 "{name}: dim {dim} out of bounds for shape {:?}",
6958 in_shape.dims(),
6959 );
6960 // primitive_shape carries both the rank-reduced shape and the U32
6961 // index dtype for ArgMaxDim/ArgMinDim (the single source of truth).
6962 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6963 .expect("index_reduction: dim validated above");
6964 let id = self.graph.write().unwrap().push(Node {
6965 op,
6966 inputs: vec![self.id],
6967 shape,
6968 dtype,
6969 });
6970 Self {
6971 graph: self.graph.clone(),
6972 id,
6973 }
6974 }
6975
6976 // --- compositions ---
6977
6978 /// Append a `SoftmaxLastDim` node. Shape is preserved.
6979 ///
6980 /// Phase 7.6 step 3: emits `Op::Fused(FusedOps::SOFTMAX_LAST_DIM,
6981 /// FusedOpParams::SoftmaxLastDim)` — the registry-extended arm.
6982 /// The legacy `Op::SoftmaxLastDim` variant remains in the enum
6983 /// during the migration; step 5 drops it once nothing emits it.
6984 pub fn softmax_last_dim(&self) -> NodeHandle {
6985 assert!(
6986 !self.shape().dims().is_empty(),
6987 "softmax_last_dim: input must be rank >= 1",
6988 );
6989 self.unary_op(Op::Fused(
6990 crate::registry::FusedOps::SOFTMAX_LAST_DIM,
6991 crate::registry::FusedOpParams::SoftmaxLastDim,
6992 ))
6993 }
6994
6995 /// Append a `CausalConv1d` node — depthwise 1-D causal convolution
6996 /// + bias + optional fused SiLU. Three inputs:
6997 /// - `self` (x): `[batch, channels, seq + kernel - 1]` F32
6998 /// (caller pre-pads with `kernel - 1` zeros on the left for the
6999 /// causal mask — matches Mamba-2's prefill convention).
7000 /// - `weight`: `[channels, 1, kernel]` F32 (depthwise — one filter
7001 /// per channel; `groups == channels`).
7002 /// - `bias`: `[channels]` F32 (required — matches baracuda's
7003 /// `causal_conv1d_*_run` signature; pass zeros if you don't want
7004 /// a bias).
7005 ///
7006 /// Output: `[batch, channels, seq]` F32 where `seq = x.dims[2] -
7007 /// (kernel - 1)`.
7008 ///
7009 /// Emits `Op::Fused(FusedOps::CAUSAL_CONV1D,
7010 /// FusedOpParams::CausalConv1d { use_silu })`. See
7011 /// `fuel-graph/src/registry/causal_conv1d.rs` for the registry
7012 /// entry. No primitive decomposition exists (fuel-graph has no
7013 /// `Op::Conv1D`); backends without a native kernel fall through
7014 /// to the executor's cpu_fallback path.
7015 ///
7016 /// # Panics
7017 ///
7018 /// Panics if any operand belongs to a different [`Graph`] than the one this
7019 /// builder is building into. Operand identity is graph-scoped and checked by
7020 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7021 /// deliberate and replaces the hang a cross-graph handle used to produce.
7022 /// Build every operand from one graph, or use a `Result`-returning entry
7023 /// point where one exists.
7024 pub fn causal_conv1d(
7025 &self,
7026 weight: &NodeHandle,
7027 bias: &NodeHandle,
7028 use_silu: bool,
7029 ) -> NodeHandle {
7030 assert!(
7031 Arc::ptr_eq(&self.graph, &weight.graph) && Arc::ptr_eq(&self.graph, &bias.graph),
7032 "causal_conv1d: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7033 );
7034 let dtype = self.dtype();
7035 assert!(
7036 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7037 "causal_conv1d: x must be F32/F64/BF16/F16, got {dtype:?}",
7038 );
7039 assert_eq!(
7040 weight.dtype(),
7041 dtype,
7042 "causal_conv1d: weight dtype {:?} must match x dtype {dtype:?}",
7043 weight.dtype(),
7044 );
7045 assert_eq!(
7046 bias.dtype(),
7047 dtype,
7048 "causal_conv1d: bias dtype {:?} must match x dtype {dtype:?}",
7049 bias.dtype(),
7050 );
7051 let x_dims = self.shape();
7052 let x_dims = x_dims.dims();
7053 let w_dims = weight.shape();
7054 let w_dims = w_dims.dims();
7055 let b_dims = bias.shape();
7056 let b_dims = b_dims.dims();
7057 assert_eq!(
7058 x_dims.len(),
7059 3,
7060 "causal_conv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
7061 );
7062 assert_eq!(
7063 w_dims.len(),
7064 3,
7065 "causal_conv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
7066 );
7067 assert_eq!(
7068 b_dims.len(),
7069 1,
7070 "causal_conv1d: bias must be rank 1 [channels], got {b_dims:?}",
7071 );
7072 let batch = x_dims[0];
7073 let channels = x_dims[1];
7074 let x_seq = x_dims[2];
7075 let kernel = w_dims[2];
7076 assert_eq!(
7077 w_dims[0], channels,
7078 "causal_conv1d: weight's first dim {} must equal channels {channels}",
7079 w_dims[0],
7080 );
7081 assert_eq!(
7082 w_dims[1], 1,
7083 "causal_conv1d: weight's middle dim must be 1 (depthwise), got {}",
7084 w_dims[1],
7085 );
7086 assert_eq!(
7087 b_dims[0], channels,
7088 "causal_conv1d: bias length {} must equal channels {channels}",
7089 b_dims[0],
7090 );
7091 assert!(
7092 x_seq >= kernel - 1,
7093 "causal_conv1d: x time dim {x_seq} must be ≥ kernel - 1 = {} \
7094 (caller must pre-pad with {} zeros)",
7095 kernel - 1,
7096 kernel - 1,
7097 );
7098 let out_seq = x_seq - (kernel - 1);
7099 let id = self.graph.write().unwrap().push(Node {
7100 op: Op::Fused(
7101 crate::registry::FusedOps::CAUSAL_CONV1D,
7102 crate::registry::FusedOpParams::CausalConv1d { use_silu },
7103 ),
7104 inputs: vec![self.id, weight.id, bias.id],
7105 shape: Shape::from_dims(&[batch, channels, out_seq]),
7106 dtype,
7107 });
7108 Self {
7109 graph: self.graph.clone(),
7110 id,
7111 }
7112 }
7113
7114 /// Append an `Nf4Matmul` node — bitsandbytes-style 4-bit
7115 /// NormalFloat quantized matrix multiply. Three inputs:
7116 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7117 /// - `w_packed`: `[N, K/2]` U8 (two 4-bit codes per byte)
7118 /// - `absmax`: `[N, K/block_size]` F32 (per-output-row, per-block)
7119 ///
7120 /// Output: `[..., M, N]` matching activations' dtype.
7121 ///
7122 /// `block_size` is the NF4 quantization block size (typically 64
7123 /// in bitsandbytes). `K` must be even AND a multiple of
7124 /// `block_size`.
7125 ///
7126 /// Emits `Op::Fused(FusedOps::NF4_MATMUL, FusedOpParams::Nf4Matmul
7127 /// { block_size })`. No primitive decomposition (the dequant +
7128 /// matmul roundtrip is exactly what NF4's fused dequant-in-kernel
7129 /// design avoids); backends without a native kernel fall through
7130 /// to the executor's cpu_fallback path.
7131 ///
7132 /// # Panics
7133 ///
7134 /// Panics if any operand belongs to a different [`Graph`] than the one this
7135 /// builder is building into. Operand identity is graph-scoped and checked by
7136 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7137 /// deliberate and replaces the hang a cross-graph handle used to produce.
7138 /// Build every operand from one graph, or use a `Result`-returning entry
7139 /// point where one exists.
7140 pub fn nf4_matmul(
7141 &self,
7142 w_packed: &NodeHandle,
7143 absmax: &NodeHandle,
7144 block_size: usize,
7145 ) -> NodeHandle {
7146 assert!(
7147 Arc::ptr_eq(&self.graph, &w_packed.graph) && Arc::ptr_eq(&self.graph, &absmax.graph),
7148 "nf4_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7149 );
7150 let act_dtype = self.dtype();
7151 assert!(
7152 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7153 "nf4_matmul v1: activations must be F32/F16/BF16, got {:?}",
7154 act_dtype,
7155 );
7156 assert_eq!(
7157 w_packed.dtype(),
7158 DType::U8,
7159 "nf4_matmul: w_packed must be U8 (two 4-bit codes per byte), got {:?}",
7160 w_packed.dtype(),
7161 );
7162 assert_eq!(
7163 absmax.dtype(),
7164 DType::F32,
7165 "nf4_matmul: absmax must be F32, got {:?}",
7166 absmax.dtype(),
7167 );
7168 let a_dims = self.shape();
7169 let a_dims = a_dims.dims();
7170 let w_dims = w_packed.shape();
7171 let w_dims = w_dims.dims();
7172 let abs_dims = absmax.shape();
7173 let abs_dims = abs_dims.dims();
7174 assert!(
7175 a_dims.len() >= 2,
7176 "nf4_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7177 );
7178 assert_eq!(
7179 w_dims.len(),
7180 2,
7181 "nf4_matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
7182 );
7183 assert_eq!(
7184 abs_dims.len(),
7185 2,
7186 "nf4_matmul: absmax must be rank 2 [n, k/block_size], got {abs_dims:?}",
7187 );
7188 let _m = a_dims[a_dims.len() - 2];
7189 let k = a_dims[a_dims.len() - 1];
7190 let n = w_dims[0];
7191 assert!(
7192 k.is_multiple_of(2),
7193 "nf4_matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
7194 );
7195 assert!(
7196 block_size > 0 && k.is_multiple_of(block_size),
7197 "nf4_matmul: k={k} must be a positive multiple of block_size={block_size}",
7198 );
7199 assert_eq!(
7200 w_dims[1],
7201 k / 2,
7202 "nf4_matmul: w_packed second dim {} must equal k/2 = {}",
7203 w_dims[1],
7204 k / 2,
7205 );
7206 assert_eq!(
7207 abs_dims,
7208 &[n, k / block_size][..],
7209 "nf4_matmul: absmax {abs_dims:?} must be [n={n}, k/block_size={}]",
7210 k / block_size,
7211 );
7212 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7213 out_dims.push(n);
7214 let id = self.graph.write().unwrap().push(Node {
7215 op: Op::Fused(
7216 crate::registry::FusedOps::NF4_MATMUL,
7217 crate::registry::FusedOpParams::Nf4Matmul { block_size },
7218 ),
7219 inputs: vec![self.id, w_packed.id, absmax.id],
7220 shape: Shape::from_dims(&out_dims),
7221 dtype: act_dtype,
7222 });
7223 Self {
7224 graph: self.graph.clone(),
7225 id,
7226 }
7227 }
7228
7229 /// Append an `AwqMatmul` node — AWQ (mit-han-lab) asymmetric int4
7230 /// weight-only matrix multiply. Four inputs:
7231 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7232 /// - `qweight`: `[N, K/8]` U32 (eight int4 codes packed per word)
7233 /// - `qzeros`: `[K/group_size, N/8]` U32 (eight int4 zero-point
7234 /// codes packed per word)
7235 /// - `scales`: `[K/group_size, N]` F32 (per-group, per-output-
7236 /// channel scale)
7237 ///
7238 /// Output: `[..., M, N]` matching activations' dtype.
7239 ///
7240 /// `group_size` must be positive and evenly divide `K`. `K` must be a
7241 /// multiple of 8 (`qweight`'s packing); `N` must be a multiple of 8
7242 /// (`qzeros`' packing). `split_k_iters` is a CUDA launch-tuning
7243 /// parameter carried through unused by the (current, decompose-only)
7244 /// execution path — see [`crate::registry::awq_matmul`]'s module doc
7245 /// for what is and isn't wired/verified yet, including the
7246 /// packing-order caveat.
7247 ///
7248 /// Emits `Op::Fused(FusedOps::AWQ_MATMUL, FusedOpParams::AwqMatmul
7249 /// { group_size, split_k_iters })`.
7250 ///
7251 /// # Panics
7252 ///
7253 /// Panics if any operand belongs to a different [`Graph`] than the one
7254 /// this builder is building into, or if any shape/dtype precondition
7255 /// above doesn't hold — same discipline as [`Self::nf4_matmul`].
7256 pub fn awq_matmul(
7257 &self,
7258 qweight: &NodeHandle,
7259 qzeros: &NodeHandle,
7260 scales: &NodeHandle,
7261 group_size: usize,
7262 split_k_iters: i32,
7263 ) -> NodeHandle {
7264 assert!(
7265 Arc::ptr_eq(&self.graph, &qweight.graph)
7266 && Arc::ptr_eq(&self.graph, &qzeros.graph)
7267 && Arc::ptr_eq(&self.graph, &scales.graph),
7268 "awq_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7269 );
7270 let act_dtype = self.dtype();
7271 assert!(
7272 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7273 "awq_matmul v1: activations must be F32/F16/BF16, got {:?}",
7274 act_dtype,
7275 );
7276 assert_eq!(
7277 qweight.dtype(),
7278 DType::U32,
7279 "awq_matmul: qweight must be U32 (eight 4-bit codes per word), got {:?}",
7280 qweight.dtype(),
7281 );
7282 assert_eq!(
7283 qzeros.dtype(),
7284 DType::U32,
7285 "awq_matmul: qzeros must be U32 (eight 4-bit codes per word), got {:?}",
7286 qzeros.dtype(),
7287 );
7288 assert_eq!(
7289 scales.dtype(),
7290 DType::F32,
7291 "awq_matmul: scales must be F32, got {:?}",
7292 scales.dtype(),
7293 );
7294 let a_dims = self.shape();
7295 let a_dims = a_dims.dims();
7296 let w_dims = qweight.shape();
7297 let w_dims = w_dims.dims();
7298 let z_dims = qzeros.shape();
7299 let z_dims = z_dims.dims();
7300 let s_dims = scales.shape();
7301 let s_dims = s_dims.dims();
7302 assert!(
7303 a_dims.len() >= 2,
7304 "awq_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7305 );
7306 assert_eq!(
7307 w_dims.len(),
7308 2,
7309 "awq_matmul: qweight must be rank 2 [N, K/8], got {w_dims:?}",
7310 );
7311 assert_eq!(
7312 z_dims.len(),
7313 2,
7314 "awq_matmul: qzeros must be rank 2 [K/group_size, N/8], got {z_dims:?}",
7315 );
7316 assert_eq!(
7317 s_dims.len(),
7318 2,
7319 "awq_matmul: scales must be rank 2 [K/group_size, N], got {s_dims:?}",
7320 );
7321 let _m = a_dims[a_dims.len() - 2];
7322 let k = a_dims[a_dims.len() - 1];
7323 let n = w_dims[0];
7324 assert!(
7325 k.is_multiple_of(8),
7326 "awq_matmul: k={k} must be a multiple of 8 (qweight packs 8 codes per word along k)",
7327 );
7328 assert!(
7329 n.is_multiple_of(8),
7330 "awq_matmul: n={n} must be a multiple of 8 (qzeros packs 8 codes per word along n)",
7331 );
7332 assert!(
7333 group_size > 0 && k.is_multiple_of(group_size),
7334 "awq_matmul: k={k} must be a positive multiple of group_size={group_size}",
7335 );
7336 assert_eq!(
7337 w_dims[1],
7338 k / 8,
7339 "awq_matmul: qweight second dim {} must equal k/8 = {}",
7340 w_dims[1],
7341 k / 8,
7342 );
7343 let n_groups = k / group_size;
7344 assert_eq!(
7345 z_dims,
7346 &[n_groups, n / 8][..],
7347 "awq_matmul: qzeros {z_dims:?} must be [k/group_size={n_groups}, n/8={}]",
7348 n / 8,
7349 );
7350 assert_eq!(
7351 s_dims,
7352 &[n_groups, n][..],
7353 "awq_matmul: scales {s_dims:?} must be [k/group_size={n_groups}, n={n}]",
7354 );
7355 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7356 out_dims.push(n);
7357 let id = self.graph.write().unwrap().push(Node {
7358 op: Op::Fused(
7359 crate::registry::FusedOps::AWQ_MATMUL,
7360 crate::registry::FusedOpParams::AwqMatmul {
7361 group_size,
7362 split_k_iters,
7363 },
7364 ),
7365 inputs: vec![self.id, qweight.id, qzeros.id, scales.id],
7366 shape: Shape::from_dims(&out_dims),
7367 dtype: act_dtype,
7368 });
7369 Self {
7370 graph: self.graph.clone(),
7371 id,
7372 }
7373 }
7374
7375 /// Append an `SsdChunkScan` node — Mamba-2's State-Space
7376 /// Duality chunked scan (forward). Five inputs:
7377 /// - `self` (x): `[batch, seqlen, heads, head_dim]` F32
7378 /// - `dt`: `[batch, seqlen, heads]` F32
7379 /// - `a`: `[heads]` F32 (per-head scalar log A)
7380 /// - `b`: `[batch, seqlen, heads, state_dim]` F32
7381 /// - `c`: `[batch, seqlen, heads, state_dim]` F32
7382 ///
7383 /// Output: `y: [batch, seqlen, heads, head_dim]` F32 (same as x).
7384 ///
7385 /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
7386 /// It controls GPU parallelism granularity but the mathematical
7387 /// result is identical to a sequential scan; the CPU kernel runs
7388 /// sequential regardless. Validation: `chunk_size > 0` and
7389 /// `seqlen % chunk_size == 0`.
7390 ///
7391 /// Emits `Op::Fused(FusedOps::SSD_CHUNK_SCAN,
7392 /// FusedOpParams::SsdChunkScan { chunk_size })`. No primitive
7393 /// decomposition; backends without a native kernel fall through
7394 /// to the executor's cpu_fallback path.
7395 /// Internal: build the bundled SsdChunkScan producer node and
7396 /// return its NodeId. Callers project per-slot via
7397 /// [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7398 fn ssd_chunk_scan_producer(
7399 &self,
7400 dt: &NodeHandle,
7401 a: &NodeHandle,
7402 b: &NodeHandle,
7403 c: &NodeHandle,
7404 chunk_size: usize,
7405 ) -> NodeHandle {
7406 assert!(
7407 Arc::ptr_eq(&self.graph, &dt.graph)
7408 && Arc::ptr_eq(&self.graph, &a.graph)
7409 && Arc::ptr_eq(&self.graph, &b.graph)
7410 && Arc::ptr_eq(&self.graph, &c.graph),
7411 "ssd_chunk_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7412 );
7413 let dtype = self.dtype();
7414 assert!(
7415 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7416 "ssd_chunk_scan: x must be F32/F64/BF16/F16, got {dtype:?}",
7417 );
7418 for (name, t) in [("dt", dt), ("a", a), ("b", b), ("c", c)] {
7419 assert_eq!(
7420 t.dtype(),
7421 dtype,
7422 "ssd_chunk_scan: {name} dtype {:?} must match x dtype {dtype:?}",
7423 t.dtype(),
7424 );
7425 }
7426 let x_dims = self.shape();
7427 let x_dims = x_dims.dims();
7428 let dt_dims = dt.shape();
7429 let dt_dims = dt_dims.dims();
7430 let a_dims = a.shape();
7431 let a_dims = a_dims.dims();
7432 let b_dims = b.shape();
7433 let b_dims = b_dims.dims();
7434 let c_dims = c.shape();
7435 let c_dims = c_dims.dims();
7436 assert_eq!(
7437 x_dims.len(),
7438 4,
7439 "ssd_chunk_scan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
7440 );
7441 let batch = x_dims[0];
7442 let seqlen = x_dims[1];
7443 let heads = x_dims[2];
7444 let head_dim = x_dims[3];
7445 assert_eq!(
7446 dt_dims,
7447 &[batch, seqlen, heads][..],
7448 "ssd_chunk_scan: dt {dt_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}]",
7449 );
7450 assert_eq!(
7451 a_dims,
7452 &[heads][..],
7453 "ssd_chunk_scan: a {a_dims:?} must be [heads={heads}]",
7454 );
7455 assert_eq!(
7456 b_dims.len(),
7457 4,
7458 "ssd_chunk_scan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
7459 );
7460 let state_dim = b_dims[3];
7461 assert_eq!(
7462 b_dims,
7463 &[batch, seqlen, heads, state_dim][..],
7464 "ssd_chunk_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}, state_dim={state_dim}]",
7465 );
7466 assert_eq!(
7467 c_dims,
7468 &[batch, seqlen, heads, state_dim][..],
7469 "ssd_chunk_scan: c {c_dims:?} must match b shape",
7470 );
7471 let params = crate::registry::FusedOpParams::SsdChunkScan { chunk_size };
7472 let input_shapes = [
7473 Shape::from_dims(x_dims),
7474 Shape::from_dims(dt_dims),
7475 Shape::from_dims(a_dims),
7476 Shape::from_dims(b_dims),
7477 Shape::from_dims(c_dims),
7478 ];
7479 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7480 let entry = crate::registry::default_registry()
7481 .entry(crate::registry::FusedOps::SSD_CHUNK_SCAN)
7482 .expect("SSD_CHUNK_SCAN registered");
7483 let specs =
7484 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7485 let (_total_bytes, views) =
7486 fuel_ir::storage::compose_bundle(&specs).expect("SsdChunkScan compose_bundle");
7487 let mut g = self.graph.write().unwrap();
7488 let id = g.push(Node {
7489 op: Op::Fused(crate::registry::FusedOps::SSD_CHUNK_SCAN, params),
7490 inputs: vec![self.id, dt.id, a.id, b.id, c.id],
7491 shape: Shape::from_dims(&[batch, seqlen, heads, head_dim]),
7492 dtype,
7493 });
7494 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7495 .expect("SsdChunkScan set_output_views");
7496 drop(g);
7497 Self {
7498 graph: self.graph.clone(),
7499 id,
7500 }
7501 }
7502
7503 /// Single-output SsdChunkScan: returns the `y` slot of the
7504 /// bundled producer (View(0)). See
7505 /// [`Self::ssd_chunk_scan_bundled`] for the multi-output variant.
7506 ///
7507 /// # Panics
7508 ///
7509 /// Panics if any operand belongs to a different [`Graph`] than the one this
7510 /// builder is building into. Operand identity is graph-scoped and checked by
7511 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7512 /// deliberate and replaces the hang a cross-graph handle used to produce.
7513 /// Build every operand from one graph, or use a `Result`-returning entry
7514 /// point where one exists.
7515 pub fn ssd_chunk_scan(
7516 &self,
7517 dt: &NodeHandle,
7518 a: &NodeHandle,
7519 b: &NodeHandle,
7520 c: &NodeHandle,
7521 chunk_size: usize,
7522 ) -> NodeHandle {
7523 self.assert_same_graph(dt, "ssd_chunk_scan", "dt");
7524 self.assert_same_graph(a, "ssd_chunk_scan", "a");
7525 self.assert_same_graph(b, "ssd_chunk_scan", "b");
7526 self.assert_same_graph(c, "ssd_chunk_scan", "c");
7527 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7528 producer
7529 .view(0)
7530 .expect("SsdChunkScan view(0) must succeed (just registered slots)")
7531 }
7532
7533 /// Append a `SelectiveScan` node — Mamba-1's selective
7534 /// state-space scan (forward). Five inputs:
7535 /// - `self` (u): `[batch, seqlen, dim]` F32
7536 /// - `delta`: `[batch, seqlen, dim]` F32
7537 /// - `a`: `[dim, dstate]` F32
7538 /// - `b`: `[batch, seqlen, dstate]` F32
7539 /// - `c`: `[batch, seqlen, dstate]` F32
7540 ///
7541 /// Output: `y: [batch, seqlen, dim]` F32.
7542 ///
7543 /// `delta_softplus` toggles the softplus(delta) activation before
7544 /// use (matches baracuda's `selective_scan_*_run` flag). The v1
7545 /// op surface skips the optional `d_skip`, `z`, `delta_bias`
7546 /// inputs and the `last_state` second output — see
7547 /// `fuel-graph/src/registry/selective_scan.rs` for the rationale.
7548 ///
7549 /// Emits `Op::Fused(FusedOps::SELECTIVE_SCAN,
7550 /// FusedOpParams::SelectiveScan { delta_softplus })`. No
7551 /// primitive decomposition exists (the scan is a sequential
7552 /// recurrence); backends without a native kernel fall through to
7553 /// the executor's cpu_fallback path.
7554 /// Internal: build the bundled SelectiveScan producer node and
7555 /// return its NodeId (wrapped in a `NodeHandle`). Callers project
7556 /// per-slot via [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7557 fn selective_scan_producer(
7558 &self,
7559 delta: &NodeHandle,
7560 a: &NodeHandle,
7561 b: &NodeHandle,
7562 c: &NodeHandle,
7563 delta_softplus: bool,
7564 ) -> NodeHandle {
7565 assert!(
7566 Arc::ptr_eq(&self.graph, &delta.graph)
7567 && Arc::ptr_eq(&self.graph, &a.graph)
7568 && Arc::ptr_eq(&self.graph, &b.graph)
7569 && Arc::ptr_eq(&self.graph, &c.graph),
7570 "selective_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7571 );
7572 let dtype = self.dtype();
7573 assert!(
7574 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7575 "selective_scan: u must be F32/F64/BF16/F16, got {dtype:?}",
7576 );
7577 for (name, t) in [("delta", delta), ("a", a), ("b", b), ("c", c)] {
7578 assert_eq!(
7579 t.dtype(),
7580 dtype,
7581 "selective_scan: {name} dtype {:?} must match u dtype {dtype:?}",
7582 t.dtype(),
7583 );
7584 }
7585 let u_dims = self.shape();
7586 let u_dims = u_dims.dims();
7587 let delta_dims = delta.shape();
7588 let delta_dims = delta_dims.dims();
7589 let a_dims = a.shape();
7590 let a_dims = a_dims.dims();
7591 let b_dims = b.shape();
7592 let b_dims = b_dims.dims();
7593 let c_dims = c.shape();
7594 let c_dims = c_dims.dims();
7595 assert_eq!(
7596 u_dims.len(),
7597 3,
7598 "selective_scan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
7599 );
7600 assert_eq!(
7601 delta_dims, u_dims,
7602 "selective_scan: delta {delta_dims:?} must match u {u_dims:?}",
7603 );
7604 assert_eq!(
7605 a_dims.len(),
7606 2,
7607 "selective_scan: a must be rank 2 [dim, dstate], got {a_dims:?}",
7608 );
7609 let batch = u_dims[0];
7610 let seqlen = u_dims[1];
7611 let dim = u_dims[2];
7612 let dstate = a_dims[1];
7613 assert_eq!(
7614 a_dims[0], dim,
7615 "selective_scan: a's first dim {} must equal dim {dim}",
7616 a_dims[0],
7617 );
7618 assert_eq!(
7619 b_dims,
7620 &[batch, seqlen, dstate][..],
7621 "selective_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7622 );
7623 assert_eq!(
7624 c_dims,
7625 &[batch, seqlen, dstate][..],
7626 "selective_scan: c {c_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7627 );
7628 let params = crate::registry::FusedOpParams::SelectiveScan { delta_softplus };
7629 let input_shapes = [
7630 Shape::from_dims(u_dims),
7631 Shape::from_dims(delta_dims),
7632 Shape::from_dims(a_dims),
7633 Shape::from_dims(b_dims),
7634 Shape::from_dims(c_dims),
7635 ];
7636 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7637 let entry = crate::registry::default_registry()
7638 .entry(crate::registry::FusedOps::SELECTIVE_SCAN)
7639 .expect("SELECTIVE_SCAN registered");
7640 let specs =
7641 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7642 let (_total_bytes, views) =
7643 fuel_ir::storage::compose_bundle(&specs).expect("SelectiveScan compose_bundle");
7644 let mut g = self.graph.write().unwrap();
7645 let id = g.push(Node {
7646 op: Op::Fused(crate::registry::FusedOps::SELECTIVE_SCAN, params),
7647 inputs: vec![self.id, delta.id, a.id, b.id, c.id],
7648 shape: Shape::from_dims(&[batch, seqlen, dim]),
7649 dtype,
7650 });
7651 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7652 .expect("SelectiveScan set_output_views");
7653 drop(g);
7654 Self {
7655 graph: self.graph.clone(),
7656 id,
7657 }
7658 }
7659
7660 /// Single-output SelectiveScan: returns the `y` slot of the
7661 /// bundled producer, with the View(0) projection emitted so
7662 /// callers can downstream-realize / copy / etc. transparently.
7663 /// See [`Self::selective_scan_bundled`] for the multi-output
7664 /// variant that also exposes `last_state` for autoregressive
7665 /// resumption.
7666 ///
7667 /// # Panics
7668 ///
7669 /// Panics if any operand belongs to a different [`Graph`] than the one this
7670 /// builder is building into. Operand identity is graph-scoped and checked by
7671 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7672 /// deliberate and replaces the hang a cross-graph handle used to produce.
7673 /// Build every operand from one graph, or use a `Result`-returning entry
7674 /// point where one exists.
7675 pub fn selective_scan(
7676 &self,
7677 delta: &NodeHandle,
7678 a: &NodeHandle,
7679 b: &NodeHandle,
7680 c: &NodeHandle,
7681 delta_softplus: bool,
7682 ) -> NodeHandle {
7683 self.assert_same_graph(delta, "selective_scan", "delta");
7684 self.assert_same_graph(a, "selective_scan", "a");
7685 self.assert_same_graph(b, "selective_scan", "b");
7686 self.assert_same_graph(c, "selective_scan", "c");
7687 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7688 producer
7689 .view(0)
7690 .expect("SelectiveScan view(0) must succeed (just registered slots)")
7691 }
7692
7693 /// Multi-output variant of [`Self::selective_scan`]. Returns
7694 /// `(y, last_state)` — both Op::View tensors projected from the
7695 /// shared bundled producer. `y` matches the existing
7696 /// single-output `selective_scan` shape; `last_state` is the
7697 /// final hidden state `[batch, dim, dstate]` for autoregressive
7698 /// resumption.
7699 pub fn selective_scan_bundled(
7700 &self,
7701 delta: &NodeHandle,
7702 a: &NodeHandle,
7703 b: &NodeHandle,
7704 c: &NodeHandle,
7705 delta_softplus: bool,
7706 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7707 self.require_same_graph(delta, "selective_scan_bundled", "delta")?;
7708 self.require_same_graph(a, "selective_scan_bundled", "a")?;
7709 self.require_same_graph(b, "selective_scan_bundled", "b")?;
7710 self.require_same_graph(c, "selective_scan_bundled", "c")?;
7711 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7712 let y = producer.view(0)?;
7713 let last_state = producer.view(1)?;
7714 Ok((y, last_state))
7715 }
7716
7717 /// Multi-output variant of [`Self::ssd_chunk_scan`]. Returns
7718 /// `(y, last_state)`.
7719 pub fn ssd_chunk_scan_bundled(
7720 &self,
7721 dt: &NodeHandle,
7722 a: &NodeHandle,
7723 b: &NodeHandle,
7724 c: &NodeHandle,
7725 chunk_size: usize,
7726 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7727 self.require_same_graph(dt, "ssd_chunk_scan_bundled", "dt")?;
7728 self.require_same_graph(a, "ssd_chunk_scan_bundled", "a")?;
7729 self.require_same_graph(b, "ssd_chunk_scan_bundled", "b")?;
7730 self.require_same_graph(c, "ssd_chunk_scan_bundled", "c")?;
7731 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7732 let y = producer.view(0)?;
7733 let last_state = producer.view(1)?;
7734 Ok((y, last_state))
7735 }
7736
7737 /// Append an [`Op::NonZeroIndices`] producer node — the keystone
7738 /// primitive for **data-dependent dynamic shapes**. Returns the
7739 /// bundled producer `NodeHandle` (a `[capacity]` U32 tensor); callers
7740 /// usually want [`Self::nonzero_indices_bundled`] to also get the
7741 /// runtime count slot.
7742 ///
7743 /// `capacity = self.elem_count()` is the static worst-case bound
7744 /// (every element nonzero). `count_sym` is the [`SymId`] the executor
7745 /// binds to the realized nonzero count in the per-pass `SymEnv`; the
7746 /// caller allocates it from their `SymGen` and threads it into any
7747 /// downstream op that consumes the count as a dynamic extent /
7748 /// `DynScalar::Sym` (the KV-cache `cached_len` pattern, generalized to
7749 /// a data-determined count).
7750 pub fn nonzero_indices_producer(&self, count_sym: SymId) -> NodeHandle {
7751 let capacity = self.shape().elem_count();
7752 let indices_shape = Shape::from_dims(&[capacity]);
7753 let count_shape = Shape::from_dims(&[1]);
7754 let specs = vec![
7755 fuel_ir::storage::OutputViewSpec {
7756 dtype: DType::U32,
7757 shape: indices_shape.clone(),
7758 layout: Layout::contiguous(indices_shape.clone()),
7759 name: Some("indices"),
7760 },
7761 fuel_ir::storage::OutputViewSpec {
7762 dtype: DType::U32,
7763 shape: count_shape.clone(),
7764 layout: Layout::contiguous(count_shape),
7765 name: Some("count"),
7766 },
7767 ];
7768 let (_total_bytes, views) =
7769 fuel_ir::storage::compose_bundle(&specs).expect("NonZeroIndices compose_bundle");
7770 let mut g = self.graph.write().unwrap();
7771 let id = g.push(Node {
7772 op: Op::NonZeroIndices { count_sym },
7773 inputs: vec![self.id],
7774 shape: indices_shape,
7775 dtype: DType::U32,
7776 });
7777 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7778 .expect("NonZeroIndices set_output_views");
7779 drop(g);
7780 Self {
7781 graph: self.graph.clone(),
7782 id,
7783 }
7784 }
7785
7786 /// Multi-output [`Op::NonZeroIndices`]: returns `(indices, count)` —
7787 /// both `Op::View` projections of the shared bundled producer.
7788 /// `indices` is `[capacity]` U32 (first `count` entries valid, in
7789 /// ascending flat order); `count` is `[1]` U32, the runtime nonzero
7790 /// count. The executor also publishes `count`'s value into the
7791 /// per-pass `SymEnv` under the producer's `count_sym`.
7792 pub fn nonzero_indices_bundled(
7793 &self,
7794 count_sym: SymId,
7795 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7796 let producer = self.nonzero_indices_producer(count_sym);
7797 let indices = producer.view(0)?;
7798 let count = producer.view(1)?;
7799 Ok((indices, count))
7800 }
7801
7802 /// Append a `FusedSoftmaxCrossEntropy` node. Two inputs:
7803 /// - `self` (logits): `[..., V]` F32 / F64 / BF16 / F16
7804 /// - `targets`: `[...]` I64 (class indices; matches PyTorch /
7805 /// baracuda convention)
7806 ///
7807 /// Output dtype is always F32 (the FSCE declared dtype — losses
7808 /// accumulate in F64 and narrow to F32, matching PyTorch and the
7809 /// baracuda kernel) regardless of the logits dtype. Output shape
7810 /// depends on `reduction`:
7811 /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
7812 /// - `Reduction::None` → same as `targets.shape`
7813 ///
7814 /// `ignore_index` rows are dropped from the loss accumulator and
7815 /// the Mean denominator. The conventional sentinel is `-100`.
7816 ///
7817 /// Emits `Op::Fused(FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7818 /// FusedOpParams::FusedSoftmaxCrossEntropy { reduction, ignore_index })`.
7819 /// See `fuel-graph/src/registry/fused_softmax_cross_entropy.rs` for
7820 /// the registry entry and decompose chain.
7821 ///
7822 /// # Panics
7823 ///
7824 /// Panics if any operand belongs to a different [`Graph`] than the one this
7825 /// builder is building into. Operand identity is graph-scoped and checked by
7826 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7827 /// deliberate and replaces the hang a cross-graph handle used to produce.
7828 /// Build every operand from one graph, or use a `Result`-returning entry
7829 /// point where one exists.
7830 pub fn fused_softmax_cross_entropy(
7831 &self,
7832 targets: &NodeHandle,
7833 reduction: crate::registry::Reduction,
7834 ignore_index: i64,
7835 ) -> NodeHandle {
7836 assert!(
7837 Arc::ptr_eq(&self.graph, &targets.graph),
7838 "fused_softmax_cross_entropy: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7839 );
7840 assert!(
7841 matches!(
7842 self.dtype(),
7843 DType::F32 | DType::F64 | DType::BF16 | DType::F16,
7844 ),
7845 "fused_softmax_cross_entropy: logits must be F32/F64/BF16/F16, got {:?}",
7846 self.dtype(),
7847 );
7848 assert_eq!(
7849 targets.dtype(),
7850 DType::I64,
7851 "fused_softmax_cross_entropy: targets must be I64, got {:?}",
7852 targets.dtype(),
7853 );
7854 let logits_dims = self.shape();
7855 let logits_dims = logits_dims.dims();
7856 assert!(
7857 !logits_dims.is_empty(),
7858 "fused_softmax_cross_entropy: logits must have rank ≥ 1",
7859 );
7860 let target_dims = targets.shape();
7861 let target_dims = target_dims.dims();
7862 assert_eq!(
7863 target_dims,
7864 &logits_dims[..logits_dims.len() - 1],
7865 "fused_softmax_cross_entropy: targets shape {target_dims:?} must equal \
7866 logits shape {logits_dims:?} minus the last dim",
7867 );
7868 let out_shape = match reduction {
7869 crate::registry::Reduction::Mean | crate::registry::Reduction::Sum => {
7870 Shape::from_dims(&[])
7871 }
7872 crate::registry::Reduction::None => Shape::from_dims(target_dims),
7873 };
7874 let id = self.graph.write().unwrap().push(Node {
7875 op: Op::Fused(
7876 crate::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7877 crate::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
7878 reduction,
7879 ignore_index,
7880 },
7881 ),
7882 inputs: vec![self.id, targets.id],
7883 shape: out_shape,
7884 dtype: DType::F32,
7885 });
7886 Self {
7887 graph: self.graph.clone(),
7888 id,
7889 }
7890 }
7891
7892 /// Append a `LayerNormLastDim` node with the given epsilon. Shape is
7893 /// preserved.
7894 ///
7895 /// Phase 7.6 step 4 (continued): emits
7896 /// `Op::Fused(FusedOps::LAYER_NORM_LAST_DIM, FusedOpParams::LayerNormLastDim { eps })`
7897 /// through the registry-extended arm. The legacy
7898 /// `Op::LayerNormLastDim { eps }` variant remains in the enum
7899 /// during migration; step 5 drops it once nothing emits it.
7900 pub fn layer_norm_last_dim(&self, eps: f64) -> NodeHandle {
7901 let dims = self.shape();
7902 let d = dims.dims();
7903 assert!(
7904 !d.is_empty() && *d.last().unwrap() > 0,
7905 "layer_norm_last_dim: input must have a non-zero last dim, got {d:?}",
7906 );
7907 self.unary_op(Op::Fused(
7908 crate::registry::FusedOps::LAYER_NORM_LAST_DIM,
7909 crate::registry::FusedOpParams::LayerNormLastDim { eps },
7910 ))
7911 }
7912
7913 /// Apply rotary position embeddings (RoPE) to `self`. The input is
7914 /// expected to have shape `[..., seq, d]` where `seq` is the
7915 /// sequence length and `d` is the per-head feature dim (which must
7916 /// be even). `base` is the frequency base — 10000.0 for LLaMA.
7917 /// `start_pos` lets callers apply RoPE at a non-zero offset, which
7918 /// is what KV-cached inference does when the query for position
7919 /// `n + k` is processed against a cache that already holds
7920 /// positions `0..n+k`.
7921 ///
7922 /// Uses the half-split layout (the one LLaMA and HuggingFace use):
7923 /// pair feature `i` with feature `i + d/2`. Under that layout the
7924 /// rotation reduces to the identity `x' = x·cos + rotate_half(x)·sin`
7925 /// where `rotate_half(x)` concatenates `[-x[d/2:], x[:d/2]]` along
7926 /// the last dim.
7927 ///
7928 /// Implemented as a composition of existing graph primitives —
7929 /// `Slice`, `Neg`, `Concat`, `Reshape`, `BroadcastTo`, `Mul`, `Add`
7930 /// — plus two precomputed `Const` tensors for the cos/sin frequency
7931 /// tables. Every primitive already has a working backward rule, so
7932 /// gradients flow through RoPE without any new backward machinery.
7933 ///
7934 /// Only `f32` is supported today. Extending to other float dtypes
7935 /// is mechanical: build the frequency tables in the target dtype.
7936 pub fn rope(&self, base: f64, start_pos: usize) -> NodeHandle {
7937 let (seq, d) = {
7938 let dims = self.shape();
7939 let v = dims.dims();
7940 let rank = v.len();
7941 assert!(rank >= 2, "rope: input must have rank ≥ 2");
7942 (v[rank - 2], v[rank - 1])
7943 };
7944 let (cos, sin) = build_rope_tables(base, start_pos, seq, d);
7945 // Phase 7.5 G2: const_*_like derives the device from self's
7946 // graph internally — RoPE tables go on the same device as self.
7947 // ⚠️ GAP-003 category 2, in production: the proof EXISTS but is NOT
7948 // LOCAL -- `build_rope_tables` owns the length guarantee and its
7949 // signature `-> (Vec<f32>, Vec<f32>)` does not carry it. So the message
7950 // claims NO proof; it names where the guarantee lives. `rope` returns
7951 // `NodeHandle` and already asserts on rank, so giving it an error
7952 // channel is a signature change -- a different obligation. See #157.
7953 let cos_t = self
7954 .const_f32_like(cos, Shape::from_dims(&[seq, d]))
7955 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7956 let sin_t = self
7957 .const_f32_like(sin, Shape::from_dims(&[seq, d]))
7958 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7959 self.rope_with_tables(&cos_t, &sin_t)
7960 }
7961
7962 /// Apply RoPE using caller-supplied `cos` and `sin` tables. Each
7963 /// table has shape `[seq, head_dim]` and matches the layout
7964 /// [`build_rope_tables`] produces. This is the hot-path entry
7965 /// point: in a transformer forward pass every attention layer
7966 /// applies RoPE to Q and K with the *same* `(start_pos, seq,
7967 /// head_dim)`, so the caller can build the tables once and share
7968 /// the const nodes across all layers rather than re-duplicating
7969 /// them inside each `.rope()` call. The classic [`Self::rope`] entry
7970 /// point funnels through this after building the tables itself.
7971 ///
7972 /// # Panics
7973 ///
7974 /// Panics if any operand belongs to a different [`Graph`] than the one this
7975 /// builder is building into. Operand identity is graph-scoped and checked by
7976 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7977 /// deliberate and replaces the hang a cross-graph handle used to produce.
7978 /// Build every operand from one graph, or use a `Result`-returning entry
7979 /// point where one exists.
7980 pub fn rope_with_tables(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
7981 self.assert_same_graph(cos, "rope_with_tables", "cos");
7982 self.assert_same_graph(sin, "rope_with_tables", "sin");
7983 assert_eq!(
7984 self.dtype(),
7985 DType::F32,
7986 "rope: only f32 is supported today (cast explicitly for other dtypes)",
7987 );
7988 let in_shape = self.shape();
7989 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
7990 let rank = dims_vec.len();
7991 assert!(
7992 rank >= 2,
7993 "rope: input must have rank ≥ 2, got {dims_vec:?}"
7994 );
7995 let seq = dims_vec[rank - 2];
7996 let d = dims_vec[rank - 1];
7997 assert!(d.is_multiple_of(2), "rope: feature dim {d} must be even",);
7998 let cos_shape = cos.shape();
7999 let sin_shape = sin.shape();
8000 assert_eq!(
8001 cos_shape.dims(),
8002 &[seq, d],
8003 "rope_with_tables: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
8004 cos_shape.dims(),
8005 );
8006 assert_eq!(
8007 sin_shape.dims(),
8008 &[seq, d],
8009 "rope_with_tables: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
8010 sin_shape.dims(),
8011 );
8012 let _ = rank;
8013 // Emit a single fused Rope node. The decomposed version
8014 // (slice+neg+concat+broadcast+mul+add) produces ~72 dispatches
8015 // on GPU backends because concat-along-last-dim has a per-row
8016 // host loop. Fused path dispatches once.
8017 //
8018 // Phase 7.6 step 4 (continued): emits
8019 // `Op::Fused(FusedOps::ROPE, FusedOpParams::Rope)` through the
8020 // registry-extended arm. The legacy `Op::Rope` variant remains
8021 // in the enum during migration; step 5 drops it once nothing
8022 // emits it.
8023 let out_shape = in_shape.clone();
8024 let dtype = self.dtype();
8025 let id = self.graph.write().unwrap().push(Node {
8026 op: Op::Fused(
8027 crate::registry::FusedOps::ROPE,
8028 crate::registry::FusedOpParams::Rope,
8029 ),
8030 inputs: vec![self.id, cos.id, sin.id],
8031 shape: out_shape,
8032 dtype,
8033 });
8034 Self {
8035 graph: self.graph.clone(),
8036 id,
8037 }
8038 }
8039
8040 /// The pre-fused decomposition of `rope_with_tables`. Retained so
8041 /// backends without a native `Op::Rope` kernel can synthesize from
8042 /// primitives, and so correctness tests can cross-check the fused
8043 /// path against the primitive path.
8044 ///
8045 /// # Panics
8046 ///
8047 /// Panics if any operand belongs to a different [`Graph`] than the one this
8048 /// builder is building into. Operand identity is graph-scoped and checked by
8049 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8050 /// deliberate and replaces the hang a cross-graph handle used to produce.
8051 /// Build every operand from one graph, or use a `Result`-returning entry
8052 /// point where one exists.
8053 #[doc(hidden)]
8054 pub fn rope_with_tables_decomposed(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8055 self.assert_same_graph(cos, "rope_with_tables_decomposed", "cos");
8056 self.assert_same_graph(sin, "rope_with_tables_decomposed", "sin");
8057 let in_shape = self.shape();
8058 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8059 let rank = dims_vec.len();
8060 let seq = dims_vec[rank - 2];
8061 let d = dims_vec[rank - 1];
8062 let half = d / 2;
8063
8064 let mut broadcast_shape: Vec<usize> = vec![1_usize; rank];
8065 broadcast_shape[rank - 2] = seq;
8066 broadcast_shape[rank - 1] = d;
8067 let cos_reshaped = cos.reshape(Shape::from_dims(&broadcast_shape));
8068 let sin_reshaped = sin.reshape(Shape::from_dims(&broadcast_shape));
8069 let cos_bcast = cos_reshaped.broadcast_to(in_shape.clone());
8070 let sin_bcast = sin_reshaped.broadcast_to(in_shape);
8071
8072 let first_half = self.slice(rank - 1, 0, half);
8073 let second_half = self.slice(rank - 1, half, half);
8074 let neg_second = second_half.neg();
8075 let rotated_half = neg_second.concat(&first_half, rank - 1);
8076
8077 let left = self.mul(&cos_bcast);
8078 let right = rotated_half.mul(&sin_bcast);
8079 left.add(&right)
8080 }
8081
8082 /// Root-Mean-Square Normalization along the last dim, without
8083 /// affine parameters. `y = x / sqrt(mean(x², last) + eps)`.
8084 ///
8085 /// This is the normalization layer used by LLaMA-family models.
8086 /// Unlike LayerNorm, RmsNorm does not subtract the mean — it only
8087 /// divides by the root-mean-square, which is both cheaper and
8088 /// empirically just as effective in transformer blocks.
8089 ///
8090 /// Emits a fused RmsNormLastDim node. Backends that have a native
8091 /// implementation dispatch it as one kernel; ones that don't get a
8092 /// CPU fallback via the reference implementation.
8093 ///
8094 /// Phase 7.6 step 4 (continued): emits
8095 /// `Op::Fused(FusedOps::RMS_NORM_LAST_DIM, FusedOpParams::RmsNormLastDim { eps })`
8096 /// through the registry-extended arm. The legacy
8097 /// `Op::RmsNormLastDim { eps }` variant remains in the enum during
8098 /// migration; step 5 drops it once nothing emits it.
8099 ///
8100 /// Use [`rms_norm_last_dim_decomposed`](Self::rms_norm_last_dim_decomposed)
8101 /// instead if you need to differentiate through this op —
8102 /// backward through the fused op is not yet implemented.
8103 pub fn rms_norm_last_dim(&self, eps: f64) -> NodeHandle {
8104 let x_dims_vec: Vec<usize> = self.shape().dims().to_vec();
8105 assert!(
8106 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8107 "rms_norm_last_dim: input must have non-zero last dim, got {x_dims_vec:?}",
8108 );
8109 self.unary_op(Op::Fused(
8110 crate::registry::FusedOps::RMS_NORM_LAST_DIM,
8111 crate::registry::FusedOpParams::RmsNormLastDim { eps },
8112 ))
8113 }
8114
8115 /// Decomposed version — emits the (sqr → mean_dim → reshape →
8116 /// add_scalar → sqrt → broadcast_to → div) primitive chain. Has
8117 /// working backward rules through its primitive subgraph. Use
8118 /// this when you need to differentiate through RMSNorm; use
8119 /// [`rms_norm_last_dim`](Self::rms_norm_last_dim) for inference.
8120 pub fn rms_norm_last_dim_decomposed(&self, eps: f64) -> NodeHandle {
8121 let x_shape = self.shape();
8122 let x_dims_vec: Vec<usize> = x_shape.dims().to_vec();
8123 assert!(
8124 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8125 "rms_norm_last_dim_decomposed: input must have non-zero last dim, got {x_dims_vec:?}",
8126 );
8127 let last = x_dims_vec.len() - 1;
8128 let mean_sq = self.sqr().mean_dim(last);
8129 let mut keepdim_dims = x_dims_vec.clone();
8130 keepdim_dims[last] = 1;
8131 let mean_sq_kd = mean_sq.reshape(Shape::from_dims(&keepdim_dims));
8132 let denom = mean_sq_kd.add_scalar(eps).sqrt();
8133 let denom_bcast = denom.broadcast_to(x_shape);
8134 self.div(&denom_bcast)
8135 }
8136
8137 // --- indexing ---
8138
8139 /// Append an `IndexSelect` node that picks slices from `self` along
8140 /// `dim` using a 1-D `u32` index tensor. The output has the same
8141 /// shape as `self` except dimension `dim` is replaced by
8142 /// `indices.shape()[0]`.
8143 ///
8144 /// # Panics
8145 ///
8146 /// Panics if any operand belongs to a different [`Graph`] than the one this
8147 /// builder is building into. Operand identity is graph-scoped and checked by
8148 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8149 /// deliberate and replaces the hang a cross-graph handle used to produce.
8150 /// Build every operand from one graph, or use a `Result`-returning entry
8151 /// point where one exists.
8152 pub fn index_select(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8153 assert!(
8154 Arc::ptr_eq(&self.graph, &indices.graph),
8155 "index_select: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8156 );
8157 assert_eq!(
8158 indices.dtype(),
8159 DType::U32,
8160 "index_select: index tensor must be U32, got {:?}",
8161 indices.dtype(),
8162 );
8163 let idx_dims = indices.shape();
8164 assert_eq!(
8165 idx_dims.dims().len(),
8166 1,
8167 "index_select: index tensor must be rank 1, got {:?}",
8168 idx_dims.dims(),
8169 );
8170 let data_dims = self.shape();
8171 assert!(
8172 dim < data_dims.dims().len(),
8173 "index_select: dim {dim} out of bounds for data shape {:?}",
8174 data_dims.dims(),
8175 );
8176 let op = Op::IndexSelect { dim };
8177 let (shape, dtype) = crate::shape::primitive_shape(
8178 &op,
8179 &[data_dims, idx_dims],
8180 &[self.dtype(), indices.dtype()],
8181 )
8182 .expect("index_select: shapes/dims validated above");
8183 let id = self.graph.write().unwrap().push(Node {
8184 op,
8185 inputs: vec![self.id, indices.id],
8186 shape,
8187 dtype,
8188 });
8189 Self {
8190 graph: self.graph.clone(),
8191 id,
8192 }
8193 }
8194
8195 /// Append a `Gather` node that performs an N-dimensional gather along
8196 /// `dim`. The `indices` tensor must be `U32` with the same rank as
8197 /// `self`. Output shape equals `indices.shape()`.
8198 ///
8199 /// # Panics
8200 ///
8201 /// Panics if any operand belongs to a different [`Graph`] than the one this
8202 /// builder is building into. Operand identity is graph-scoped and checked by
8203 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8204 /// deliberate and replaces the hang a cross-graph handle used to produce.
8205 /// Build every operand from one graph, or use a `Result`-returning entry
8206 /// point where one exists.
8207 pub fn gather(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8208 assert!(
8209 Arc::ptr_eq(&self.graph, &indices.graph),
8210 "gather: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8211 );
8212 assert_eq!(
8213 indices.dtype(),
8214 DType::U32,
8215 "gather: index tensor must be U32, got {:?}",
8216 indices.dtype(),
8217 );
8218 let data_rank = self.shape().dims().len();
8219 let idx_rank = indices.shape().dims().len();
8220 assert_eq!(
8221 data_rank, idx_rank,
8222 "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
8223 );
8224 assert!(
8225 dim < data_rank,
8226 "gather: dim {dim} out of bounds for rank {data_rank}",
8227 );
8228 let op = Op::Gather { dim };
8229 let (shape, dtype) = crate::shape::primitive_shape(
8230 &op,
8231 &[self.shape(), indices.shape()],
8232 &[self.dtype(), indices.dtype()],
8233 )
8234 .expect("gather: shapes/dims validated above");
8235 let id = self.graph.write().unwrap().push(Node {
8236 op,
8237 inputs: vec![self.id, indices.id],
8238 shape,
8239 dtype,
8240 });
8241 Self {
8242 graph: self.graph.clone(),
8243 id,
8244 }
8245 }
8246
8247 /// Append a `Concat` node joining `self` and `other` along `dim`.
8248 ///
8249 /// # Panics
8250 ///
8251 /// Panics if any operand belongs to a different [`Graph`] than the one this
8252 /// builder is building into. Operand identity is graph-scoped and checked by
8253 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8254 /// deliberate and replaces the hang a cross-graph handle used to produce.
8255 /// Build every operand from one graph, or use a `Result`-returning entry
8256 /// point where one exists.
8257 pub fn concat(&self, other: &NodeHandle, dim: usize) -> NodeHandle {
8258 assert!(
8259 Arc::ptr_eq(&self.graph, &other.graph),
8260 "concat: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8261 );
8262 assert_eq!(
8263 self.dtype(),
8264 other.dtype(),
8265 "concat: dtype mismatch {:?} vs {:?}",
8266 self.dtype(),
8267 other.dtype(),
8268 );
8269 let a = self.shape();
8270 let b = other.shape();
8271 let ad = a.dims();
8272 let bd = b.dims();
8273 assert_eq!(ad.len(), bd.len(), "concat: rank mismatch");
8274 assert!(dim < ad.len(), "concat: dim out of bounds");
8275 for i in 0..ad.len() {
8276 if i != dim {
8277 assert_eq!(
8278 ad[i], bd[i],
8279 "concat: non-dim shapes must match (dim {i}: {} vs {})",
8280 ad[i], bd[i],
8281 );
8282 }
8283 }
8284 let op = Op::Concat { dim };
8285 let (shape, dtype) =
8286 crate::shape::primitive_shape(&op, &[a, b], &[self.dtype(), other.dtype()])
8287 .expect("concat: shapes/dtypes validated above");
8288 let id = self.graph.write().unwrap().push(Node {
8289 op,
8290 inputs: vec![self.id, other.id],
8291 shape,
8292 dtype,
8293 });
8294 Self {
8295 graph: self.graph.clone(),
8296 id,
8297 }
8298 }
8299
8300 /// Append a `Slice` (narrow) node taking elements `[start, start+len)`
8301 /// along `dim`. The output has the same rank; only `dim` shrinks.
8302 pub fn slice(&self, dim: usize, start: usize, len: usize) -> NodeHandle {
8303 let in_shape = self.shape();
8304 let in_dims = in_shape.dims();
8305 assert!(dim < in_dims.len(), "slice: dim out of bounds");
8306 assert!(
8307 start + len <= in_dims[dim],
8308 "slice: [start={start}, len={len}) exceeds dim size {}",
8309 in_dims[dim],
8310 );
8311 let op = Op::Slice { dim, start, len };
8312 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8313 .expect("slice: dim/start/len validated above");
8314 let id = self.graph.write().unwrap().push(Node {
8315 op,
8316 inputs: vec![self.id],
8317 shape,
8318 dtype,
8319 });
8320 Self {
8321 graph: self.graph.clone(),
8322 id,
8323 }
8324 }
8325
8326 /// Append an `AddScalar` node: `y[i] = x[i] + c`. Convenient for
8327 /// avoiding a full-shape const node when you just want to bias a
8328 /// tensor by a constant.
8329 pub fn add_scalar(&self, c: f64) -> NodeHandle {
8330 self.unary_op(Op::AddScalar(c))
8331 }
8332
8333 /// Append a `MulScalar` node: `y[i] = x[i] * c`.
8334 pub fn mul_scalar(&self, c: f64) -> NodeHandle {
8335 self.unary_op(Op::MulScalar(c))
8336 }
8337
8338 /// Append a `PowI` node raising each element to an integer power.
8339 pub fn powi(&self, n: i32) -> NodeHandle {
8340 self.unary_op(Op::PowI(n))
8341 }
8342
8343 /// Append a `Clamp` node restricting each element to `[min, max]`.
8344 pub fn clamp(&self, min: f64, max: f64) -> NodeHandle {
8345 assert!(min <= max, "clamp: min ({min}) must be <= max ({max})",);
8346 self.unary_op(Op::Clamp { min, max })
8347 }
8348
8349 /// Append a `Maximum` node `max(self, other)` element-wise. Matching
8350 /// shapes required.
8351 ///
8352 /// # Panics
8353 ///
8354 /// Panics if any operand belongs to a different [`Graph`] than the one this
8355 /// builder is building into. Operand identity is graph-scoped and checked by
8356 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8357 /// deliberate and replaces the hang a cross-graph handle used to produce.
8358 /// Build every operand from one graph, or use a `Result`-returning entry
8359 /// point where one exists.
8360 pub fn maximum(&self, other: &NodeHandle) -> NodeHandle {
8361 self.binary_op("maximum", Op::Maximum, other, self.shape())
8362 }
8363
8364 /// Append a `Minimum` node `min(self, other)` element-wise.
8365 ///
8366 /// # Panics
8367 ///
8368 /// Panics if any operand belongs to a different [`Graph`] than the one this
8369 /// builder is building into. Operand identity is graph-scoped and checked by
8370 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8371 /// deliberate and replaces the hang a cross-graph handle used to produce.
8372 /// Build every operand from one graph, or use a `Result`-returning entry
8373 /// point where one exists.
8374 pub fn minimum(&self, other: &NodeHandle) -> NodeHandle {
8375 self.binary_op("minimum", Op::Minimum, other, self.shape())
8376 }
8377
8378 /// The IEEE-754 NaN-**suppressing** maximum — the KISS-OPS §6.15-0001
8379 /// `fmax_ieee` op, DISTINCT from [`maximum`](Self::maximum) (which is
8380 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8381 /// the other; if both are NaN, returns NaN; otherwise the larger.
8382 ///
8383 /// Built by RESOLUTION through the spec-pinned §6.13 decomposition
8384 /// (KISS-OPS-6.15-0001), used VERBATIM — Fuel does not substitute `maximum`
8385 /// for it (that substitution is the §6.15 violation). Because the
8386 /// decomposition is spec-authored, its edge behaviour — including ±0 ordering
8387 /// under `cmp_ge` (`cmp_ge(-0.0, +0.0)` is true, so this returns `-0.0` for
8388 /// that pair) — is the SPEC's to define and a KISS conformance vector's to
8389 /// catch. Fuel resolves; it does not re-derive. (GAP-048.)
8390 pub fn fmax_ieee(&self, other: &NodeHandle) -> NodeHandle {
8391 // select(a != a, b, select(b != b, a, select(a >= b, a, b)))
8392 let a = self;
8393 let b = other;
8394 let plain = a.ge(b).where_cond(a, b); // a >= b ? a : b
8395 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8396 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8397 }
8398
8399 /// The IEEE-754 NaN-**suppressing** minimum — the KISS-OPS §6.15-0001
8400 /// `fmin_ieee` op, DISTINCT from [`minimum`](Self::minimum) (which is
8401 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8402 /// the other; if both are NaN, returns NaN; otherwise the smaller.
8403 ///
8404 /// Built by RESOLUTION through the spec-pinned KISS-OPS §6.13 decomposition
8405 /// (KISS-OPS-6.15-0001), used VERBATIM — the `cmp_le` mirror of
8406 /// [`fmax_ieee`](Self::fmax_ieee)'s `cmp_ge` form. Fuel resolves; it does not
8407 /// substitute `minimum` (that substitution is the §6.15 violation) and does
8408 /// not re-derive: the decomposition is KISS's, so its ±0 edge behaviour is the
8409 /// spec's to define and a KISS conformance vector's to catch. (GAP-048.)
8410 pub fn fmin_ieee(&self, other: &NodeHandle) -> NodeHandle {
8411 // select(a != a, b, select(b != b, a, select(a <= b, a, b)))
8412 let a = self;
8413 let b = other;
8414 let plain = a.le(b).where_cond(a, b); // a <= b ? a : b
8415 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8416 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8417 }
8418
8419 /// Round toward zero — the KISS-OPS §6.3 `trunc` floor op (GAP-300).
8420 ///
8421 /// ⚠️ Unlike [`fmax_ieee`](Self::fmax_ieee)/[`fmin_ieee`](Self::fmin_ieee),
8422 /// which resolve through KISS's OWN §6.13 decompositions, `trunc` is a §6.3
8423 /// *floor* op: KISS-OPS-6.3-0003 forbids the standard from carrying a
8424 /// reference decomposition for a floor op, so THIS expansion is FUEL's, blessed
8425 /// by no spec clause. It IS now checked by KISS vectors: `ops-rounding.json`
8426 /// (vendored at KISS `0af5d3b6`) carries 18 `f32` `trunc` cells (signed zero, halves
8427 /// and ties, 2^23, max finite, ±inf, subnormals), all of which pass through the lazy
8428 /// `Tensor` (`fuel-tensor/tests/kiss_nan_conformance.rs`); `f64` and NaN inputs are
8429 /// not in that file. Beyond it, correctness is Fuel's liability — see GAP-300, whose born-reds assert
8430 /// on `to_bits()` (a value compare `0.0 == -0.0` passes vacuously).
8431 ///
8432 /// `trunc(q) = if q >= 0 { floor(q) } else { ceil(q) }`. Float dtypes only;
8433 /// integer dtypes are already whole, so `trunc` is identity for them (returned
8434 /// unchanged — never a panic on a non-float operand).
8435 ///
8436 /// REJECTED-FOR-NOW alternative: `copysign(floor(abs(q)), q)` is cleaner (no
8437 /// dtype-matched zero; ±0/NaN/inf fall out of the IEEE primitives). Fuel has no
8438 /// `copysign` op today (absent from `Op` and the builder API), so it is not
8439 /// buildable — adopt it IF `copysign` ever lands.
8440 pub fn trunc(&self) -> NodeHandle {
8441 let q = self;
8442 // A scalar zero of q's dtype, broadcast to q's shape — comparisons require
8443 // matching shapes (no implicit broadcast in `binary_compare_op`).
8444 let zero = match q.dtype() {
8445 DType::F32 => q
8446 .const_f32_like(vec![0.0f32], &[1])
8447 .expect("trunc: a 1-element vec with shape [1]")
8448 .broadcast_to(q.shape()),
8449 DType::F64 => q
8450 .const_f64_like(vec![0.0f64], &[1])
8451 .expect("trunc: a 1-element vec with shape [1]")
8452 .broadcast_to(q.shape()),
8453 DType::BF16 => q
8454 .const_bf16_like(vec![half::bf16::from_f32(0.0)], &[1])
8455 .expect("trunc: a 1-element vec with shape [1]")
8456 .broadcast_to(q.shape()),
8457 DType::F16 => q
8458 .const_f16_like(vec![half::f16::from_f32(0.0)], &[1])
8459 .expect("trunc: a 1-element vec with shape [1]")
8460 .broadcast_to(q.shape()),
8461 // Integer/other dtypes are already whole: trunc is identity.
8462 _ => return q.clone(),
8463 };
8464 // q >= 0 ? floor(q) : ceil(q). Note: at ±0 BOTH branches yield the same
8465 // signed zero (`floor(-0.0) == ceil(-0.0) == -0.0`), so trunc's ±0 result
8466 // is robust to a tie-bias in `ge` — but the born-red still checks the bits.
8467 q.ge(&zero).where_cond(&q.floor(), &q.ceil())
8468 }
8469
8470 /// Truncated remainder — the KISS-OPS §6.15-0003 `rem_trunc` op, DISTINCT from
8471 /// [`rem`](Self::rem) (which is FLOORED / PyTorch, sign of the *divisor*).
8472 /// `rem_trunc` takes the sign of the *dividend* (C99 `fmod` / Rust `%`).
8473 ///
8474 /// Built by RESOLUTION through KISS's spec-pinned §6.13 decomposition
8475 /// (KISS-OPS-6.15-0003) — `a - trunc(a / b) * b` — used VERBATIM. Fuel does not
8476 /// substitute `rem` (that substitution is the §6.15 violation); the two diverge
8477 /// whenever the operands have opposite signs (e.g. `-7 rem_trunc 3 = -1`, where
8478 /// `rem` (floored) = `2`). The `trunc` leaf is Fuel's own expansion (GAP-300).
8479 pub fn rem_trunc(&self, other: &NodeHandle) -> NodeHandle {
8480 // a - trunc(a / b) * b
8481 let a = self;
8482 let b = other;
8483 let t = a.div(b).trunc();
8484 a.sub(&t.mul(b))
8485 }
8486
8487 /// Element-wise addition with automatic broadcasting. Unlike `add`,
8488 /// which requires matching shapes, `broadcast_add` computes the
8489 /// broadcast shape of the two operands, inserts explicit
8490 /// `BroadcastTo` nodes as needed, and then emits a regular `Add`.
8491 /// Useful for bias addition (`[batch, hidden] + [hidden]`) without
8492 /// the caller writing the broadcast out explicitly.
8493 ///
8494 /// # Panics
8495 ///
8496 /// Panics if any operand belongs to a different [`Graph`] than the one this
8497 /// builder is building into. Operand identity is graph-scoped and checked by
8498 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8499 /// deliberate and replaces the hang a cross-graph handle used to produce.
8500 /// Build every operand from one graph, or use a `Result`-returning entry
8501 /// point where one exists.
8502 pub fn broadcast_add(&self, other: &NodeHandle) -> NodeHandle {
8503 let (a, b) = self.auto_broadcast_pair("broadcast_add", other);
8504 a.add(&b)
8505 }
8506
8507 /// Element-wise subtraction with automatic broadcasting.
8508 ///
8509 /// # Panics
8510 ///
8511 /// Panics if any operand belongs to a different [`Graph`] than the one this
8512 /// builder is building into. Operand identity is graph-scoped and checked by
8513 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8514 /// deliberate and replaces the hang a cross-graph handle used to produce.
8515 /// Build every operand from one graph, or use a `Result`-returning entry
8516 /// point where one exists.
8517 pub fn broadcast_sub(&self, other: &NodeHandle) -> NodeHandle {
8518 let (a, b) = self.auto_broadcast_pair("broadcast_sub", other);
8519 a.sub(&b)
8520 }
8521
8522 /// Element-wise multiplication with automatic broadcasting.
8523 ///
8524 /// # Panics
8525 ///
8526 /// Panics if any operand belongs to a different [`Graph`] than the one this
8527 /// builder is building into. Operand identity is graph-scoped and checked by
8528 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8529 /// deliberate and replaces the hang a cross-graph handle used to produce.
8530 /// Build every operand from one graph, or use a `Result`-returning entry
8531 /// point where one exists.
8532 pub fn broadcast_mul(&self, other: &NodeHandle) -> NodeHandle {
8533 let (a, b) = self.auto_broadcast_pair("broadcast_mul", other);
8534 a.mul(&b)
8535 }
8536
8537 /// Element-wise division with automatic broadcasting.
8538 ///
8539 /// # Panics
8540 ///
8541 /// Panics if any operand belongs to a different [`Graph`] than the one this
8542 /// builder is building into. Operand identity is graph-scoped and checked by
8543 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8544 /// deliberate and replaces the hang a cross-graph handle used to produce.
8545 /// Build every operand from one graph, or use a `Result`-returning entry
8546 /// point where one exists.
8547 pub fn broadcast_div(&self, other: &NodeHandle) -> NodeHandle {
8548 let (a, b) = self.auto_broadcast_pair("broadcast_div", other);
8549 a.div(&b)
8550 }
8551
8552 /// Build both operands broadcast to their common shape. Used by the
8553 /// `broadcast_*` wrappers above. Inserts explicit `BroadcastTo` nodes
8554 /// on whichever side needs them — either or both may pass through
8555 /// unchanged if already at the target shape.
8556 fn auto_broadcast_pair(
8557 &self,
8558 op: &'static str,
8559 other: &NodeHandle,
8560 ) -> (NodeHandle, NodeHandle) {
8561 assert!(
8562 Arc::ptr_eq(&self.graph, &other.graph),
8563 "{op}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8564 each `from_*` constructor mints a NEW graph, so build the second operand with \
8565 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8566 self.graph_id(),
8567 other.graph_id(),
8568 );
8569 assert_eq!(
8570 self.dtype(),
8571 other.dtype(),
8572 "{op}: dtype mismatch {:?} vs {:?}",
8573 self.dtype(),
8574 other.dtype(),
8575 );
8576 let a_shape = self.shape();
8577 let b_shape = other.shape();
8578 let target_dims = compute_broadcast_shape(a_shape.dims(), b_shape.dims());
8579 let target = Shape::from_dims(&target_dims);
8580 let a = if a_shape.dims() == target.dims() {
8581 self.clone()
8582 } else {
8583 self.broadcast_to(target.clone())
8584 };
8585 let b = if b_shape.dims() == target.dims() {
8586 other.clone()
8587 } else {
8588 other.broadcast_to(target)
8589 };
8590 (a, b)
8591 }
8592
8593 /// Append an `IndexAdd` node — the functional inverse of
8594 /// `IndexSelect`. Returns `base` with `src` added at positions given
8595 /// by `indices` along `dim`.
8596 ///
8597 /// # Panics
8598 ///
8599 /// Panics if any operand belongs to a different [`Graph`] than the one this
8600 /// builder is building into. Operand identity is graph-scoped and checked by
8601 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8602 /// deliberate and replaces the hang a cross-graph handle used to produce.
8603 /// Build every operand from one graph, or use a `Result`-returning entry
8604 /// point where one exists.
8605 pub fn index_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8606 assert!(
8607 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8608 "index_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8609 );
8610 assert_eq!(indices.dtype(), DType::U32, "index_add: index must be U32");
8611 assert_eq!(
8612 self.dtype(),
8613 src.dtype(),
8614 "index_add: base and src dtypes must match"
8615 );
8616 let base_dims = self.shape();
8617 let src_dims = src.shape();
8618 assert_eq!(
8619 base_dims.dims().len(),
8620 src_dims.dims().len(),
8621 "index_add: base and src must have the same rank",
8622 );
8623 assert_eq!(
8624 indices.shape().dims().len(),
8625 1,
8626 "index_add: index must be rank 1",
8627 );
8628 assert_eq!(
8629 src_dims.dims()[dim],
8630 indices.shape().dims()[0],
8631 "index_add: src dim {dim} ({}) must match index length ({})",
8632 src_dims.dims()[dim],
8633 indices.shape().dims()[0],
8634 );
8635 let dtype = self.dtype();
8636 let out_shape = base_dims;
8637 let id = self.graph.write().unwrap().push(Node {
8638 op: Op::IndexAdd { dim },
8639 inputs: vec![self.id, indices.id, src.id],
8640 shape: out_shape,
8641 dtype,
8642 });
8643 Self {
8644 graph: self.graph.clone(),
8645 id,
8646 }
8647 }
8648
8649 /// Append a `ScatterAdd` node — the functional inverse of `Gather`.
8650 /// Returns `base` with values from `src` accumulated at positions
8651 /// given by `indices` (with `indices[p]` substituted at `dim`).
8652 ///
8653 /// # Panics
8654 ///
8655 /// Panics if any operand belongs to a different [`Graph`] than the one this
8656 /// builder is building into. Operand identity is graph-scoped and checked by
8657 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8658 /// deliberate and replaces the hang a cross-graph handle used to produce.
8659 /// Build every operand from one graph, or use a `Result`-returning entry
8660 /// point where one exists.
8661 pub fn scatter_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8662 assert!(
8663 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8664 "scatter_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8665 );
8666 assert_eq!(
8667 indices.dtype(),
8668 DType::U32,
8669 "scatter_add: index must be U32"
8670 );
8671 assert_eq!(
8672 self.dtype(),
8673 src.dtype(),
8674 "scatter_add: base and src dtypes must match"
8675 );
8676 assert_eq!(
8677 indices.shape().dims(),
8678 src.shape().dims(),
8679 "scatter_add: index and src must have the same shape",
8680 );
8681 let dtype = self.dtype();
8682 let out_shape = self.shape();
8683 let id = self.graph.write().unwrap().push(Node {
8684 op: Op::ScatterAdd { dim },
8685 inputs: vec![self.id, indices.id, src.id],
8686 shape: out_shape,
8687 dtype,
8688 });
8689 Self {
8690 graph: self.graph.clone(),
8691 id,
8692 }
8693 }
8694
8695 // --- internal helpers for the new builders ---
8696
8697 fn scalar_reduction(&self, op: Op) -> NodeHandle {
8698 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
8699 .expect("scalar_reduction: single input always infers a rank-0 shape");
8700 let id = self.graph.write().unwrap().push(Node {
8701 op,
8702 inputs: vec![self.id],
8703 shape,
8704 dtype,
8705 });
8706 Self {
8707 graph: self.graph.clone(),
8708 id,
8709 }
8710 }
8711
8712 fn axis_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
8713 let in_shape = self.shape();
8714 assert!(
8715 dim < in_shape.dims().len(),
8716 "{name}: dim {dim} out of bounds for shape {:?}",
8717 in_shape.dims(),
8718 );
8719 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8720 .expect("axis_reduction: dim validated above");
8721 let id = self.graph.write().unwrap().push(Node {
8722 op,
8723 inputs: vec![self.id],
8724 shape,
8725 dtype,
8726 });
8727 Self {
8728 graph: self.graph.clone(),
8729 id,
8730 }
8731 }
8732
8733 // Internal helpers. Both shape-validate and append.
8734
8735 /// Build-time graph-affinity check for a `Result`-returning builder.
8736 ///
8737 /// Node ids index ONE graph's arena, so an operand from a different graph
8738 /// records an id pointing at an unrelated node — a malformed dependency
8739 /// graph whose failure mode is a **realize-time hang**, not a panic or an
8740 /// error. Checking here converts a silent deadlock into a typed build-time
8741 /// error naming both graphs, per "validate at graph-build time".
8742 fn require_same_graph(
8743 &self,
8744 other: &NodeHandle,
8745 op: &str,
8746 role: &str,
8747 ) -> std::result::Result<(), fuel_ir::Error> {
8748 if !Arc::ptr_eq(&self.graph, &other.graph) {
8749 return Err(fuel_ir::Error::Msg(format!(
8750 "{op}: operands must live on the same graph — self is on graph #{}, \
8751 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8752 build the other operand with `from_*_on(self.graph(), ..)` or \
8753 `const_*_like`",
8754 self.graph_id(),
8755 other.graph_id(),
8756 ))
8757 .bt());
8758 }
8759 Ok(())
8760 }
8761
8762 /// Panicking sibling of [`Self::require_same_graph`] for the builders that
8763 /// return `NodeHandle` rather than `Result` — same convention as `matmul`,
8764 /// `qmatmul`, `conv2d` and `paged_attn`. A panic at the build site is far
8765 /// better than the hang it replaces: it names the operand and both graphs.
8766 fn assert_same_graph(&self, other: &NodeHandle, op: &str, role: &str) {
8767 assert!(
8768 Arc::ptr_eq(&self.graph, &other.graph),
8769 "{op}: operands must live on the same graph — self is on graph #{}, \
8770 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8771 build the other operand with `from_*_on(self.graph(), ..)` or \
8772 `const_*_like`",
8773 self.graph_id(),
8774 other.graph_id(),
8775 );
8776 }
8777
8778 fn binary_op(
8779 &self,
8780 name: &'static str,
8781 op: Op,
8782 other: &NodeHandle,
8783 out_shape: Shape,
8784 ) -> NodeHandle {
8785 assert!(
8786 Arc::ptr_eq(&self.graph, &other.graph),
8787 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8788 each `from_*` constructor mints a NEW graph, so build the second operand with \
8789 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8790 self.graph_id(),
8791 other.graph_id(),
8792 );
8793 assert_eq!(
8794 self.dtype(),
8795 other.dtype(),
8796 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8797 self.dtype(),
8798 other.dtype(),
8799 );
8800 assert_eq!(
8801 self.shape().dims(),
8802 other.shape().dims(),
8803 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8804 self.shape().dims(),
8805 other.shape().dims(),
8806 );
8807 let dtype = self.dtype();
8808 let id = self.graph.write().unwrap().push(Node {
8809 op,
8810 inputs: vec![self.id, other.id],
8811 shape: out_shape,
8812 dtype,
8813 });
8814 Self {
8815 graph: self.graph.clone(),
8816 id,
8817 }
8818 }
8819
8820 /// Result-returning sibling of [`Self::binary_op`]. Validates the
8821 /// graph/dtype/shape preconditions and returns `Err` rather than
8822 /// panicking — the production-correct shape new builders should
8823 /// use. Existing panicking sites are kept for back-compat; new
8824 /// ops should call this directly.
8825 fn try_binary_op(
8826 &self,
8827 name: &'static str,
8828 op: Op,
8829 other: &NodeHandle,
8830 out_shape: Shape,
8831 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
8832 if !Arc::ptr_eq(&self.graph, &other.graph) {
8833 return Err(fuel_ir::Error::Msg(format!(
8834 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8835 each `from_*` constructor mints a NEW graph, so build the second operand with \
8836 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8837 self.graph_id(),
8838 other.graph_id(),
8839 )).bt());
8840 }
8841 if self.dtype() != other.dtype() {
8842 return Err(fuel_ir::Error::Msg(format!(
8843 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8844 self.dtype(),
8845 other.dtype(),
8846 ))
8847 .bt());
8848 }
8849 if self.shape().dims() != other.shape().dims() {
8850 return Err(fuel_ir::Error::Msg(format!(
8851 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8852 self.shape().dims(),
8853 other.shape().dims(),
8854 ))
8855 .bt());
8856 }
8857 let dtype = self.dtype();
8858 let id = self.graph.write().unwrap().push(Node {
8859 op,
8860 inputs: vec![self.id, other.id],
8861 shape: out_shape,
8862 dtype,
8863 });
8864 Ok(Self {
8865 graph: self.graph.clone(),
8866 id,
8867 })
8868 }
8869
8870 fn unary_op(&self, op: Op) -> NodeHandle {
8871 let shape = self.shape();
8872 let dtype = self.dtype();
8873 let id = self.graph.write().unwrap().push(Node {
8874 op,
8875 inputs: vec![self.id],
8876 shape,
8877 dtype,
8878 });
8879 Self {
8880 graph: self.graph.clone(),
8881 id,
8882 }
8883 }
8884
8885 /// Binary builder for ops whose inputs share dtype/shape but whose
8886 /// output is a `U8` mask (`Op::Equal` and the rest of the
8887 /// comparison family). Differs from [`Self::binary_op`] only in the
8888 /// node's output dtype: always `DType::U8` regardless of input
8889 /// dtype.
8890 fn binary_compare_op(&self, name: &'static str, op: Op, other: &NodeHandle) -> NodeHandle {
8891 assert!(
8892 Arc::ptr_eq(&self.graph, &other.graph),
8893 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8894 each `from_*` constructor mints a NEW graph, so build the second operand with \
8895 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8896 self.graph_id(),
8897 other.graph_id(),
8898 );
8899 assert_eq!(
8900 self.dtype(),
8901 other.dtype(),
8902 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8903 self.dtype(),
8904 other.dtype(),
8905 );
8906 assert_eq!(
8907 self.shape().dims(),
8908 other.shape().dims(),
8909 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8910 self.shape().dims(),
8911 other.shape().dims(),
8912 );
8913 let shape = self.shape();
8914 let id = self.graph.write().unwrap().push(Node {
8915 op,
8916 inputs: vec![self.id, other.id],
8917 shape,
8918 // GAP-168(c): comparisons yield a `Bool` mask. This BUILDER path is
8919 // the one eq/ne/lt/le/gt/ge take; it must agree with the
8920 // `primitive_shape` comparison arm (fuel-graph/src/shape.rs), which
8921 // is the OTHER site that decides this dtype (reached on re-lowering).
8922 dtype: DType::Bool,
8923 });
8924 Self {
8925 graph: self.graph.clone(),
8926 id,
8927 }
8928 }
8929
8930 /// Build the backward graph from `self`, treating `self` as the output
8931 /// whose gradient drives the rest of the computation.
8932 ///
8933 /// Walks the forward graph in reverse topological order, applies the
8934 /// per-op gradient rule to each node, and emits new graph nodes for
8935 /// the gradient with respect to every node reachable from `self`. The
8936 /// returned [`GradMap`] lets you look up the gradient tensor for any
8937 /// forward tensor from the same graph.
8938 ///
8939 /// The initial upstream gradient is a ones tensor of the same shape
8940 /// and dtype as `self` — the conventional `dL/dL = 1` seed for
8941 /// backprop. For a scalar loss this is `[1.0]`; for a non-scalar
8942 /// output it is "each element of the output contributes with weight 1
8943 /// to the total derivative."
8944 ///
8945 /// ## Supported ops in the MVP
8946 ///
8947 /// `Const`, `Add`, `Mul`, `MatMul`, `Transpose`, `Sqr`, `Exp` all have
8948 /// gradient rules implemented. `Relu` panics — its gradient needs a
8949 /// `Step`/`Where`/`Sign` op that is not yet in the catalog and will
8950 /// land in a follow-up once an indicator-valued op is defined.
8951 ///
8952 /// ## Ownership and the forward graph
8953 ///
8954 /// Backward extends the same graph that held the forward pass. The
8955 /// gradient nodes live alongside the forward nodes in one arena. After
8956 /// `backward()`, realizing a gradient tensor re-executes whatever part
8957 /// of the forward pass the gradient depends on — the executor walks
8958 /// the combined graph as one.
8959 pub fn backward(&self) -> GradMap {
8960 let graph_handle = self.graph.clone();
8961
8962 // C3 pre-pass (Op::Scan Phase 2): lower every reachable Op::Scan to
8963 // primitives + decompose the SSM fused recipes BEFORE the topo order is
8964 // taken, so the reverse walk sees only differentiable primitives. On a
8965 // scan-free graph it is a near-no-op — two topo scans (Pass 1's SSM
8966 // collect + Pass 2's first iteration, which finds no scans and breaks),
8967 // no rewiring. The (possibly remapped) root replaces self.id below.
8968 let root = lower_scans_for_backward(&graph_handle, self.id);
8969
8970 // Compute topological order of reachable nodes, then reverse it
8971 // so we walk from the root (output) toward the leaves (inputs).
8972 let mut order = topo_order(&graph_handle.read().unwrap(), root);
8973 order.reverse();
8974
8975 // Initial upstream gradient for the root: ones tensor of matching
8976 // shape and dtype. For a scalar loss this is [1.0]; for vector
8977 // outputs it seeds each element with weight 1.
8978 let (root_shape, root_dtype) = {
8979 let g = graph_handle.read().unwrap();
8980 let n = g.node(root);
8981 (n.shape.clone(), n.dtype)
8982 };
8983 let ones_id = build_ones(&graph_handle, root_shape, root_dtype);
8984
8985 let mut upstream: HashMap<NodeId, NodeId> = HashMap::new();
8986 upstream.insert(root, ones_id);
8987
8988 for id in order {
8989 let up_id = match upstream.get(&id).copied() {
8990 Some(v) => v,
8991 None => continue, // unreachable from the root, no gradient to propagate
8992 };
8993 // Snapshot the op and its input IDs so we can drop the read
8994 // borrow before taking a mutable borrow to append new nodes.
8995 let (op, inputs) = {
8996 let g = graph_handle.read().unwrap();
8997 let node = g.node(id);
8998 (node.op.clone(), node.inputs.clone())
8999 };
9000
9001 // Symbolic-autograd dispatch (Phase 6d Track 2). If a
9002 // `GradientRule` is registered for this op, use it. Ops
9003 // that haven't migrated yet fall through to the legacy
9004 // inline `match` below.
9005 if let Some(grads) =
9006 crate::grad::dispatch_gradient(&graph_handle, &op, &inputs, id, up_id)
9007 {
9008 debug_assert_eq!(
9009 grads.len(),
9010 inputs.len(),
9011 "GradientRule for {:?} returned {} gradients but op has {} inputs",
9012 op.short_name(),
9013 grads.len(),
9014 inputs.len(),
9015 );
9016 for (input_id, grad) in inputs.iter().zip(grads.iter()) {
9017 if let Some(g) = grad {
9018 accumulate_grad(&mut upstream, *input_id, *g, &graph_handle);
9019 }
9020 }
9021 continue;
9022 }
9023
9024 match op {
9025 Op::Const => {
9026 // Leaf. The upstream value has already been stored and
9027 // is what `GradMap::get` will return for this input.
9028 }
9029 Op::Iota { .. } => {
9030 // Leaf, non-differentiable: a constant position
9031 // generator with no inputs — no gradient to propagate.
9032 }
9033 Op::NonZeroIndices { .. } => {
9034 // Produces discrete indices + a runtime count; both
9035 // are integer/non-differentiable. No gradient flows to
9036 // the input. (A differentiated graph that reaches this
9037 // op surfaces as a usage error in the grad-emitting
9038 // pass, matching the ArgMaxDim/ArgMinDim precedent.)
9039 }
9040 Op::Add => {
9041 // d(a + b)/da = 1, d(a + b)/db = 1.
9042 // Upstream flows unchanged into both inputs.
9043 accumulate_grad(&mut upstream, inputs[0], up_id, &graph_handle);
9044 accumulate_grad(&mut upstream, inputs[1], up_id, &graph_handle);
9045 }
9046 Op::Mul => {
9047 // d(a * b)/da = b, d(a * b)/db = a.
9048 // Upstream * b goes to a; upstream * a goes to b.
9049 let a = inputs[0];
9050 let b = inputs[1];
9051 let a_shape = node_shape(&graph_handle, a);
9052 let b_shape = node_shape(&graph_handle, b);
9053 let dtype = node_dtype(&graph_handle, a);
9054 let grad_a = push_node(&graph_handle, Op::Mul, vec![up_id, b], a_shape, dtype);
9055 let grad_b = push_node(&graph_handle, Op::Mul, vec![up_id, a], b_shape, dtype);
9056 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9057 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9058 }
9059 Op::MatMul => {
9060 // Forward: Y = A @ B, A: [m, k], B: [k, n], Y: [m, n]
9061 // Backward: dA = dY @ B^T, dB = A^T @ dY.
9062 let a = inputs[0];
9063 let b = inputs[1];
9064 let a_shape = node_shape(&graph_handle, a);
9065 let b_shape = node_shape(&graph_handle, b);
9066 let dtype = node_dtype(&graph_handle, a);
9067 // B^T: shape [n, k]
9068 let b_t_shape = transposed_shape(&b_shape);
9069 let b_t = push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
9070 // dA = upstream @ B^T, shape [m, k] = a_shape
9071 let grad_a = push_node(
9072 &graph_handle,
9073 Op::MatMul,
9074 vec![up_id, b_t],
9075 a_shape.clone(),
9076 dtype,
9077 );
9078 // A^T: shape [k, m]
9079 let a_t_shape = transposed_shape(&a_shape);
9080 let a_t = push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
9081 // dB = A^T @ upstream, shape [k, n] = b_shape
9082 let grad_b =
9083 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
9084 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9085 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9086 }
9087 Op::Transpose => {
9088 // d(x^T)/dx is a transpose on the way back.
9089 let x = inputs[0];
9090 let x_shape = node_shape(&graph_handle, x);
9091 let dtype = node_dtype(&graph_handle, x);
9092 let grad_x =
9093 push_node(&graph_handle, Op::Transpose, vec![up_id], x_shape, dtype);
9094 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9095 }
9096 Op::Permute(ref axes) => {
9097 // Backward: apply the inverse permutation to upstream.
9098 // If forward permutes with `axes` (out[i] = in[axes[i]]),
9099 // the inverse `inv` satisfies `inv[axes[i]] = i`.
9100 let x = inputs[0];
9101 let x_shape = node_shape(&graph_handle, x);
9102 let dtype = node_dtype(&graph_handle, x);
9103 let mut inv = vec![0_usize; axes.len()];
9104 for (i, &ax) in axes.iter().enumerate() {
9105 inv[ax] = i;
9106 }
9107 let grad_x =
9108 push_node(&graph_handle, Op::Permute(inv), vec![up_id], x_shape, dtype);
9109 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9110 }
9111 Op::Sqr => {
9112 // d(x^2)/dx = 2x. Expressed as `x + x` to avoid
9113 // needing a scalar constant broadcast — both sums
9114 // have the same shape as x, the existing Add op
9115 // handles them natively.
9116 let x = inputs[0];
9117 let x_shape = node_shape(&graph_handle, x);
9118 let dtype = node_dtype(&graph_handle, x);
9119 let two_x =
9120 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
9121 let grad_x =
9122 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
9123 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9124 }
9125 Op::Exp => {
9126 // d(e^x)/dx = e^x, which is the forward output — i.e.
9127 // this node `id`. Reuse it directly instead of
9128 // recomputing.
9129 let x = inputs[0];
9130 let out_shape = node_shape(&graph_handle, id);
9131 let dtype = node_dtype(&graph_handle, id);
9132 let grad_x =
9133 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
9134 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9135 }
9136 Op::Sub => {
9137 // d(a - b)/da = 1, d(a - b)/db = -1.
9138 let a = inputs[0];
9139 let b = inputs[1];
9140 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9141 let b_shape = node_shape(&graph_handle, b);
9142 let dtype = node_dtype(&graph_handle, b);
9143 let neg_up = push_node(&graph_handle, Op::Neg, vec![up_id], b_shape, dtype);
9144 accumulate_grad(&mut upstream, b, neg_up, &graph_handle);
9145 }
9146 Op::Div => {
9147 // y = a / b
9148 // dy/da = 1/b → grad_a = upstream / b
9149 // dy/db = -a/b² → grad_b = -(upstream * a / (b*b))
9150 let a = inputs[0];
9151 let b = inputs[1];
9152 let a_shape = node_shape(&graph_handle, a);
9153 let b_shape = node_shape(&graph_handle, b);
9154 let dtype = node_dtype(&graph_handle, a);
9155 // grad_a
9156 let grad_a = push_node(
9157 &graph_handle,
9158 Op::Div,
9159 vec![up_id, b],
9160 a_shape.clone(),
9161 dtype,
9162 );
9163 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9164 // grad_b: -(upstream * a / (b*b))
9165 let b_sq = push_node(&graph_handle, Op::Sqr, vec![b], b_shape.clone(), dtype);
9166 let up_times_a =
9167 push_node(&graph_handle, Op::Mul, vec![up_id, a], a_shape, dtype);
9168 let quotient = push_node(
9169 &graph_handle,
9170 Op::Div,
9171 vec![up_times_a, b_sq],
9172 b_shape.clone(),
9173 dtype,
9174 );
9175 let grad_b = push_node(&graph_handle, Op::Neg, vec![quotient], b_shape, dtype);
9176 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9177 }
9178 Op::Neg => {
9179 // d(-x)/dx = -1. grad_x = -upstream.
9180 let x = inputs[0];
9181 let x_shape = node_shape(&graph_handle, x);
9182 let dtype = node_dtype(&graph_handle, x);
9183 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
9184 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9185 }
9186 Op::Sqrt => {
9187 // y = sqrt(x), dy/dx = 1/(2*sqrt(x)) = 1/(2y).
9188 // grad_x = upstream / (y + y). Reuse the forward node.
9189 let x = inputs[0];
9190 let x_shape = node_shape(&graph_handle, x);
9191 let dtype = node_dtype(&graph_handle, x);
9192 let two_y =
9193 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
9194 let grad_x =
9195 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
9196 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9197 }
9198 Op::Log => {
9199 // d(ln(x))/dx = 1/x. grad_x = upstream / x.
9200 let x = inputs[0];
9201 let x_shape = node_shape(&graph_handle, x);
9202 let dtype = node_dtype(&graph_handle, x);
9203 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
9204 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9205 }
9206 Op::Sin => {
9207 // d(sin(x))/dx = cos(x). grad_x = upstream * cos(x).
9208 let x = inputs[0];
9209 let x_shape = node_shape(&graph_handle, x);
9210 let dtype = node_dtype(&graph_handle, x);
9211 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
9212 let grad_x =
9213 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
9214 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9215 }
9216 Op::Cos => {
9217 // d(cos(x))/dx = -sin(x). grad_x = -(upstream * sin(x)).
9218 let x = inputs[0];
9219 let x_shape = node_shape(&graph_handle, x);
9220 let dtype = node_dtype(&graph_handle, x);
9221 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
9222 let up_sin = push_node(
9223 &graph_handle,
9224 Op::Mul,
9225 vec![up_id, sin_x],
9226 x_shape.clone(),
9227 dtype,
9228 );
9229 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
9230 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9231 }
9232 Op::Tanh => {
9233 // y = tanh(x), dy/dx = 1 - y². grad_x = upstream * (1 - y*y).
9234 // Build: ones_of_y_shape - y*y, then multiply by upstream.
9235 let x = inputs[0];
9236 let y_shape = node_shape(&graph_handle, id);
9237 let dtype = node_dtype(&graph_handle, id);
9238 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
9239 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9240 let one_minus_sq = push_node(
9241 &graph_handle,
9242 Op::Sub,
9243 vec![ones, y_sq],
9244 y_shape.clone(),
9245 dtype,
9246 );
9247 let grad_x = push_node(
9248 &graph_handle,
9249 Op::Mul,
9250 vec![up_id, one_minus_sq],
9251 y_shape,
9252 dtype,
9253 );
9254 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9255 }
9256 Op::Sigmoid => {
9257 // y = sigmoid(x), dy/dx = y * (1 - y).
9258 // grad_x = upstream * y * (1 - y).
9259 let x = inputs[0];
9260 let y_shape = node_shape(&graph_handle, id);
9261 let dtype = node_dtype(&graph_handle, id);
9262 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9263 let one_minus_y = push_node(
9264 &graph_handle,
9265 Op::Sub,
9266 vec![ones, id],
9267 y_shape.clone(),
9268 dtype,
9269 );
9270 let y_times_1my = push_node(
9271 &graph_handle,
9272 Op::Mul,
9273 vec![id, one_minus_y],
9274 y_shape.clone(),
9275 dtype,
9276 );
9277 let grad_x = push_node(
9278 &graph_handle,
9279 Op::Mul,
9280 vec![up_id, y_times_1my],
9281 y_shape,
9282 dtype,
9283 );
9284 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9285 }
9286 Op::Silu => {
9287 // y = x * sigmoid(x)
9288 // dy/dx = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
9289 // = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
9290 //
9291 // Simpler: let s = sigmoid(x). dy/dx = s + y * (1 - s),
9292 // where y = x * s is the forward output (this node).
9293 // grad_x = upstream * (s + y * (1 - s)).
9294 let x = inputs[0];
9295 let x_shape = node_shape(&graph_handle, x);
9296 let dtype = node_dtype(&graph_handle, x);
9297 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
9298 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
9299 let one_minus_s = push_node(
9300 &graph_handle,
9301 Op::Sub,
9302 vec![ones, s],
9303 x_shape.clone(),
9304 dtype,
9305 );
9306 let y_times_1ms = push_node(
9307 &graph_handle,
9308 Op::Mul,
9309 vec![id, one_minus_s],
9310 x_shape.clone(),
9311 dtype,
9312 );
9313 let inner = push_node(
9314 &graph_handle,
9315 Op::Add,
9316 vec![s, y_times_1ms],
9317 x_shape.clone(),
9318 dtype,
9319 );
9320 let grad_x =
9321 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
9322 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9323 }
9324 Op::GeluTanh => {
9325 let x = inputs[0];
9326 let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
9327 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9328 }
9329 Op::Relu => {
9330 // d(relu(x))/dx = step(x). grad_x = upstream * step(x).
9331 let x = inputs[0];
9332 let x_shape = node_shape(&graph_handle, x);
9333 let dtype = node_dtype(&graph_handle, x);
9334 let step_x =
9335 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
9336 let grad_x =
9337 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
9338 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9339 }
9340 Op::Step => {
9341 // d(step(x))/dx is 0 almost everywhere (and a Dirac
9342 // delta at 0 which has no finite representation). The
9343 // standard move is to treat the derivative as 0 and
9344 // stop propagation — Step's backward is silently a
9345 // no-op. Callers that need a smooth surrogate should
9346 // use Sigmoid or Tanh instead.
9347 }
9348 Op::Recip => {
9349 // y = 1/x, dy/dx = -1/x² = -y².
9350 // grad_x = -upstream * y * y. Reuse forward output (id)
9351 // so we don't recompute the reciprocal.
9352 let x = inputs[0];
9353 let x_shape = node_shape(&graph_handle, x);
9354 let dtype = node_dtype(&graph_handle, x);
9355 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9356 let up_y_sq = push_node(
9357 &graph_handle,
9358 Op::Mul,
9359 vec![up_id, y_sq],
9360 x_shape.clone(),
9361 dtype,
9362 );
9363 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
9364 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9365 }
9366 Op::Abs => {
9367 // y = |x|, dy/dx = sign(x), with sign(0)=0 by
9368 // subgradient convention. Simplified to a direct
9369 // `Op::Sign` use after Op::Sign landed in PR B2;
9370 // the previous form synthesized `step(x) - step(-x)`
9371 // (5 backward nodes) but Sign expresses the same
9372 // function in 1 node, so the chain shrinks to
9373 // `Mul(upstream, Sign(x))` — 2 nodes total.
9374 let x = inputs[0];
9375 let x_shape = node_shape(&graph_handle, x);
9376 let dtype = node_dtype(&graph_handle, x);
9377 let sign_x =
9378 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
9379 let grad_x =
9380 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
9381 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9382 }
9383 Op::Where => {
9384 // Handled by `WhereRule` via `dispatch_gradient`;
9385 // this arm only exists for exhaustiveness.
9386 }
9387 Op::Floor | Op::Ceil | Op::Round | Op::Sign => {
9388 // d(floor(x))/dx, d(ceil(x))/dx, d(round(x))/dx,
9389 // d(sign(x))/dx are all 0 almost everywhere (with
9390 // a Dirac train at integer / half-integer / zero
9391 // that has no finite representation). Treat the
9392 // derivative as 0 and stop propagation — mirrors
9393 // `Op::Step`'s backward.
9394 }
9395 Op::Erf => {
9396 // y = erf(x). dy/dx = (2/√π) * exp(-x²).
9397 // grad_x = upstream * (2/√π) * exp(-x²).
9398 // Decomposes to: Sqr(x) → Neg → Exp → MulScalar(2/√π)
9399 // → Mul(upstream, .).
9400 // 2/√π = 1.1283791670955125738961589031...
9401 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
9402 let x = inputs[0];
9403 let x_shape = node_shape(&graph_handle, x);
9404 let dtype = node_dtype(&graph_handle, x);
9405 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9406 let neg_x_sq =
9407 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
9408 let exp_neg_x_sq = push_node(
9409 &graph_handle,
9410 Op::Exp,
9411 vec![neg_x_sq],
9412 x_shape.clone(),
9413 dtype,
9414 );
9415 let scaled = push_node(
9416 &graph_handle,
9417 Op::MulScalar(TWO_OVER_SQRT_PI),
9418 vec![exp_neg_x_sq],
9419 x_shape.clone(),
9420 dtype,
9421 );
9422 let grad_x =
9423 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9424 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9425 }
9426 Op::Flip { dim } => {
9427 // y = flip(x, dim). Backward is another Flip on
9428 // the same dim — Flip is its own inverse
9429 // (involutive). One backward node, exact gradient.
9430 let x = inputs[0];
9431 let x_shape = node_shape(&graph_handle, x);
9432 let dtype = node_dtype(&graph_handle, x);
9433 let grad_x =
9434 push_node(&graph_handle, Op::Flip { dim }, vec![up_id], x_shape, dtype);
9435 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9436 }
9437 Op::Pad {
9438 padding,
9439 mode,
9440 value: _,
9441 } => {
9442 // Backward delegates to Op::PadBackward — a single
9443 // node that handles all three modes uniformly via
9444 // its kernel. Constant: slice the unpadded region.
9445 // Reflect/Replicate: accumulate gradient at the
9446 // mirrored / replicated positions.
9447 let padding = padding.clone();
9448 let x = inputs[0];
9449 let x_shape = node_shape(&graph_handle, x);
9450 let dtype = node_dtype(&graph_handle, x);
9451 let grad_x = push_node(
9452 &graph_handle,
9453 Op::PadBackward {
9454 in_shape: x_shape.clone(),
9455 padding,
9456 mode,
9457 },
9458 vec![up_id],
9459 x_shape,
9460 dtype,
9461 );
9462 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9463 }
9464 Op::PadBackward { .. } => {
9465 // Backward helper — typically a leaf in autograd
9466 // (the upstream gradient itself never gets a
9467 // higher-order backward in v1). No-op arm for
9468 // exhaustiveness; if higher-order autograd needs
9469 // PadBackward's backward, that's its own scope.
9470 }
9471 Op::CumSum { dim } => {
9472 // y[..., i, ...] = sum_{k=0..=i} x[..., k, ...]
9473 // dL/dx[..., i, ...] = sum_{k=i..n} dL/dy[..., k, ...]
9474 // i.e. reverse cumsum. Express via Flip → CumSum → Flip.
9475 let x = inputs[0];
9476 let x_shape = node_shape(&graph_handle, x);
9477 let dtype = node_dtype(&graph_handle, x);
9478 let flip1 = push_node(
9479 &graph_handle,
9480 Op::Flip { dim },
9481 vec![up_id],
9482 x_shape.clone(),
9483 dtype,
9484 );
9485 let cs = push_node(
9486 &graph_handle,
9487 Op::CumSum { dim },
9488 vec![flip1],
9489 x_shape.clone(),
9490 dtype,
9491 );
9492 let grad_x =
9493 push_node(&graph_handle, Op::Flip { dim }, vec![cs], x_shape, dtype);
9494 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9495 }
9496 Op::Roll { dim, shift } => {
9497 // y = roll(x, dim, shift). Backward is the opposite
9498 // shift along the same dim. One backward node.
9499 let x = inputs[0];
9500 let x_shape = node_shape(&graph_handle, x);
9501 let dtype = node_dtype(&graph_handle, x);
9502 let grad_x = push_node(
9503 &graph_handle,
9504 Op::Roll { dim, shift: -shift },
9505 vec![up_id],
9506 x_shape,
9507 dtype,
9508 );
9509 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9510 }
9511 Op::Triu { diagonal } => {
9512 // y = triu(x, diagonal). Mask is a binary indicator
9513 // — gradient passes through kept positions and is
9514 // zero on the masked half. Same op on the upstream.
9515 let x = inputs[0];
9516 let x_shape = node_shape(&graph_handle, x);
9517 let dtype = node_dtype(&graph_handle, x);
9518 let grad_x = push_node(
9519 &graph_handle,
9520 Op::Triu { diagonal },
9521 vec![up_id],
9522 x_shape,
9523 dtype,
9524 );
9525 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9526 }
9527 Op::Tril { diagonal } => {
9528 // Mirror of Op::Triu — same mask gradient.
9529 let x = inputs[0];
9530 let x_shape = node_shape(&graph_handle, x);
9531 let dtype = node_dtype(&graph_handle, x);
9532 let grad_x = push_node(
9533 &graph_handle,
9534 Op::Tril { diagonal },
9535 vec![up_id],
9536 x_shape,
9537 dtype,
9538 );
9539 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9540 }
9541 Op::LogSoftmaxLastDim => {
9542 // grad_x = upstream - exp(y) * sum(upstream, last_dim, keepdim).
9543 // Folded into Op::LogSoftmaxLastDimBackward — takes
9544 // (forward_output, upstream), avoids re-evaluating
9545 // the softmax outside the kernel.
9546 let x = inputs[0];
9547 let x_shape = node_shape(&graph_handle, x);
9548 let dtype = node_dtype(&graph_handle, x);
9549 let grad_x = push_node(
9550 &graph_handle,
9551 Op::LogSoftmaxLastDimBackward,
9552 vec![id, up_id],
9553 x_shape,
9554 dtype,
9555 );
9556 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9557 }
9558 Op::LogSoftmaxLastDimBackward => {
9559 // Backward helper — no higher-order autograd in v1.
9560 }
9561 Op::MaskedFill { value: _ } => {
9562 // y = mask ? value : x. dy/dx = (mask == 0).
9563 // grad_x = MaskedFill(upstream, mask, value=0_of_dtype).
9564 // The mask is integer-only; no gradient flows to it.
9565 let x = inputs[0];
9566 let mask = inputs[1];
9567 let x_shape = node_shape(&graph_handle, x);
9568 let dtype = node_dtype(&graph_handle, x);
9569 let zero = match fuel_ir::Scalar::zero(dtype) {
9570 Ok(z) => z,
9571 Err(_) => {
9572 // A packed/scale dtype has no zero scalar. MaskedFill
9573 // on such a dtype is a build-time bug (a future D5
9574 // graph-build guard forbids it), so this is
9575 // unreachable in a well-formed graph. debug_assert
9576 // catches it in debug; release skips this gradient
9577 // rather than panicking (never-panic invariant).
9578 debug_assert!(false, "MaskedFill backward on non-real dtype {dtype:?}");
9579 continue;
9580 }
9581 };
9582 let grad_x = push_node(
9583 &graph_handle,
9584 Op::MaskedFill { value: zero },
9585 vec![up_id, mask],
9586 x_shape,
9587 dtype,
9588 );
9589 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9590 // No gradient to mask: it's discrete.
9591 }
9592 Op::Rem => {
9593 // y = a - floor(a/b) * b (PyTorch convention).
9594 // d/da = 1 (the floor term is treated as a constant
9595 // w.r.t. a almost everywhere; the actual
9596 // derivative has a Dirac component at
9597 // integer a/b ratios that we drop, matching
9598 // PyTorch's autograd convention).
9599 // d/db = -floor(a/b)
9600 // grad_a = upstream
9601 // grad_b = upstream * (-floor(a/b))
9602 let a = inputs[0];
9603 let b = inputs[1];
9604 let a_shape = node_shape(&graph_handle, a);
9605 let dtype = node_dtype(&graph_handle, a);
9606 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9607 let div_ab =
9608 push_node(&graph_handle, Op::Div, vec![a, b], a_shape.clone(), dtype);
9609 let floor_div = push_node(
9610 &graph_handle,
9611 Op::Floor,
9612 vec![div_ab],
9613 a_shape.clone(),
9614 dtype,
9615 );
9616 let neg_floor = push_node(
9617 &graph_handle,
9618 Op::Neg,
9619 vec![floor_div],
9620 a_shape.clone(),
9621 dtype,
9622 );
9623 let grad_b = push_node(
9624 &graph_handle,
9625 Op::Mul,
9626 vec![up_id, neg_floor],
9627 a_shape,
9628 dtype,
9629 );
9630 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9631 }
9632 Op::Rsqrt => {
9633 // y = x^(-1/2). dy/dx = -0.5 * x^(-3/2).
9634 // Identity: y² = 1/x, so x^(-3/2) = y/x = y * y² = y³.
9635 // grad_x = -0.5 * upstream * y³.
9636 // Reuses the forward output id for y; never touches
9637 // x directly (avoids the divide-by-zero singularity
9638 // that the obvious `-0.5 * upstream * y / x` form
9639 // would have).
9640 let x = inputs[0];
9641 let x_shape = node_shape(&graph_handle, x);
9642 let dtype = node_dtype(&graph_handle, x);
9643 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9644 let y_cu = push_node(
9645 &graph_handle,
9646 Op::Mul,
9647 vec![id, y_sq],
9648 x_shape.clone(),
9649 dtype,
9650 );
9651 let scaled = push_node(
9652 &graph_handle,
9653 Op::MulScalar(-0.5),
9654 vec![y_cu],
9655 x_shape.clone(),
9656 dtype,
9657 );
9658 let grad_x =
9659 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9660 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9661 }
9662 Op::Pow => {
9663 // y = pow(a, b).
9664 // d/da = b * pow(a, b-1)
9665 // d/db = y * ln(a)
9666 // grad_a = upstream * b * pow(a, b-1)
9667 // grad_b = upstream * y * ln(a)
9668 // The forward output `id` IS y; we reuse it.
9669 let a = inputs[0];
9670 let b = inputs[1];
9671 let a_shape = node_shape(&graph_handle, a);
9672 let dtype = node_dtype(&graph_handle, a);
9673 // d/da branch: pow(a, b - 1)
9674 let b_minus_one = push_node(
9675 &graph_handle,
9676 Op::AddScalar(-1.0),
9677 vec![b],
9678 a_shape.clone(),
9679 dtype,
9680 );
9681 let pow_a_bm1 = push_node(
9682 &graph_handle,
9683 Op::Pow,
9684 vec![a, b_minus_one],
9685 a_shape.clone(),
9686 dtype,
9687 );
9688 let b_times_pow = push_node(
9689 &graph_handle,
9690 Op::Mul,
9691 vec![b, pow_a_bm1],
9692 a_shape.clone(),
9693 dtype,
9694 );
9695 let grad_a = push_node(
9696 &graph_handle,
9697 Op::Mul,
9698 vec![up_id, b_times_pow],
9699 a_shape.clone(),
9700 dtype,
9701 );
9702 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9703 // d/db branch: y * ln(a)
9704 let log_a = push_node(&graph_handle, Op::Log, vec![a], a_shape.clone(), dtype);
9705 let y_log_a = push_node(
9706 &graph_handle,
9707 Op::Mul,
9708 vec![id, log_a],
9709 a_shape.clone(),
9710 dtype,
9711 );
9712 let grad_b =
9713 push_node(&graph_handle, Op::Mul, vec![up_id, y_log_a], a_shape, dtype);
9714 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9715 }
9716 Op::Gelu => {
9717 // y = 0.5 * x * (1 + erf(x/√2)).
9718 // dy/dx = Φ(x) + x · φ(x)
9719 // = 0.5 * (1 + erf(x/√2))
9720 // + x * (1/√(2π)) * exp(-x²/2)
9721 // where Φ is the standard-normal CDF (= y/x for x≠0;
9722 // we recompute it explicitly so the backward stays
9723 // safe at x=0) and φ is the PDF.
9724 //
9725 // Chain (12 nodes):
9726 // x_over_sqrt2 = MulScalar(1/√2)(x)
9727 // erf_arg = Erf(x_over_sqrt2)
9728 // plus_one = AddScalar(1.0)(erf_arg)
9729 // cdf_term = MulScalar(0.5)(plus_one)
9730 // x_sq = Sqr(x)
9731 // half_x_sq = MulScalar(0.5)(x_sq)
9732 // neg_half_x_sq= Neg(half_x_sq)
9733 // exp_term = Exp(neg_half_x_sq)
9734 // phi = MulScalar(1/√(2π))(exp_term)
9735 // pdf_term = Mul(x, phi)
9736 // d_gelu = Add(cdf_term, pdf_term)
9737 // grad_x = Mul(upstream, d_gelu)
9738 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
9739 // 1/√(2π) = 0.39894228040143267793994605993...
9740 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
9741 let x = inputs[0];
9742 let x_shape = node_shape(&graph_handle, x);
9743 let dtype = node_dtype(&graph_handle, x);
9744 // CDF half: 0.5 * (1 + erf(x/√2)).
9745 let x_over_sqrt2 = push_node(
9746 &graph_handle,
9747 Op::MulScalar(INV_SQRT_2),
9748 vec![x],
9749 x_shape.clone(),
9750 dtype,
9751 );
9752 let erf_arg = push_node(
9753 &graph_handle,
9754 Op::Erf,
9755 vec![x_over_sqrt2],
9756 x_shape.clone(),
9757 dtype,
9758 );
9759 let plus_one = push_node(
9760 &graph_handle,
9761 Op::AddScalar(1.0),
9762 vec![erf_arg],
9763 x_shape.clone(),
9764 dtype,
9765 );
9766 let cdf_term = push_node(
9767 &graph_handle,
9768 Op::MulScalar(0.5),
9769 vec![plus_one],
9770 x_shape.clone(),
9771 dtype,
9772 );
9773 // PDF half: x * (1/√(2π)) * exp(-x²/2).
9774 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9775 let half_x_sq = push_node(
9776 &graph_handle,
9777 Op::MulScalar(0.5),
9778 vec![x_sq],
9779 x_shape.clone(),
9780 dtype,
9781 );
9782 let neg_half_x_sq = push_node(
9783 &graph_handle,
9784 Op::Neg,
9785 vec![half_x_sq],
9786 x_shape.clone(),
9787 dtype,
9788 );
9789 let exp_term = push_node(
9790 &graph_handle,
9791 Op::Exp,
9792 vec![neg_half_x_sq],
9793 x_shape.clone(),
9794 dtype,
9795 );
9796 let phi = push_node(
9797 &graph_handle,
9798 Op::MulScalar(INV_SQRT_2PI),
9799 vec![exp_term],
9800 x_shape.clone(),
9801 dtype,
9802 );
9803 let pdf_term =
9804 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
9805 // Sum the two halves and apply upstream.
9806 let d_gelu = push_node(
9807 &graph_handle,
9808 Op::Add,
9809 vec![cdf_term, pdf_term],
9810 x_shape.clone(),
9811 dtype,
9812 );
9813 let grad_x =
9814 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
9815 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9816 }
9817 Op::Equal | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => {
9818 // Comparison family: handled by `NoGradientBinaryRule`
9819 // via `dispatch_gradient`. The `if let Some(grads) =
9820 // dispatch_gradient(...) { continue; }` block above
9821 // intercepts before we get here. This arm exists only
9822 // for exhaustiveness; it should be unreachable in
9823 // practice. Keeping it as a no-op rather than
9824 // `unreachable!()` defends against a future hand-edit
9825 // that removes the dispatcher arm by mistake — the
9826 // graph still terminates traversal cleanly.
9827 }
9828 Op::Cast(_) => {
9829 // Forward: y = cast(x, target_dtype).
9830 // Backward: dL/dx = cast(upstream, source_dtype).
9831 let x = inputs[0];
9832 let x_dtype = node_dtype(&graph_handle, x);
9833 let x_shape = node_shape(&graph_handle, x);
9834 let grad_x = push_node(
9835 &graph_handle,
9836 Op::Cast(x_dtype),
9837 vec![up_id],
9838 x_shape,
9839 x_dtype,
9840 );
9841 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9842 }
9843 Op::SumAll => {
9844 // Forward: y = sum(x), scalar.
9845 // Backward: dL/dx = broadcast_to(upstream, x.shape).
9846 let x = inputs[0];
9847 let x_shape = node_shape(&graph_handle, x);
9848 let dtype = node_dtype(&graph_handle, x);
9849 let grad_x = push_node(
9850 &graph_handle,
9851 Op::BroadcastTo(x_shape.clone()),
9852 vec![up_id],
9853 x_shape,
9854 dtype,
9855 );
9856 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9857 }
9858 Op::MeanAll => {
9859 // Forward: y = mean(x) = sum(x) / n, scalar.
9860 // Backward: dL/dx = broadcast_to(upstream / n, x.shape).
9861 // We build `ones / n` as a constant of shape x.shape
9862 // and multiply by broadcast_to(upstream, x.shape).
9863 // Simpler: broadcast upstream, then divide by an n-const.
9864 let x = inputs[0];
9865 let x_shape = node_shape(&graph_handle, x);
9866 let dtype = node_dtype(&graph_handle, x);
9867 let n_elem = x_shape.elem_count();
9868 let broadcast_up = push_node(
9869 &graph_handle,
9870 Op::BroadcastTo(x_shape.clone()),
9871 vec![up_id],
9872 x_shape.clone(),
9873 dtype,
9874 );
9875 let n_const =
9876 build_filled_const(&graph_handle, x_shape.clone(), dtype, n_elem as f64);
9877 let grad_x = push_node(
9878 &graph_handle,
9879 Op::Div,
9880 vec![broadcast_up, n_const],
9881 x_shape,
9882 dtype,
9883 );
9884 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9885 }
9886 Op::BroadcastTo(_) => {
9887 // Forward: y = broadcast_to(x, target).
9888 // Backward: dL/dx = reduce_sum_to(upstream, x.shape) —
9889 // sum away every dim that was expanded or newly added.
9890 let x = inputs[0];
9891 let x_shape = node_shape(&graph_handle, x);
9892 let dtype = node_dtype(&graph_handle, x);
9893 let grad_x = push_node(
9894 &graph_handle,
9895 Op::ReduceSumTo(x_shape.clone()),
9896 vec![up_id],
9897 x_shape,
9898 dtype,
9899 );
9900 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9901 }
9902 Op::Reshape(_) => {
9903 // Forward: y = reshape(x, target). Data unchanged.
9904 // Backward: reshape upstream back to x.shape.
9905 let x = inputs[0];
9906 let x_shape = node_shape(&graph_handle, x);
9907 let dtype = node_dtype(&graph_handle, x);
9908 let grad_x = push_node(
9909 &graph_handle,
9910 Op::Reshape(x_shape.clone()),
9911 vec![up_id],
9912 x_shape,
9913 dtype,
9914 );
9915 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9916 }
9917 Op::Contiguize => {
9918 // Forward: y = contiguize(x). Identity at the
9919 // value level; only the layout differs. Backward:
9920 // pass upstream through unchanged. The
9921 // downstream `accumulate_grad` will sum this
9922 // into x's gradient regardless of x's own layout.
9923 let x = inputs[0];
9924 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
9925 }
9926 Op::Unsqueeze { dim: _ } => {
9927 // Forward: y = unsqueeze(x, dim) — inserts a size-1
9928 // axis without touching bytes. Backward: drop that
9929 // axis. Bytes are unchanged either direction; a
9930 // Reshape to x.shape is the simplest expression of
9931 // "same bytes, different rank" that the executor
9932 // handles natively.
9933 let x = inputs[0];
9934 let x_shape = node_shape(&graph_handle, x);
9935 let dtype = node_dtype(&graph_handle, x);
9936 let grad_x = push_node(
9937 &graph_handle,
9938 Op::Reshape(x_shape.clone()),
9939 vec![up_id],
9940 x_shape,
9941 dtype,
9942 );
9943 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9944 }
9945 Op::Squeeze { dim } => {
9946 // Forward: y = squeeze(x, dim) — drops a size-1 axis,
9947 // metadata-only. Backward: re-insert the axis at the
9948 // same position via Unsqueeze. Both directions are
9949 // metadata-only views (no bytes touched).
9950 let x = inputs[0];
9951 let x_shape = node_shape(&graph_handle, x);
9952 let dtype = node_dtype(&graph_handle, x);
9953 let grad_x = push_node(
9954 &graph_handle,
9955 Op::Unsqueeze { dim },
9956 vec![up_id],
9957 x_shape,
9958 dtype,
9959 );
9960 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9961 }
9962 Op::ReduceSumTo(_) => {
9963 // Forward: y = reduce_sum_to(x, target).
9964 // Backward: broadcast upstream back to x.shape.
9965 let x = inputs[0];
9966 let x_shape = node_shape(&graph_handle, x);
9967 let dtype = node_dtype(&graph_handle, x);
9968 let grad_x = push_node(
9969 &graph_handle,
9970 Op::BroadcastTo(x_shape.clone()),
9971 vec![up_id],
9972 x_shape,
9973 dtype,
9974 );
9975 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9976 }
9977 Op::MaxAll | Op::MinAll => {
9978 // For y = max(x) (or min), the gradient is an
9979 // indicator at the argmax positions, distributed
9980 // across ties. Expressed without a dedicated argmax
9981 // op using the Step trick:
9982 //
9983 // broadcasted_y = broadcast_to(y, x.shape)
9984 // diff = broadcasted_y - x (for Max)
9985 // | x - broadcasted_y (for Min)
9986 // indicator = ones - step(diff)
9987 // grad_x = broadcast_to(upstream, x.shape) * indicator
9988 //
9989 // At argmax positions `diff == 0`, `step(0) == 0`, so
9990 // the indicator is 1. Elsewhere `diff > 0` so step is
9991 // 1 and the indicator is 0. Ties share the gradient.
9992 let x = inputs[0];
9993 let x_shape = node_shape(&graph_handle, x);
9994 let dtype = node_dtype(&graph_handle, x);
9995 let is_max = matches!(op, Op::MaxAll);
9996 let broadcasted_y = push_node(
9997 &graph_handle,
9998 Op::BroadcastTo(x_shape.clone()),
9999 vec![id],
10000 x_shape.clone(),
10001 dtype,
10002 );
10003 let diff = if is_max {
10004 push_node(
10005 &graph_handle,
10006 Op::Sub,
10007 vec![broadcasted_y, x],
10008 x_shape.clone(),
10009 dtype,
10010 )
10011 } else {
10012 push_node(
10013 &graph_handle,
10014 Op::Sub,
10015 vec![x, broadcasted_y],
10016 x_shape.clone(),
10017 dtype,
10018 )
10019 };
10020 let step_diff =
10021 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10022 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10023 let indicator = push_node(
10024 &graph_handle,
10025 Op::Sub,
10026 vec![ones, step_diff],
10027 x_shape.clone(),
10028 dtype,
10029 );
10030 let broadcast_up = push_node(
10031 &graph_handle,
10032 Op::BroadcastTo(x_shape.clone()),
10033 vec![up_id],
10034 x_shape.clone(),
10035 dtype,
10036 );
10037 let grad_x = push_node(
10038 &graph_handle,
10039 Op::Mul,
10040 vec![broadcast_up, indicator],
10041 x_shape,
10042 dtype,
10043 );
10044 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10045 }
10046 Op::SumDim(dim) => {
10047 // Insert a size-1 at `dim` via reshape, then broadcast
10048 // back to x.shape.
10049 let x = inputs[0];
10050 let x_shape = node_shape(&graph_handle, x);
10051 let dtype = node_dtype(&graph_handle, x);
10052 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10053 let reshaped = push_node(
10054 &graph_handle,
10055 Op::Reshape(keepdim_shape.clone()),
10056 vec![up_id],
10057 keepdim_shape,
10058 dtype,
10059 );
10060 let grad_x = push_node(
10061 &graph_handle,
10062 Op::BroadcastTo(x_shape.clone()),
10063 vec![reshaped],
10064 x_shape,
10065 dtype,
10066 );
10067 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10068 }
10069 Op::MeanDim(dim) => {
10070 // SumDim-style backward, then divide by the reduced dim size.
10071 let x = inputs[0];
10072 let x_shape = node_shape(&graph_handle, x);
10073 let dtype = node_dtype(&graph_handle, x);
10074 let reduced_size = x_shape.dims()[dim];
10075 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10076 let reshaped = push_node(
10077 &graph_handle,
10078 Op::Reshape(keepdim_shape.clone()),
10079 vec![up_id],
10080 keepdim_shape,
10081 dtype,
10082 );
10083 let broadcast = push_node(
10084 &graph_handle,
10085 Op::BroadcastTo(x_shape.clone()),
10086 vec![reshaped],
10087 x_shape.clone(),
10088 dtype,
10089 );
10090 let n_const = build_filled_const(
10091 &graph_handle,
10092 x_shape.clone(),
10093 dtype,
10094 reduced_size as f64,
10095 );
10096 let grad_x = push_node(
10097 &graph_handle,
10098 Op::Div,
10099 vec![broadcast, n_const],
10100 x_shape,
10101 dtype,
10102 );
10103 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10104 }
10105 Op::MaxDim(dim) | Op::MinDim(dim) => {
10106 // Same indicator trick as MaxAll/MinAll, but apply the
10107 // "reshape to keepdim then broadcast" pattern to both
10108 // the forward output and upstream before multiplying.
10109 let x = inputs[0];
10110 let x_shape = node_shape(&graph_handle, x);
10111 let dtype = node_dtype(&graph_handle, x);
10112 let is_max = matches!(op, Op::MaxDim(_));
10113 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10114 let y_keepdim = push_node(
10115 &graph_handle,
10116 Op::Reshape(keepdim_shape.clone()),
10117 vec![id],
10118 keepdim_shape.clone(),
10119 dtype,
10120 );
10121 let broadcasted_y = push_node(
10122 &graph_handle,
10123 Op::BroadcastTo(x_shape.clone()),
10124 vec![y_keepdim],
10125 x_shape.clone(),
10126 dtype,
10127 );
10128 let diff = if is_max {
10129 push_node(
10130 &graph_handle,
10131 Op::Sub,
10132 vec![broadcasted_y, x],
10133 x_shape.clone(),
10134 dtype,
10135 )
10136 } else {
10137 push_node(
10138 &graph_handle,
10139 Op::Sub,
10140 vec![x, broadcasted_y],
10141 x_shape.clone(),
10142 dtype,
10143 )
10144 };
10145 let step_diff =
10146 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10147 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10148 let indicator = push_node(
10149 &graph_handle,
10150 Op::Sub,
10151 vec![ones, step_diff],
10152 x_shape.clone(),
10153 dtype,
10154 );
10155 let up_keepdim = push_node(
10156 &graph_handle,
10157 Op::Reshape(keepdim_shape.clone()),
10158 vec![up_id],
10159 keepdim_shape,
10160 dtype,
10161 );
10162 let broadcast_up = push_node(
10163 &graph_handle,
10164 Op::BroadcastTo(x_shape.clone()),
10165 vec![up_keepdim],
10166 x_shape.clone(),
10167 dtype,
10168 );
10169 let grad_x = push_node(
10170 &graph_handle,
10171 Op::Mul,
10172 vec![broadcast_up, indicator],
10173 x_shape,
10174 dtype,
10175 );
10176 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10177 }
10178 // Phase 7.6 step 5 (2026-05-11): the legacy
10179 // `Op::SoftmaxLastDim` / `Op::LayerNormLastDim` /
10180 // `Op::RmsNormLastDim` / `Op::Rope` /
10181 // `Op::Conv2D` / `Op::FusedLinear` arms have been
10182 // dropped together with the variants themselves; the
10183 // `Op::Fused(fid, _)` arm below dispatches per id and
10184 // is the single source of truth for migrated forward
10185 // ops' backward.
10186 Op::ArgMaxDim(_) | Op::ArgMinDim(_) => {
10187 // Argmax/argmin produce integer indices, which are
10188 // non-differentiable. Panic rather than silently
10189 // zero-propagating — if the user has one of these in
10190 // their differentiated graph, they've almost
10191 // certainly made a mistake.
10192 panic!(
10193 "backward: ArgMaxDim/ArgMinDim produce integer \
10194 indices and cannot be differentiated through. \
10195 Use MaxDim/MinDim if you want a differentiable \
10196 selection."
10197 );
10198 }
10199 Op::ReduceMaxTo(_) => {
10200 // Forward: y = reduce_max_to(x, target).
10201 // Backward: route upstream to position(s) where
10202 // x equals its per-window max via the fused
10203 // backward helper Op::Fused(REDUCE_MAX_TO_BACKWARD,
10204 // _) (takes (x, upstream) and emits grad_x of
10205 // x.shape). Tied maxes share the gradient equally
10206 // (fair-share subgradient). Note this is the
10207 // backward of a *primitive* (Op::ReduceMaxTo),
10208 // not a fused forward — no BackwardKind::Fused
10209 // edge in the registry drives this; the explicit
10210 // emission is the source of truth.
10211 let x = inputs[0];
10212 let x_shape = node_shape(&graph_handle, x);
10213 let dtype = node_dtype(&graph_handle, x);
10214 let grad_x = push_node(
10215 &graph_handle,
10216 Op::Fused(
10217 crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD,
10218 crate::registry::FusedOpParams::ReduceMaxToBackward,
10219 ),
10220 vec![x, up_id],
10221 x_shape,
10222 dtype,
10223 );
10224 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10225 }
10226 // Phase 7.6 step 5 (final, 2026-05-11): legacy
10227 // `Op::QMatMul` arm dropped with the variant; QMatMul
10228 // backward panics via the Op::Fused arm below.
10229 // Phase 7.6 step 5 (2026-05-11): the legacy
10230 // `Op::SoftmaxLastDimBackward | Op::LayerNormLastDimBackward |
10231 // Op::RmsNormLastDimBackward | Op::ReduceMaxToBackward`
10232 // higher-order panic arm has been dropped together
10233 // with the variants themselves. The Op::Fused arm
10234 // below panics for those four ids.
10235 Op::IndexSelect { dim } => {
10236 // Forward: out = index_select(data, dim, indices).
10237 // Backward: grad_data = index_add(zeros_like(data), dim, indices, upstream).
10238 let data = inputs[0];
10239 let idx = inputs[1];
10240 let data_shape = node_shape(&graph_handle, data);
10241 let dtype = node_dtype(&graph_handle, data);
10242 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10243 let grad_data = push_node(
10244 &graph_handle,
10245 Op::IndexAdd { dim },
10246 vec![zeros, idx, up_id],
10247 data_shape,
10248 dtype,
10249 );
10250 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10251 // Index tensor is itself non-differentiable (integer dtype).
10252 }
10253 Op::Gather { dim } => {
10254 // Forward: out = gather(data, dim, indices).
10255 // Backward: grad_data = scatter_add(zeros_like(data), dim, indices, upstream).
10256 let data = inputs[0];
10257 let idx = inputs[1];
10258 let data_shape = node_shape(&graph_handle, data);
10259 let dtype = node_dtype(&graph_handle, data);
10260 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10261 let grad_data = push_node(
10262 &graph_handle,
10263 Op::ScatterAdd { dim },
10264 vec![zeros, idx, up_id],
10265 data_shape,
10266 dtype,
10267 );
10268 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10269 }
10270 Op::IndexAdd { dim } => {
10271 // Forward: out = index_add(base, dim, indices, src).
10272 // Backward:
10273 // grad_base = upstream (pass-through — base flows
10274 // through the non-indexed positions and
10275 // the accumulated positions don't zero
10276 // it out, they add to it)
10277 // grad_src = index_select(upstream, dim, indices)
10278 // (the pieces of upstream that came from
10279 // src in the forward).
10280 let base = inputs[0];
10281 let idx = inputs[1];
10282 let src = inputs[2];
10283 let src_shape = node_shape(&graph_handle, src);
10284 let dtype = node_dtype(&graph_handle, src);
10285 // grad_base: upstream passes through.
10286 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10287 // grad_src: select from upstream at the indices.
10288 let grad_src = push_node(
10289 &graph_handle,
10290 Op::IndexSelect { dim },
10291 vec![up_id, idx],
10292 src_shape,
10293 dtype,
10294 );
10295 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10296 }
10297 Op::Concat { dim } => {
10298 // Forward: out = concat(inputs.., dim).
10299 // Backward: split upstream along `dim` into one slice per
10300 // input at the cumulative offset, routing each slice to its
10301 // input. N-ary (unroll_scan stacks N per-step ys into a
10302 // single Concat; the SSM/Hopfield BPTT unroll relies on
10303 // this). Duplicate inputs accumulate via accumulate_grad.
10304 let mut start = 0usize;
10305 for &inp in &inputs {
10306 let in_shape = node_shape(&graph_handle, inp);
10307 let dtype = node_dtype(&graph_handle, inp);
10308 let len = in_shape.dims()[dim];
10309 let grad_in = push_node(
10310 &graph_handle,
10311 Op::Slice { dim, start, len },
10312 vec![up_id],
10313 in_shape,
10314 dtype,
10315 );
10316 accumulate_grad(&mut upstream, inp, grad_in, &graph_handle);
10317 start += len;
10318 }
10319 }
10320 Op::Slice { dim, start, len: _ } => {
10321 // Forward: out = slice(x, dim, start, len).
10322 // Backward: build a zeros tensor of x.shape, then
10323 // scatter the upstream into the slice range. We use
10324 // a concat of three pieces: left zeros, upstream,
10325 // right zeros (along `dim`).
10326 let x = inputs[0];
10327 let x_shape = node_shape(&graph_handle, x);
10328 let dtype = node_dtype(&graph_handle, x);
10329 let x_dims = x_shape.dims();
10330 let dim_size = x_dims[dim];
10331 let up_len = x_dims[dim].min(node_shape(&graph_handle, up_id).dims()[dim]);
10332 let left_len = start;
10333 let right_len = dim_size - start - up_len;
10334 // Build left zero pad if needed.
10335 let mut pieces: Vec<NodeId> = Vec::new();
10336 if left_len > 0 {
10337 let mut left_dims: Vec<usize> = x_dims.to_vec();
10338 left_dims[dim] = left_len;
10339 let left_shape = Shape::from_dims(&left_dims);
10340 pieces.push(build_filled_const(&graph_handle, left_shape, dtype, 0.0));
10341 }
10342 pieces.push(up_id);
10343 if right_len > 0 {
10344 let mut right_dims: Vec<usize> = x_dims.to_vec();
10345 right_dims[dim] = right_len;
10346 let right_shape = Shape::from_dims(&right_dims);
10347 pieces.push(build_filled_const(&graph_handle, right_shape, dtype, 0.0));
10348 }
10349 // Fold concat-left-to-right.
10350 let mut current = pieces[0];
10351 let mut current_dims: Vec<usize> = {
10352 let n = graph_handle.read().unwrap();
10353 n.node(current).shape.dims().to_vec()
10354 };
10355 for &next in &pieces[1..] {
10356 let next_dims: Vec<usize> = {
10357 let n = graph_handle.read().unwrap();
10358 n.node(next).shape.dims().to_vec()
10359 };
10360 let mut combined = current_dims.clone();
10361 combined[dim] = current_dims[dim] + next_dims[dim];
10362 let combined_shape = Shape::from_dims(&combined);
10363 current = push_node(
10364 &graph_handle,
10365 Op::Concat { dim },
10366 vec![current, next],
10367 combined_shape,
10368 dtype,
10369 );
10370 current_dims = combined;
10371 }
10372 accumulate_grad(&mut upstream, x, current, &graph_handle);
10373 }
10374 Op::AddScalar(_) => {
10375 // y = x + c, dy/dx = 1. Upstream passes through.
10376 let x = inputs[0];
10377 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10378 }
10379 Op::MulScalar(c) => {
10380 // y = x * c, dy/dx = c. Multiply upstream by c via
10381 // another MulScalar node.
10382 let x = inputs[0];
10383 let x_shape = node_shape(&graph_handle, x);
10384 let dtype = node_dtype(&graph_handle, x);
10385 let grad_x =
10386 push_node(&graph_handle, Op::MulScalar(c), vec![up_id], x_shape, dtype);
10387 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10388 }
10389 Op::PowI(n) => {
10390 // y = x^n, dy/dx = n * x^(n-1).
10391 // grad_x = upstream * n * x^(n-1). Emitted as a
10392 // single fused PowIBackward node; the executor
10393 // routes it to baracuda's `unary_powi_backward_*`
10394 // kernel (alpha.31) on CUDA, or falls back to the
10395 // primitive decomposition (PowI(n-1) → MulScalar →
10396 // Mul) on backends that haven't registered the
10397 // fused kernel.
10398 let x = inputs[0];
10399 let x_shape = node_shape(&graph_handle, x);
10400 let dtype = node_dtype(&graph_handle, x);
10401 let grad_x = push_node(
10402 &graph_handle,
10403 Op::Fused(
10404 crate::registry::FusedOps::POWI_BACKWARD,
10405 crate::registry::FusedOpParams::PowIBackward { exp: n },
10406 ),
10407 vec![x, up_id],
10408 x_shape,
10409 dtype,
10410 );
10411 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10412 }
10413 Op::Clamp { min, max } => {
10414 // Subgradient: 1 where min <= x <= max, 0 elsewhere.
10415 // Expressed via (step(x - min) - step(x - max))
10416 // which is 1 in the interior (x > min and x <= max...
10417 // actually step(0) = 0, so the right end is a bit
10418 // tricky). For a reference implementation the
10419 // simplest approach is a dedicated "clamp backward"
10420 // indicator. We build it out of the existing ops:
10421 //
10422 // lower_ok = step(x - min) // 1 where x > min
10423 // upper_ok = step(max - x) // 1 where x < max
10424 // indicator = lower_ok * upper_ok
10425 // grad_x = upstream * indicator
10426 //
10427 // This underestimates the gradient on the exact
10428 // boundary by a measure-zero amount — standard.
10429 let x = inputs[0];
10430 let x_shape = node_shape(&graph_handle, x);
10431 let dtype = node_dtype(&graph_handle, x);
10432 let min_shifted = push_node(
10433 &graph_handle,
10434 Op::AddScalar(-min),
10435 vec![x],
10436 x_shape.clone(),
10437 dtype,
10438 );
10439 let lower_ok = push_node(
10440 &graph_handle,
10441 Op::Step,
10442 vec![min_shifted],
10443 x_shape.clone(),
10444 dtype,
10445 );
10446 let max_minus_x = push_node(
10447 &graph_handle,
10448 Op::MulScalar(-1.0),
10449 vec![x],
10450 x_shape.clone(),
10451 dtype,
10452 );
10453 let max_minus_x = push_node(
10454 &graph_handle,
10455 Op::AddScalar(max),
10456 vec![max_minus_x],
10457 x_shape.clone(),
10458 dtype,
10459 );
10460 let upper_ok = push_node(
10461 &graph_handle,
10462 Op::Step,
10463 vec![max_minus_x],
10464 x_shape.clone(),
10465 dtype,
10466 );
10467 let indicator = push_node(
10468 &graph_handle,
10469 Op::Mul,
10470 vec![lower_ok, upper_ok],
10471 x_shape.clone(),
10472 dtype,
10473 );
10474 let grad_x = push_node(
10475 &graph_handle,
10476 Op::Mul,
10477 vec![up_id, indicator],
10478 x_shape,
10479 dtype,
10480 );
10481 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10482 }
10483 Op::Maximum => {
10484 // y_i = max(a_i, b_i). Gradient flows to whichever
10485 // input was the max at that position:
10486 // mask_a = step(a - b) (1 where a > b, else 0)
10487 // mask_b = 1 - mask_a (approximately — at ties
10488 // gradient goes to b due to
10489 // step(0) = 0)
10490 // grad_a = upstream * mask_a
10491 // grad_b = upstream * mask_b
10492 let a = inputs[0];
10493 let b = inputs[1];
10494 let shape = node_shape(&graph_handle, a);
10495 let dtype = node_dtype(&graph_handle, a);
10496 let diff = push_node(&graph_handle, Op::Sub, vec![a, b], shape.clone(), dtype);
10497 let mask_a =
10498 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10499 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10500 let mask_b = push_node(
10501 &graph_handle,
10502 Op::Sub,
10503 vec![ones, mask_a],
10504 shape.clone(),
10505 dtype,
10506 );
10507 let grad_a = push_node(
10508 &graph_handle,
10509 Op::Mul,
10510 vec![up_id, mask_a],
10511 shape.clone(),
10512 dtype,
10513 );
10514 let grad_b =
10515 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10516 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10517 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10518 }
10519 Op::Minimum => {
10520 // Symmetric to Maximum. mask_a = step(b - a).
10521 let a = inputs[0];
10522 let b = inputs[1];
10523 let shape = node_shape(&graph_handle, a);
10524 let dtype = node_dtype(&graph_handle, a);
10525 let diff = push_node(&graph_handle, Op::Sub, vec![b, a], shape.clone(), dtype);
10526 let mask_a =
10527 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10528 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10529 let mask_b = push_node(
10530 &graph_handle,
10531 Op::Sub,
10532 vec![ones, mask_a],
10533 shape.clone(),
10534 dtype,
10535 );
10536 let grad_a = push_node(
10537 &graph_handle,
10538 Op::Mul,
10539 vec![up_id, mask_a],
10540 shape.clone(),
10541 dtype,
10542 );
10543 let grad_b =
10544 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10545 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10546 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10547 }
10548 Op::ScatterAdd { dim } => {
10549 // Forward: out = scatter_add(base, dim, indices, src).
10550 // Backward:
10551 // grad_base = upstream (pass-through)
10552 // grad_src = gather(upstream, dim, indices)
10553 let base = inputs[0];
10554 let idx = inputs[1];
10555 let src = inputs[2];
10556 let src_shape = node_shape(&graph_handle, src);
10557 let dtype = node_dtype(&graph_handle, src);
10558 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10559 let grad_src = push_node(
10560 &graph_handle,
10561 Op::Gather { dim },
10562 vec![up_id, idx],
10563 src_shape,
10564 dtype,
10565 );
10566 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10567 }
10568 Op::Copy { .. } => {
10569 // Forward: out = copy(x, target). Backward: the
10570 // gradient flows back to `x`'s original device, so
10571 // the reverse would be another Copy. The source
10572 // device is x's residency — we don't have the typed
10573 // "where was x?" here without tracking it, so we
10574 // fall back to the graph's placement hint on x (if
10575 // any) or trust the scheduler to re-insert the
10576 // correct copy during Phase 4. For Phase 3 we
10577 // assume inference-only use and pass upstream through.
10578 let x = inputs[0];
10579 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10580 }
10581 Op::Release => {
10582 // Release has no data output and no gradient to
10583 // propagate. Input is destroyed; any downstream
10584 // node that needs gradient through the original
10585 // tensor must get it from a sibling Copy's backward
10586 // path, not this one.
10587 }
10588 Op::Move { .. } => {
10589 // Move is Copy + destroy-source. For backward,
10590 // treat it the same as Copy — gradient flows back
10591 // through the move. The Phase 3-style assumption
10592 // still applies: we pass upstream through and rely
10593 // on the scheduler to re-insert the correct reverse
10594 // transfer in a training pass. For inference-only
10595 // use (the current case), this is a no-op.
10596 let x = inputs[0];
10597 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10598 }
10599 Op::WriteSlice { .. } => {
10600 // KV-cache writes are forward-only — the slab being
10601 // written *into* gets mutated in place, and the
10602 // source slab is read non-destructively. There is
10603 // no meaningful gradient through a mutating write
10604 // in fuel's tape-based autograd model. If a use
10605 // case needs differentiable scatter, the gradient
10606 // path is a `Gather` (read the slab back) plus an
10607 // accumulating `IndexAdd` on the destination —
10608 // express that explicitly in forward.
10609 panic!(
10610 "NodeHandle::backward: Op::WriteSlice is non-differentiable. \
10611 Use Gather + IndexAdd if you need a differentiable scatter."
10612 );
10613 }
10614 Op::WriteSliceRotating { .. } => {
10615 // Same forward-only contract as WriteSlice — the
10616 // ring buffer's bytes are mutated in place at a
10617 // dynamic offset. Sliding-window KV caches don't
10618 // need a gradient path; a differentiable scatter
10619 // is expressible as Gather + IndexAdd in forward.
10620 panic!(
10621 "NodeHandle::backward: Op::WriteSliceRotating is non-differentiable. \
10622 Use Gather + IndexAdd if you need a differentiable scatter."
10623 );
10624 }
10625 Op::WriteSliceDoff { .. } => {
10626 // Forward-only, like WriteSlice/WriteSliceRotating —
10627 // the KV-cache buffer is mutated in place at a
10628 // device-resident offset. Decode-time append; no
10629 // gradient path.
10630 panic!(
10631 "NodeHandle::backward: Op::WriteSliceDoff is non-differentiable. \
10632 Use Gather + IndexAdd if you need a differentiable scatter."
10633 );
10634 }
10635 // Phase 7.6 step 5 (2026-05-11): the legacy
10636 // `Op::Conv2D { stride, padding, groups }` backward
10637 // arm has been dropped together with the variant;
10638 // `Op::Fused(CONV2D, _)` below carries the full
10639 // backward logic (including the inner dW Conv2D
10640 // emission, which itself goes through Op::Fused).
10641 // Phase 7.6 step 4 (final): the builders for
10642 // ConvTranspose2D, FlashAttn, and PagedAttn now emit
10643 // `Op::Fused(<id>, _)`; these legacy backward arms
10644 // still fire for direct legacy-variant constructions
10645 // Phase 7.6 step 5 (final, 2026-05-11): the legacy
10646 // `Op::ConvTranspose2D` / `Op::FlashAttn` /
10647 // `Op::PagedAttn` / `Op::FusedLinear` backward arms
10648 // have all been dropped together with the variants;
10649 // `Op::Fused(<id>, _)` below panics for each id.
10650 Op::Fused(fid, params) => {
10651 // Per-id backward dispatch. Each migrated fused op
10652 // gets a branch here that emits the appropriate
10653 // gradient subgraph.
10654 if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM {
10655 // grad_x = softmax_last_dim_backward(y, upstream).
10656 // Phase 7.6 step 4 (backward-helper batch):
10657 // emits Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, _)
10658 // — the architecturally-correct registry form,
10659 // matching the BackwardKind::Fused edge on
10660 // SOFTMAX_LAST_DIM's entry.
10661 let x = inputs[0];
10662 let y_shape = node_shape(&graph_handle, id);
10663 let dtype = node_dtype(&graph_handle, id);
10664 let grad_x = push_node(
10665 &graph_handle,
10666 Op::Fused(
10667 crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
10668 crate::registry::FusedOpParams::SoftmaxLastDimBackward,
10669 ),
10670 vec![id, up_id],
10671 y_shape,
10672 dtype,
10673 );
10674 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10675 } else if fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM {
10676 // grad_x = layer_norm_last_dim_backward(x, upstream, eps).
10677 // Phase 7.6 step 4 (backward-helper batch): emits
10678 // registry form Op::Fused(LAYER_NORM_LAST_DIM_BACKWARD, _).
10679 let eps = match params {
10680 crate::registry::FusedOpParams::LayerNormLastDim { eps } => eps,
10681 _ => panic!(
10682 "NodeHandle::backward: Op::Fused(LAYER_NORM_LAST_DIM, _) \
10683 expected FusedOpParams::LayerNormLastDim, got {params:?}",
10684 ),
10685 };
10686 let x = inputs[0];
10687 let x_shape = node_shape(&graph_handle, x);
10688 let dtype = node_dtype(&graph_handle, x);
10689 let grad_x = push_node(
10690 &graph_handle,
10691 Op::Fused(
10692 crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
10693 crate::registry::FusedOpParams::LayerNormLastDimBackward { eps },
10694 ),
10695 vec![x, up_id],
10696 x_shape,
10697 dtype,
10698 );
10699 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10700 } else if fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM {
10701 // grad_x = rms_norm_last_dim_backward(x, upstream, eps).
10702 // Phase 7.6 step 4 (backward-helper batch): emits
10703 // registry form Op::Fused(RMS_NORM_LAST_DIM_BACKWARD, _).
10704 let eps = match params {
10705 crate::registry::FusedOpParams::RmsNormLastDim { eps } => eps,
10706 _ => panic!(
10707 "NodeHandle::backward: Op::Fused(RMS_NORM_LAST_DIM, _) \
10708 expected FusedOpParams::RmsNormLastDim, 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::RMS_NORM_LAST_DIM_BACKWARD,
10718 crate::registry::FusedOpParams::RmsNormLastDimBackward { 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::ROPE {
10726 // grad_x = rope(upstream, cos, -sin) — same
10727 // formula as the legacy Op::Rope arm above.
10728 // Emit the registry form for the backward
10729 // Rope node so the gradient subgraph routes
10730 // through the same Op::Fused dispatch as the
10731 // forward.
10732 let x = inputs[0];
10733 let cos = inputs[1];
10734 let sin = inputs[2];
10735 let x_shape = node_shape(&graph_handle, x);
10736 let sin_shape = node_shape(&graph_handle, sin);
10737 let dtype = node_dtype(&graph_handle, x);
10738 let neg_sin =
10739 push_node(&graph_handle, Op::Neg, vec![sin], sin_shape, dtype);
10740 let grad_x = push_node(
10741 &graph_handle,
10742 Op::Fused(
10743 crate::registry::FusedOps::ROPE,
10744 crate::registry::FusedOpParams::Rope,
10745 ),
10746 vec![up_id, cos, neg_sin],
10747 x_shape,
10748 dtype,
10749 );
10750 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10751 } else if fid == crate::registry::FusedOps::FUSED_LINEAR {
10752 // (a @ b) + bias backward — same three-grad
10753 // decomposition as the legacy Op::FusedLinear
10754 // arm above. We reuse MatMul backward (no
10755 // intermediate matmul output is cached, so the
10756 // grad computes from upstream + a, b directly).
10757 let a = inputs[0];
10758 let b = inputs[1];
10759 let bias = inputs[2];
10760 let a_shape = node_shape(&graph_handle, a);
10761 let b_shape = node_shape(&graph_handle, b);
10762 let bias_shape = node_shape(&graph_handle, bias);
10763 let dtype = node_dtype(&graph_handle, a);
10764 let b_t_shape = transposed_shape(&b_shape);
10765 let b_t =
10766 push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
10767 let grad_a = push_node(
10768 &graph_handle,
10769 Op::MatMul,
10770 vec![up_id, b_t],
10771 a_shape.clone(),
10772 dtype,
10773 );
10774 let a_t_shape = transposed_shape(&a_shape);
10775 let a_t =
10776 push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
10777 let grad_b =
10778 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
10779 let grad_bias = push_node(
10780 &graph_handle,
10781 Op::ReduceSumTo(bias_shape.clone()),
10782 vec![up_id],
10783 bias_shape,
10784 dtype,
10785 );
10786 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10787 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10788 accumulate_grad(&mut upstream, bias, grad_bias, &graph_handle);
10789 } else if fid == crate::registry::FusedOps::CONV2D {
10790 // Same backward formulation as the legacy
10791 // Op::Conv2D arm above. The inner Conv2D node
10792 // emitted for grad_w also goes through the
10793 // registry (Op::Fused(CONV2D, _)) so the
10794 // gradient subgraph routes consistently. The
10795 // ConvTranspose2D node stays as a primitive
10796 // variant until that op migrates in its own
10797 // step-4 commit.
10798 let (stride, padding, groups) = match params {
10799 crate::registry::FusedOpParams::Conv2D {
10800 stride,
10801 padding,
10802 groups,
10803 } => (stride, padding, groups),
10804 _ => panic!(
10805 "NodeHandle::backward: Op::Fused(CONV2D, _) \
10806 expected FusedOpParams::Conv2D, got {params:?}",
10807 ),
10808 };
10809 let x = inputs[0];
10810 let weight = inputs[1];
10811 let x_shape = node_shape(&graph_handle, x);
10812 let w_shape = node_shape(&graph_handle, weight);
10813 let dtype = node_dtype(&graph_handle, x);
10814
10815 // dX via transposed conv (see legacy arm for derivation).
10816 let x_dims = x_shape.dims();
10817 let w_dims = w_shape.dims();
10818 let dy_dims = node_shape(&graph_handle, id).dims().to_vec();
10819 let (sh, sw) = stride;
10820 let (ph, pw) = padding;
10821 let (kh, kw) = (w_dims[2], w_dims[3]);
10822 let (h_in, w_in) = (x_dims[2], x_dims[3]);
10823 let (dy_h, dy_w) = (dy_dims[2], dy_dims[3]);
10824 let base_h = (dy_h - 1) * sh + (kh - 1) + 1;
10825 let base_w = (dy_w - 1) * sw + (kw - 1) + 1;
10826 let want_h = h_in + 2 * ph;
10827 let want_w = w_in + 2 * pw;
10828 let out_pad_h = want_h.saturating_sub(base_h);
10829 let out_pad_w = want_w.saturating_sub(base_w);
10830 if groups != 1 {
10831 panic!(
10832 "NodeHandle::backward: Op::Fused(CONV2D) groups>1 \
10833 backward not yet implemented (got groups={groups}). \
10834 The stride/padding/groups=1 case is wired; grouped \
10835 backward needs a per-group weight reshape.",
10836 );
10837 }
10838 let perm_01 = vec![1usize, 0, 2, 3];
10839 // Phase 7.6 step 4 (final): emit registry form
10840 // for the inner dX node so the gradient subgraph
10841 // routes consistently through Op::Fused dispatch.
10842 let grad_x = push_node(
10843 &graph_handle,
10844 Op::Fused(
10845 crate::registry::FusedOps::CONV_TRANSPOSE2D,
10846 crate::registry::FusedOpParams::ConvTranspose2D {
10847 stride,
10848 padding,
10849 output_padding: (out_pad_h, out_pad_w),
10850 dilation: (1, 1),
10851 groups,
10852 },
10853 ),
10854 vec![up_id, weight],
10855 x_shape.clone(),
10856 dtype,
10857 );
10858 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10859
10860 // dW via correlation expressed as a conv2d.
10861 if sh != 1 || sw != 1 {
10862 panic!(
10863 "NodeHandle::backward: Op::Fused(CONV2D) stride>1 \
10864 backward not yet implemented (got stride={stride:?}). \
10865 Conv2D needs a `dilation` field to express this \
10866 without composing extra ops.",
10867 );
10868 }
10869 let x_swapped_shape = {
10870 let d = x_dims;
10871 Shape::from_dims(&[d[1], d[0], d[2], d[3]])
10872 };
10873 let x_swapped = push_node(
10874 &graph_handle,
10875 Op::Permute(perm_01.clone()),
10876 vec![x],
10877 x_swapped_shape,
10878 dtype,
10879 );
10880 let dy_swapped_shape =
10881 Shape::from_dims(&[dy_dims[1], dy_dims[0], dy_dims[2], dy_dims[3]]);
10882 let dy_swapped = push_node(
10883 &graph_handle,
10884 Op::Permute(perm_01.clone()),
10885 vec![up_id],
10886 dy_swapped_shape,
10887 dtype,
10888 );
10889 let conv_out_shape =
10890 Shape::from_dims(&[w_dims[1], w_dims[0], w_dims[2], w_dims[3]]);
10891 let grad_w_pre_transpose = push_node(
10892 &graph_handle,
10893 Op::Fused(
10894 crate::registry::FusedOps::CONV2D,
10895 crate::registry::FusedOpParams::Conv2D {
10896 stride: (1, 1),
10897 padding,
10898 groups: 1,
10899 },
10900 ),
10901 vec![x_swapped, dy_swapped],
10902 conv_out_shape,
10903 dtype,
10904 );
10905 let grad_w = push_node(
10906 &graph_handle,
10907 Op::Permute(perm_01),
10908 vec![grad_w_pre_transpose],
10909 w_shape,
10910 dtype,
10911 );
10912 accumulate_grad(&mut upstream, weight, grad_w, &graph_handle);
10913
10914 // Bias (if present): sum dY over N, H, W via
10915 // ReduceSumTo([1, Cout, 1, 1]) then reshape to
10916 // [Cout]. Same path as the legacy arm.
10917 if inputs.len() >= 3 {
10918 let bias = inputs[2];
10919 let bias_shape = node_shape(&graph_handle, bias);
10920 let cout_4d = Shape::from_dims(&[1, dy_dims[1], 1, 1]);
10921 let reduced = push_node(
10922 &graph_handle,
10923 Op::ReduceSumTo(cout_4d.clone()),
10924 vec![up_id],
10925 cout_4d,
10926 dtype,
10927 );
10928 let grad_b = push_node(
10929 &graph_handle,
10930 Op::Reshape(bias_shape.clone()),
10931 vec![reduced],
10932 bias_shape,
10933 dtype,
10934 );
10935 accumulate_grad(&mut upstream, bias, grad_b, &graph_handle);
10936 }
10937 } else if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD
10938 || fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD
10939 || fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
10940 || fid == crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD
10941 {
10942 // Higher-order gradients through backward
10943 // helpers panic.
10944 panic!(
10945 "backward: higher-order gradients through \
10946 softmax/layer_norm/rms_norm/reduce_max_to backward \
10947 helpers are not yet supported in the MVP."
10948 );
10949 } else if fid == crate::registry::FusedOps::CONV_TRANSPOSE2D {
10950 // Higher-order grad of the transposed conv
10951 // isn't needed for Conv2D's backward (which
10952 // only consumes the forward output). Adding
10953 // it requires the same dilation-as-stride
10954 // trick as Conv2D's dW. Punt until a real
10955 // consumer asks for it.
10956 panic!(
10957 "NodeHandle::backward: ConvTranspose2D does \
10958 not yet have its own gradient rule \
10959 (only used in the forward path of \
10960 Conv2D's backward).",
10961 );
10962 } else if fid == crate::registry::FusedOps::FLASH_ATTN {
10963 // Emit three backward nodes: dQ via
10964 // FLASH_ATTN_BACKWARD_Q, dK via _K, dV via _V.
10965 // Each takes (q, k, v, dO, [alibi]) and
10966 // recomputes the softmax state independently
10967 // in CPU's math-definition path. GPU kernels
10968 // (when they ship) can fuse the recompute.
10969 let q = inputs[0];
10970 let k = inputs[1];
10971 let v = inputs[2];
10972 let alibi = inputs.get(3).copied();
10973 let q_shape = node_shape(&graph_handle, q);
10974 let k_shape = node_shape(&graph_handle, k);
10975 let v_shape = node_shape(&graph_handle, v);
10976 let dtype = node_dtype(&graph_handle, q);
10977 let (scale, causal, wl, wr, sc) = match params {
10978 crate::registry::FusedOpParams::FlashAttn {
10979 softmax_scale,
10980 causal,
10981 window_size_left,
10982 window_size_right,
10983 softcap,
10984 // Backward over the static (full-K) flash
10985 // only; the runtime-k_len capacity form is
10986 // forward-only (decode). k_len is ignored
10987 // here.
10988 k_len: _,
10989 } => (
10990 softmax_scale,
10991 causal,
10992 window_size_left,
10993 window_size_right,
10994 softcap,
10995 ),
10996 other => panic!(
10997 "NodeHandle::backward: FlashAttn node carries \
10998 unexpected params {other:?}",
10999 ),
11000 };
11001 let bw_params = crate::registry::FusedOpParams::FlashAttnBackward {
11002 softmax_scale: scale,
11003 causal,
11004 window_size_left: wl,
11005 window_size_right: wr,
11006 softcap: sc,
11007 };
11008 let mut bw_inputs = vec![q, k, v, up_id];
11009 if let Some(a) = alibi {
11010 bw_inputs.push(a);
11011 }
11012 let grad_q = push_node(
11013 &graph_handle,
11014 Op::Fused(
11015 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_Q,
11016 bw_params.clone(),
11017 ),
11018 bw_inputs.clone(),
11019 q_shape,
11020 dtype,
11021 );
11022 let grad_k = push_node(
11023 &graph_handle,
11024 Op::Fused(
11025 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_K,
11026 bw_params.clone(),
11027 ),
11028 bw_inputs.clone(),
11029 k_shape,
11030 dtype,
11031 );
11032 let grad_v = push_node(
11033 &graph_handle,
11034 Op::Fused(crate::registry::FusedOps::FLASH_ATTN_BACKWARD_V, bw_params),
11035 bw_inputs,
11036 v_shape,
11037 dtype,
11038 );
11039 accumulate_grad(&mut upstream, q, grad_q, &graph_handle);
11040 accumulate_grad(&mut upstream, k, grad_k, &graph_handle);
11041 accumulate_grad(&mut upstream, v, grad_v, &graph_handle);
11042 } else if fid == crate::registry::FusedOps::PAGED_ATTN {
11043 // Paged attention is decode-side only by
11044 // construction (variable-length KV cache, no
11045 // training pass writes through it). No
11046 // gradient rule.
11047 panic!(
11048 "NodeHandle::backward: PagedAttn is \
11049 decode-only; no gradient rule exists.",
11050 );
11051 } else if fid == crate::registry::FusedOps::QMATMUL {
11052 // Quantized matmul: weights are frozen
11053 // bytes; activation gradient isn't
11054 // implemented today. Dequantize-then-matmul
11055 // is the workaround if differentiable
11056 // quantized inference is needed.
11057 panic!(
11058 "backward: QMatMul is not differentiable \
11059 (quantized weights are frozen). Use a \
11060 dequantize + standard matmul if you \
11061 need gradients through this input."
11062 );
11063 } else {
11064 panic!(
11065 "NodeHandle::backward: Op::Fused id {fid:?} has no \
11066 backward arm wired yet. This is a programming \
11067 bug — extend the match when the op migrates \
11068 to the registry.",
11069 );
11070 }
11071 }
11072 Op::Alloc { .. } => {
11073 // Op::Alloc is a source op (zero inputs) that
11074 // produces a fresh zero-init buffer. No upstream
11075 // gradient to propagate — the alloc's "input" is
11076 // the abstract notion of fresh memory, which has
11077 // no derivative. Mirrors Op::Const's treatment.
11078 // (Phase 3a of bridge-retirement; see
11079 // `WorkItemKind::Alloc` in fuel-storage.)
11080 }
11081 Op::ZeroFill => {
11082 // Op::ZeroFill writes deterministic constants
11083 // (zeros) to its input's bytes. The output is
11084 // a constant tensor; gradient w.r.t. it is
11085 // meaningless. Like Op::Const / Op::Alloc, no
11086 // gradient propagates back.
11087 }
11088 Op::ScatterIntoSlot { .. } => {
11089 // Item 4 IR-only scaffold — the backward graph
11090 // emits this op as the producer's gradient
11091 // assembler, but `ScatterIntoSlot` itself has no
11092 // backward (it's a structural op composing
11093 // already-differentiated slot gradients). No
11094 // gradient propagates back; matches the
11095 // Op::Const / Op::Alloc / Op::ZeroFill treatment.
11096 }
11097 Op::Branch { .. } => {
11098 // PR-A0 inert scaffold. `Op::Branch` is the
11099 // multi-path phi/merge node; it is never constructed
11100 // in A0, so this arm is unreachable today. When the
11101 // PR-A1 builders land, gradient flow through a Branch
11102 // routes via its arms (each an `inputs[i]` route exit)
11103 // and reconverges at `reconverge_at` — not through the
11104 // merge node itself. `backward` is infallible
11105 // (`-> GradMap`), so the no-panic inert handling is to
11106 // drop the gradient at the structural node, matching
11107 // the Op::Const / Op::ScatterIntoSlot treatment above.
11108 // The real per-arm routing lands with the builders.
11109 }
11110 Op::Scan { .. } => {
11111 // Defensive `panic!` — `backward() -> GradMap` is infallible
11112 // (no Err channel), so this is an internal-error guard in the
11113 // same infallible walk that already panics for QMatMul /
11114 // PagedAttn, NOT a recoverable typed error. It is unreachable
11115 // via the public builders: the C3 pre-pass
11116 // (lower_scans_for_backward) unrolls every Op::Scan to
11117 // primitives before the topo order is taken, and the builders
11118 // always emit the View consumers the pre-pass's remap +
11119 // never-hang guard lower away. Reaching here means the
11120 // pre-pass did not run (an internal bug).
11121 panic!(
11122 "NodeHandle::backward: Op::Scan reached the reverse walk un-lowered — \
11123 the C3 lower_scans_for_backward pre-pass did not run (internal bug)."
11124 );
11125 }
11126 Op::ScanPlaceholder { .. } => {
11127 // Inert body-hole leaf (no inputs) — never a real
11128 // differentiation target. Drop gradient like Op::Const /
11129 // Op::Iota; a live backward never reaches it (the body is
11130 // materialized by unroll_scan before any realize).
11131 }
11132 Op::View { slot } | Op::ViewOwned { slot } => {
11133 // Multi-output projection — item 4 backward
11134 // composition (Option C, 2026-06-01).
11135 //
11136 // Forward (Op::View): shares the producer's
11137 // bundled Storage Arc and exposes one slot's
11138 // typed window. Forward (Op::ViewOwned): memcpys
11139 // the slot's bytes into a fresh Storage.
11140 //
11141 // Backward: scatter the upstream gradient into
11142 // the slot's byte range of a fresh zero-bundle of
11143 // the producer's primary shape, then accumulate
11144 // that partial-bundle gradient as the producer's
11145 // input gradient. Multiple View consumers of the
11146 // same producer accumulate via the standard
11147 // sum-of-partials path:
11148 // bundle_grad =
11149 // ScatterIntoSlot{0}(0, g_y) +
11150 // ScatterIntoSlot{1}(0, g_state) + ...
11151 //
11152 // **Status (item 4)**: IR-level wiring only —
11153 // emits the scatter chain in the backward graph,
11154 // but no Op::ScatterIntoSlot kernel is registered.
11155 // The production multi-output producers
11156 // (SelectiveScan, SsdChunkScan) are
11157 // `BackwardKind::NotDifferentiable`, so autograd
11158 // panics at the producer before this scatter is
11159 // realized. When a differentiable multi-output op
11160 // materializes (Mamba training, FSCE loss+grad
11161 // fused), it lights up the ScatterIntoSlot CPU
11162 // kernel + tests alongside its own backward.
11163 let producer = inputs[0];
11164 let producer_shape = node_shape(&graph_handle, producer);
11165 let producer_dtype = node_dtype(&graph_handle, producer);
11166 let zero = build_filled_const(
11167 &graph_handle,
11168 producer_shape.clone(),
11169 producer_dtype,
11170 0.0,
11171 );
11172 let scattered = push_node(
11173 &graph_handle,
11174 Op::ScatterIntoSlot { slot },
11175 vec![zero, up_id],
11176 producer_shape,
11177 producer_dtype,
11178 );
11179 accumulate_grad(&mut upstream, producer, scattered, &graph_handle);
11180 }
11181 Op::ReluInplace => {
11182 // Same backward as Op::Relu — d(relu(x))/dx = step(x).
11183 // The view-aware `derive_ordering` (Phase 4a) pins
11184 // `Op::Step(x)` to run BEFORE Op::ReluInplace, so the
11185 // step kernel sees x's original bytes.
11186 let x = inputs[0];
11187 let x_shape = node_shape(&graph_handle, x);
11188 let dtype = node_dtype(&graph_handle, x);
11189 let step_x =
11190 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
11191 let grad_x =
11192 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
11193 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11194 }
11195 Op::SiluInplace => {
11196 // Same backward as Op::Silu — grad_x = upstream * (s + y*(1-s))
11197 // where s = sigmoid(x) and y = silu(x) = this in-place node's
11198 // output. The post-mutation bytes at `id` ARE silu(x) (the
11199 // in-place op runs after the Sigmoid(x) read because of the
11200 // alias-aware ordering pass). `Op::Sigmoid(x)` reads x's
11201 // pre-mutation bytes; `Op::Mul(id, ...)` reads post-mutation
11202 // bytes — both correct.
11203 let x = inputs[0];
11204 let x_shape = node_shape(&graph_handle, x);
11205 let dtype = node_dtype(&graph_handle, x);
11206 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
11207 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
11208 let one_minus_s = push_node(
11209 &graph_handle,
11210 Op::Sub,
11211 vec![ones, s],
11212 x_shape.clone(),
11213 dtype,
11214 );
11215 let y_times_1ms = push_node(
11216 &graph_handle,
11217 Op::Mul,
11218 vec![id, one_minus_s],
11219 x_shape.clone(),
11220 dtype,
11221 );
11222 let inner = push_node(
11223 &graph_handle,
11224 Op::Add,
11225 vec![s, y_times_1ms],
11226 x_shape.clone(),
11227 dtype,
11228 );
11229 let grad_x =
11230 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
11231 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11232 }
11233 Op::TanhInplace => {
11234 // Same backward as Op::Tanh — grad_x = upstream * (1 - y²)
11235 // where y = tanh(x) = this in-place node's output. `Op::Sqr(id)`
11236 // reads post-mutation bytes (= tanh(x) by definition of the
11237 // in-place op); no need to reference x at all.
11238 let x = inputs[0];
11239 let y_shape = node_shape(&graph_handle, id);
11240 let dtype = node_dtype(&graph_handle, id);
11241 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
11242 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11243 let one_minus_sq = push_node(
11244 &graph_handle,
11245 Op::Sub,
11246 vec![ones, y_sq],
11247 y_shape.clone(),
11248 dtype,
11249 );
11250 let grad_x = push_node(
11251 &graph_handle,
11252 Op::Mul,
11253 vec![up_id, one_minus_sq],
11254 y_shape,
11255 dtype,
11256 );
11257 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11258 }
11259 Op::SigmoidInplace => {
11260 // Same backward as Op::Sigmoid — grad_x = upstream * y * (1 - y)
11261 // where y = sigmoid(x) = this in-place node's output.
11262 let x = inputs[0];
11263 let y_shape = node_shape(&graph_handle, id);
11264 let dtype = node_dtype(&graph_handle, id);
11265 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11266 let one_minus_y = push_node(
11267 &graph_handle,
11268 Op::Sub,
11269 vec![ones, id],
11270 y_shape.clone(),
11271 dtype,
11272 );
11273 let y_times_1my = push_node(
11274 &graph_handle,
11275 Op::Mul,
11276 vec![id, one_minus_y],
11277 y_shape.clone(),
11278 dtype,
11279 );
11280 let grad_x = push_node(
11281 &graph_handle,
11282 Op::Mul,
11283 vec![up_id, y_times_1my],
11284 y_shape,
11285 dtype,
11286 );
11287 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11288 }
11289 Op::GeluTanhInplace => {
11290 // Same backward as Op::GeluTanh. The formula reads only the
11291 // pre-mutation input `x` (like SiluInplace's Sigmoid(x) read),
11292 // which the alias-aware ordering pass keeps ahead of the
11293 // in-place write.
11294 let x = inputs[0];
11295 let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
11296 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11297 }
11298 Op::NegInplace => {
11299 // Same backward as Op::Neg — grad_x = -upstream. No
11300 // dependency on x or y; Phase 4a ordering not needed.
11301 let x = inputs[0];
11302 let x_shape = node_shape(&graph_handle, x);
11303 let dtype = node_dtype(&graph_handle, x);
11304 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
11305 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11306 }
11307 Op::AbsInplace => {
11308 // Same backward as Op::Abs — grad_x = sign(x) * upstream.
11309 // `Op::Sign(x)` reads x's pre-mutation bytes (Phase 4a
11310 // pins the in-place op after the Sign read).
11311 let x = inputs[0];
11312 let x_shape = node_shape(&graph_handle, x);
11313 let dtype = node_dtype(&graph_handle, x);
11314 let sign_x =
11315 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
11316 let grad_x =
11317 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
11318 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11319 }
11320 Op::SqrInplace => {
11321 // Same backward as Op::Sqr — grad_x = 2x * upstream,
11322 // expressed as `x + x` to avoid a scalar broadcast.
11323 // `x + x` reads pre-mutation bytes (Phase 4a).
11324 let x = inputs[0];
11325 let x_shape = node_shape(&graph_handle, x);
11326 let dtype = node_dtype(&graph_handle, x);
11327 let two_x =
11328 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
11329 let grad_x =
11330 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
11331 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11332 }
11333 Op::SqrtInplace => {
11334 // Same backward as Op::Sqrt — y = √x, grad_x = upstream/(2y).
11335 // Reads only the forward output `id`, which is post-mutation =
11336 // √x by definition; no pre-mutation x access needed.
11337 let x = inputs[0];
11338 let x_shape = node_shape(&graph_handle, x);
11339 let dtype = node_dtype(&graph_handle, x);
11340 let two_y =
11341 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
11342 let grad_x =
11343 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
11344 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11345 }
11346 Op::RsqrtInplace => {
11347 // Same backward as Op::Rsqrt — y = x^(-1/2),
11348 // grad_x = -0.5 * upstream * y³. Reads forward output (id)
11349 // only — post-mutation = y by definition.
11350 let x = inputs[0];
11351 let x_shape = node_shape(&graph_handle, x);
11352 let dtype = node_dtype(&graph_handle, x);
11353 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11354 let y_cu = push_node(
11355 &graph_handle,
11356 Op::Mul,
11357 vec![id, y_sq],
11358 x_shape.clone(),
11359 dtype,
11360 );
11361 let scaled = push_node(
11362 &graph_handle,
11363 Op::MulScalar(-0.5),
11364 vec![y_cu],
11365 x_shape.clone(),
11366 dtype,
11367 );
11368 let grad_x =
11369 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11370 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11371 }
11372 Op::RecipInplace => {
11373 // Same backward as Op::Recip — y = 1/x, grad_x = -upstream * y².
11374 // Reads forward output (id) only — post-mutation = 1/x.
11375 let x = inputs[0];
11376 let x_shape = node_shape(&graph_handle, x);
11377 let dtype = node_dtype(&graph_handle, x);
11378 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11379 let up_y_sq = push_node(
11380 &graph_handle,
11381 Op::Mul,
11382 vec![up_id, y_sq],
11383 x_shape.clone(),
11384 dtype,
11385 );
11386 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
11387 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11388 }
11389 Op::ExpInplace => {
11390 // Same backward as Op::Exp — d(exp(x))/dx = exp(x) = y = id.
11391 // grad_x = upstream * y. Reads forward output (id) only.
11392 let x = inputs[0];
11393 let out_shape = node_shape(&graph_handle, id);
11394 let dtype = node_dtype(&graph_handle, id);
11395 let grad_x =
11396 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
11397 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11398 }
11399 Op::LogInplace => {
11400 // Same backward as Op::Log — grad_x = upstream / x.
11401 // `Op::Div(up, x)` reads pre-mutation bytes of x (Phase 4a).
11402 let x = inputs[0];
11403 let x_shape = node_shape(&graph_handle, x);
11404 let dtype = node_dtype(&graph_handle, x);
11405 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
11406 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11407 }
11408 Op::SinInplace => {
11409 // Same backward as Op::Sin — grad_x = upstream * cos(x).
11410 // `Op::Cos(x)` reads pre-mutation x via Phase 4a ordering.
11411 let x = inputs[0];
11412 let x_shape = node_shape(&graph_handle, x);
11413 let dtype = node_dtype(&graph_handle, x);
11414 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
11415 let grad_x =
11416 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
11417 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11418 }
11419 Op::CosInplace => {
11420 // Same backward as Op::Cos — grad_x = -(upstream * sin(x)).
11421 let x = inputs[0];
11422 let x_shape = node_shape(&graph_handle, x);
11423 let dtype = node_dtype(&graph_handle, x);
11424 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
11425 let up_sin = push_node(
11426 &graph_handle,
11427 Op::Mul,
11428 vec![up_id, sin_x],
11429 x_shape.clone(),
11430 dtype,
11431 );
11432 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
11433 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11434 }
11435 Op::SignInplace | Op::FloorInplace | Op::CeilInplace | Op::RoundInplace => {
11436 // Same backward as Op::{Sign, Floor, Ceil, Round} —
11437 // derivative is 0 almost everywhere; drop gradient
11438 // (no accumulation, mirroring Op::Step's pattern).
11439 }
11440 Op::ErfInplace => {
11441 // Same backward as Op::Erf — grad_x = upstream * (2/√π) * exp(-x²).
11442 // `Op::Sqr(x)` reads pre-mutation x via Phase 4a ordering.
11443 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
11444 let x = inputs[0];
11445 let x_shape = node_shape(&graph_handle, x);
11446 let dtype = node_dtype(&graph_handle, x);
11447 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11448 let neg_x_sq =
11449 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
11450 let exp_neg = push_node(
11451 &graph_handle,
11452 Op::Exp,
11453 vec![neg_x_sq],
11454 x_shape.clone(),
11455 dtype,
11456 );
11457 let scaled = push_node(
11458 &graph_handle,
11459 Op::MulScalar(TWO_OVER_SQRT_PI),
11460 vec![exp_neg],
11461 x_shape.clone(),
11462 dtype,
11463 );
11464 let grad_x =
11465 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11466 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11467 }
11468 Op::ClampInplace { min, max } => {
11469 // Same backward as Op::Clamp — indicator is 1 where
11470 // min ≤ x ≤ max, 0 elsewhere. Reads pre-mutation x via
11471 // Phase 4a ordering.
11472 let x = inputs[0];
11473 let x_shape = node_shape(&graph_handle, x);
11474 let dtype = node_dtype(&graph_handle, x);
11475 let min_shifted = push_node(
11476 &graph_handle,
11477 Op::AddScalar(-min),
11478 vec![x],
11479 x_shape.clone(),
11480 dtype,
11481 );
11482 let lower_ok = push_node(
11483 &graph_handle,
11484 Op::Step,
11485 vec![min_shifted],
11486 x_shape.clone(),
11487 dtype,
11488 );
11489 let neg_x = push_node(
11490 &graph_handle,
11491 Op::MulScalar(-1.0),
11492 vec![x],
11493 x_shape.clone(),
11494 dtype,
11495 );
11496 let max_minus_x = push_node(
11497 &graph_handle,
11498 Op::AddScalar(max),
11499 vec![neg_x],
11500 x_shape.clone(),
11501 dtype,
11502 );
11503 let upper_ok = push_node(
11504 &graph_handle,
11505 Op::Step,
11506 vec![max_minus_x],
11507 x_shape.clone(),
11508 dtype,
11509 );
11510 let indicator = push_node(
11511 &graph_handle,
11512 Op::Mul,
11513 vec![lower_ok, upper_ok],
11514 x_shape.clone(),
11515 dtype,
11516 );
11517 let grad_x = push_node(
11518 &graph_handle,
11519 Op::Mul,
11520 vec![up_id, indicator],
11521 x_shape,
11522 dtype,
11523 );
11524 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11525 }
11526 Op::PowIInplace(n) => {
11527 // Same backward as Op::PowI — single fused
11528 // POWI_BACKWARD node `(x, upstream) → exp · x^(exp-1) ·
11529 // upstream`. Reads pre-mutation x via Phase 4a ordering.
11530 let x = inputs[0];
11531 let x_shape = node_shape(&graph_handle, x);
11532 let dtype = node_dtype(&graph_handle, x);
11533 let grad_x = push_node(
11534 &graph_handle,
11535 Op::Fused(
11536 crate::registry::FusedOps::POWI_BACKWARD,
11537 crate::registry::FusedOpParams::PowIBackward { exp: n },
11538 ),
11539 vec![x, up_id],
11540 x_shape,
11541 dtype,
11542 );
11543 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11544 }
11545 Op::GeluInplace => {
11546 // Same backward as Op::Gelu — exact-GELU derivative
11547 // is Φ(x) + x·φ(x). Both halves read pre-mutation x via
11548 // Phase 4a ordering. Identical 12-node chain to Op::Gelu.
11549 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
11550 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
11551 let x = inputs[0];
11552 let x_shape = node_shape(&graph_handle, x);
11553 let dtype = node_dtype(&graph_handle, x);
11554 let x_over_sqrt2 = push_node(
11555 &graph_handle,
11556 Op::MulScalar(INV_SQRT_2),
11557 vec![x],
11558 x_shape.clone(),
11559 dtype,
11560 );
11561 let erf_arg = push_node(
11562 &graph_handle,
11563 Op::Erf,
11564 vec![x_over_sqrt2],
11565 x_shape.clone(),
11566 dtype,
11567 );
11568 let plus_one = push_node(
11569 &graph_handle,
11570 Op::AddScalar(1.0),
11571 vec![erf_arg],
11572 x_shape.clone(),
11573 dtype,
11574 );
11575 let cdf_term = push_node(
11576 &graph_handle,
11577 Op::MulScalar(0.5),
11578 vec![plus_one],
11579 x_shape.clone(),
11580 dtype,
11581 );
11582 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11583 let half_x_sq = push_node(
11584 &graph_handle,
11585 Op::MulScalar(0.5),
11586 vec![x_sq],
11587 x_shape.clone(),
11588 dtype,
11589 );
11590 let neg_half = push_node(
11591 &graph_handle,
11592 Op::Neg,
11593 vec![half_x_sq],
11594 x_shape.clone(),
11595 dtype,
11596 );
11597 let exp_term = push_node(
11598 &graph_handle,
11599 Op::Exp,
11600 vec![neg_half],
11601 x_shape.clone(),
11602 dtype,
11603 );
11604 let phi = push_node(
11605 &graph_handle,
11606 Op::MulScalar(INV_SQRT_2PI),
11607 vec![exp_term],
11608 x_shape.clone(),
11609 dtype,
11610 );
11611 let pdf_term =
11612 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
11613 let d_gelu = push_node(
11614 &graph_handle,
11615 Op::Add,
11616 vec![cdf_term, pdf_term],
11617 x_shape.clone(),
11618 dtype,
11619 );
11620 let grad_x =
11621 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
11622 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11623 }
11624 }
11625 }
11626
11627 GradMap {
11628 graph: graph_handle,
11629 forward_to_grad: upstream,
11630 }
11631 }
11632}
11633
11634/// Map from forward-graph node IDs to the IDs of their accumulated
11635/// backward-graph gradient nodes, returned by [`NodeHandle::backward`].
11636///
11637/// All gradient nodes live on the same graph as the forward nodes. Getting
11638/// a gradient by calling [`GradMap::get`] returns a new [`NodeHandle`] handle
11639/// pointing at the gradient node so callers can realize it, plug it into
11640/// further computation, or back-propagate through it again.
11641pub struct GradMap {
11642 graph: SharedGraph,
11643 forward_to_grad: HashMap<NodeId, NodeId>,
11644}
11645
11646impl GradMap {
11647 /// Get the gradient tensor for a forward tensor from the same graph.
11648 ///
11649 /// Returns `None` if the forward tensor was not reachable from the
11650 /// root passed to `backward` (i.e. not part of the computation being
11651 /// differentiated).
11652 ///
11653 /// # Panics
11654 ///
11655 /// Panics if any operand belongs to a different [`Graph`] than the one this
11656 /// builder is building into. Operand identity is graph-scoped and checked by
11657 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
11658 /// deliberate and replaces the hang a cross-graph handle used to produce.
11659 /// Build every operand from one graph, or use a `Result`-returning entry
11660 /// point where one exists.
11661 pub fn get(&self, forward: &NodeHandle) -> Option<NodeHandle> {
11662 assert!(
11663 Arc::ptr_eq(&self.graph, &forward.graph),
11664 "GradMap::get: tensor is from a different graph",
11665 );
11666 let &grad_id = self.forward_to_grad.get(&forward.id)?;
11667 Some(NodeHandle {
11668 graph: self.graph.clone(),
11669 id: grad_id,
11670 })
11671 }
11672
11673 /// Number of forward nodes that have a recorded gradient.
11674 pub fn len(&self) -> usize {
11675 self.forward_to_grad.len()
11676 }
11677
11678 /// Whether this map has no gradients (e.g. a backward over a lone const).
11679 pub fn is_empty(&self) -> bool {
11680 self.forward_to_grad.is_empty()
11681 }
11682}
11683
11684// -------- internal helpers shared by the backward pass --------------------
11685
11686/// Does the registry declare this fused op's backward to be "lower it via its
11687/// total `decompose`, then differentiate the primitives"?
11688fn lowers_for_backward(fid: crate::registry::FusedOpId) -> bool {
11689 crate::registry::default_registry()
11690 .entry(fid)
11691 .is_some_and(|e| e.backward == crate::registry::BackwardKind::Decompose)
11692}
11693
11694/// The generic decompose-backward hook (Op::Scan Phase 2, C3): before the
11695/// reverse walk takes its topo order, lower every reachable `Op::Scan` to
11696/// `bound` primitives and decompose the two SSM `Op::Fused` recipes into their
11697/// `Op::Scan` form, rewiring consumers so the walk sees only differentiable
11698/// primitives. BPTT differentiates the static-`bound` unroll (the runtime
11699/// early-exit predicate is a forward-only optimization, ignored here — spec C3
11700/// static-horizon note). Operates in place on the shared graph (a `backward()`
11701/// caller is a training step that wants the unrolled activations anyway).
11702/// Returns the (possibly remapped) root NodeId to walk from.
11703fn lower_scans_for_backward(graph: &SharedGraph, root: NodeId) -> NodeId {
11704 use std::collections::HashMap;
11705 let mut root = root;
11706 // helper: apply a remap to every consumer's inputs + the root, in place.
11707 fn apply_remap(graph: &SharedGraph, remap: &HashMap<NodeId, NodeId>, root: &mut NodeId) {
11708 if remap.is_empty() {
11709 return;
11710 }
11711 let mut g = graph.write().unwrap();
11712 let n = g.len();
11713 for nid in 0..n {
11714 let ilen = g.node(NodeId(nid)).inputs.len();
11715 for i in 0..ilen {
11716 let cur = g.node(NodeId(nid)).inputs[i];
11717 if let Some(&new) = remap.get(&cur) {
11718 g.rewrite_input(NodeId(nid), cur, new);
11719 }
11720 }
11721 }
11722 if let Some(&new) = remap.get(root) {
11723 *root = new;
11724 }
11725 }
11726
11727 // --- Pass 1: decompose every reachable Op::Fused whose registry entry declares
11728 // `BackwardKind::Decompose` (the SSM recipes into Op::Scan, which pass 2 then
11729 // unrolls; single-output recipes such as NF4/AWQ matmul and causal conv1d
11730 // straight to primitives). The registry is the source of truth: an id with
11731 // a hand-written backward arm in the reverse walk is `Fused(..)` or
11732 // `NotDifferentiable` there, never `Decompose`.
11733 {
11734 let targets: Vec<(
11735 NodeId,
11736 crate::registry::FusedOpId,
11737 crate::registry::FusedOpParams,
11738 )> = {
11739 let g = graph.read().unwrap();
11740 crate::topo_order(&g, root)
11741 .into_iter()
11742 .filter_map(|id| match &g.node(id).op {
11743 Op::Fused(fid, params) if lowers_for_backward(*fid) => {
11744 Some((id, *fid, params.clone()))
11745 }
11746 _ => None,
11747 })
11748 .collect()
11749 };
11750 let mut remap = HashMap::new();
11751 for (id, fid, params) in targets {
11752 if let Some(entry) = crate::registry::default_registry().entry(fid) {
11753 let y = {
11754 let mut g = graph.write().unwrap();
11755 (entry.decompose)(&mut g, id, ¶ms)
11756 };
11757 if y != id {
11758 remap.insert(id, y);
11759 // Collapse the fused node's slot-0 View consumers DIRECTLY to
11760 // the decompose output. Slot 0 is the primary value (the
11761 // multi-output authoring contract: Node.shape == slot-0
11762 // shape), and the SSM decompose re-presents its primary AS
11763 // slot 0, so `View{0}(y) == y`. Without this collapse the
11764 // outer View{0} survives into the reverse walk and emits an
11765 // `Op::ScatterIntoSlot` (which has no CPU realize kernel),
11766 // so realizing the gradient would fail. Slot-1 (last_state)
11767 // consumers keep their `View{1}(y)` re-projection via the
11768 // default input rewrite (remap[id] = y) and are not
11769 // differentiated on this path.
11770 let g = graph.read().unwrap();
11771 for nid in 0..g.len() {
11772 let node = g.node(NodeId(nid));
11773 if let Op::View { slot: 0 } | Op::ViewOwned { slot: 0 } = node.op
11774 && node.inputs.first() == Some(&id)
11775 {
11776 remap.insert(NodeId(nid), y);
11777 }
11778 }
11779 }
11780 }
11781 }
11782 apply_remap(graph, &remap, &mut root);
11783 }
11784
11785 // --- Pass 2: unroll every reachable Op::Scan to `bound` primitives.
11786 loop {
11787 let scans: Vec<(NodeId, usize, ScanEmit)> = {
11788 let g = graph.read().unwrap();
11789 crate::topo_order(&g, root)
11790 .into_iter()
11791 .filter_map(|id| match &g.node(id).op {
11792 Op::Scan { bound, emit, .. } => Some((id, *bound, *emit)),
11793 _ => None,
11794 })
11795 .collect()
11796 };
11797 if scans.is_empty() {
11798 break;
11799 }
11800 let mut remap = HashMap::new();
11801 for (scan_id, bound, emit) in scans {
11802 let (a, b) = {
11803 let mut g = graph.write().unwrap();
11804 match crate::scan::unroll_scan(&mut g, scan_id, bound) {
11805 Ok(pair) => pair,
11806 Err(_) => continue, // malformed scan: leave it; the C4 guard describes it.
11807 }
11808 };
11809 // Normalize to (slot 0 = stacked_ys, slots 1.. = final carries).
11810 //
11811 // GAP-303: `unroll_scan` now returns (selected, complementary) as
11812 // VECS. The `ys` side is always exactly one node; the carry side is
11813 // `n_carries` wide. At `n_carries == 1` this is byte-for-byte the old
11814 // behaviour -- one ys, one carry, slot 1 the only carry slot.
11815 let (ys_v, carries) = match emit {
11816 ScanEmit::All => (a, b),
11817 ScanEmit::Final => (b, a),
11818 };
11819 let Some(&slot0) = ys_v.first() else {
11820 continue; // malformed: no stacked ys; the C4 guard describes it.
11821 };
11822 // Remap the scan's View{slot}/ViewOwned{slot} consumers to the unroll outputs.
11823 let g = graph.read().unwrap();
11824 for nid in 0..g.len() {
11825 let node = g.node(NodeId(nid));
11826 if let Op::View { slot } | Op::ViewOwned { slot } = node.op
11827 && node.inputs.first() == Some(&scan_id)
11828 {
11829 // ⚠️ Slot 0 is `ys`; slot k>=1 is carry k-1. The old form was
11830 // `if slot == 0 { slot0 } else { slot1 }`, which folded EVERY
11831 // slot above 0 onto the single carry -- a fifth site of the
11832 // 2-slot assumption. Out-of-range slots are LEFT UNMAPPED for
11833 // the C4 guard rather than indexed (never-panic).
11834 let target = if slot == 0 {
11835 Some(slot0)
11836 } else {
11837 carries.get(slot as usize - 1).copied()
11838 };
11839 if let Some(t) = target {
11840 remap.insert(NodeId(nid), t);
11841 }
11842 }
11843 }
11844 }
11845 // Defensive never-hang guard: if a full pass lowered no scan to a
11846 // consumer remap (e.g. a malformed scan that unroll rejects, or a raw
11847 // scan producer with no View consumers), stop rather than re-scanning
11848 // the same unchanged graph forever. Any residual Op::Scan then reaches
11849 // the C4 defensive `panic!` guard (backward is infallible, so it cannot
11850 // return an error) — an internal-bug signal, never an infinite loop.
11851 if remap.is_empty() {
11852 break;
11853 }
11854 apply_remap(graph, &remap, &mut root);
11855 // Unrolled graphs contain no Op::Scan, so a well-formed graph terminates
11856 // in <= 2 iterations (the loop re-scans in case a decomposed body itself
11857 // contained a scan; the current SSM decompose does not).
11858 }
11859 root
11860}
11861
11862/// Read a node's shape without holding the borrow past the call site.
11863fn node_shape(graph: &SharedGraph, id: NodeId) -> Shape {
11864 graph.read().unwrap().node(id).shape.clone()
11865}
11866
11867/// Read a node's dtype without holding the borrow past the call site.
11868fn node_dtype(graph: &SharedGraph, id: NodeId) -> DType {
11869 graph.read().unwrap().node(id).dtype
11870}
11871
11872/// Shape with its last two dims swapped. Used by MatMul's backward rule
11873/// to construct transpose-node output shapes for any rank ≥ 2.
11874fn transposed_shape(shape: &Shape) -> Shape {
11875 let d = shape.dims();
11876 assert!(
11877 d.len() >= 2,
11878 "transposed_shape: expected rank ≥ 2, got {d:?}",
11879 );
11880 let rank = d.len();
11881 let mut out: Vec<usize> = d.to_vec();
11882 out.swap(rank - 2, rank - 1);
11883 Shape::from_dims(&out)
11884}
11885
11886/// Given a full tensor shape and a dim that was reduced away, produce the
11887/// keepdim shape — i.e. the full shape with size 1 at `dim`. Used by
11888/// axis-reduction backward rules to reshape the reduced upstream back to
11889/// a shape that broadcasts against the original input.
11890fn reshape_to_keepdim(full_dims: &[usize], dim: usize) -> Shape {
11891 assert!(
11892 dim < full_dims.len(),
11893 "reshape_to_keepdim: dim {dim} out of bounds for {full_dims:?}",
11894 );
11895 let mut out: Vec<usize> = full_dims.to_vec();
11896 out[dim] = 1;
11897 Shape::from_dims(&out)
11898}
11899
11900/// Validate that `src` can be broadcast to `dst` using NumPy rules:
11901/// right-align, pad the shorter shape with 1s on the left, and for each
11902/// aligned dimension the src size must equal the dst size or be 1.
11903fn check_broadcast_compatible(src: &[usize], dst: &[usize]) {
11904 assert!(
11905 src.len() <= dst.len(),
11906 "broadcast_to: source rank {} exceeds target rank {}",
11907 src.len(),
11908 dst.len(),
11909 );
11910 let pad = dst.len() - src.len();
11911 for (i, &s) in src.iter().enumerate() {
11912 let d = dst[pad + i];
11913 assert!(
11914 s == d || s == 1,
11915 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11916 pad + i,
11917 );
11918 }
11919}
11920
11921/// Result-returning sibling of [`check_broadcast_compatible`].
11922fn try_check_broadcast_compatible(
11923 src: &[usize],
11924 dst: &[usize],
11925) -> std::result::Result<(), fuel_ir::Error> {
11926 if src.len() > dst.len() {
11927 return Err(fuel_ir::Error::Msg(format!(
11928 "broadcast_to: source rank {} exceeds target rank {}",
11929 src.len(),
11930 dst.len(),
11931 ))
11932 .bt());
11933 }
11934 let pad = dst.len() - src.len();
11935 for (i, &s) in src.iter().enumerate() {
11936 let d = dst[pad + i];
11937 if s != d && s != 1 {
11938 return Err(fuel_ir::Error::Msg(format!(
11939 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11940 pad + i,
11941 ))
11942 .bt());
11943 }
11944 }
11945 Ok(())
11946}
11947
11948/// Compute the NumPy broadcast shape of two input shapes. Right-align,
11949/// pad the shorter with leading 1s, and take the element-wise max at
11950/// each position. Panics if the shapes are incompatible (neither can
11951/// expand to match the other at some dim).
11952fn compute_broadcast_shape(a: &[usize], b: &[usize]) -> Vec<usize> {
11953 let n = a.len().max(b.len());
11954 let a_pad = n - a.len();
11955 let b_pad = n - b.len();
11956 let mut out = Vec::with_capacity(n);
11957 for i in 0..n {
11958 let ai = if i < a_pad { 1 } else { a[i - a_pad] };
11959 let bi = if i < b_pad { 1 } else { b[i - b_pad] };
11960 let oi = if ai == bi {
11961 ai
11962 } else if ai == 1 {
11963 bi
11964 } else if bi == 1 {
11965 ai
11966 } else {
11967 panic!(
11968 "compute_broadcast_shape: incompatible shapes {a:?} vs {b:?} at axis {i}: {ai} vs {bi}",
11969 );
11970 };
11971 out.push(oi);
11972 }
11973 out
11974}
11975
11976/// Push a node to the graph and return its ID. Used by backward to append
11977/// gradient-computing nodes without going through the public builders,
11978/// which would re-validate shapes the backward pass has already derived.
11979fn push_node(
11980 graph: &SharedGraph,
11981 op: Op,
11982 inputs: Vec<NodeId>,
11983 shape: Shape,
11984 dtype: DType,
11985) -> NodeId {
11986 graph.write().unwrap().push(Node {
11987 op,
11988 inputs,
11989 shape,
11990 dtype,
11991 })
11992}
11993
11994/// Build a ones tensor of the given shape and dtype as a `Const` node.
11995/// Used to seed the initial upstream gradient at the root of the backward
11996/// pass (`dL/dL = 1`).
11997/// Backward of the tanh-approximation GELU, `y = 0.5 x (1 + tanh(u))` with
11998/// `u = c (x + k x^3)`, `c = sqrt(2/pi)`, `k = 0.044715`:
11999///
12000/// `dy/dx = 0.5 (1 + t) + 0.5 x (1 - t^2) c (1 + 3 k x^2)`, `t = tanh(u)`.
12001///
12002/// Returns `upstream * dy/dx` as a new node. Built from existing primitives
12003/// (no new Op); `t` is recomputed from `x` so the rule is safe at `x = 0`.
12004fn build_gelu_tanh_grad(graph: &SharedGraph, x: NodeId, upstream: NodeId) -> NodeId {
12005 // sqrt(2/pi), the constant the forward kernels use.
12006 const C: f64 = 0.797_884_560_802_865_4;
12007 const K: f64 = 0.044_715;
12008 let shape = node_shape(graph, x);
12009 let dtype = node_dtype(graph, x);
12010 let un = |op: Op, input: NodeId| push_node(graph, op, vec![input], shape.clone(), dtype);
12011 let x_sq = un(Op::Sqr, x);
12012 let x_cu = push_node(graph, Op::Mul, vec![x_sq, x], shape.clone(), dtype);
12013 let k_x_cu = un(Op::MulScalar(K), x_cu);
12014 let inner = push_node(graph, Op::Add, vec![x, k_x_cu], shape.clone(), dtype);
12015 let u = un(Op::MulScalar(C), inner);
12016 let t = un(Op::Tanh, u);
12017 // 0.5 (1 + t)
12018 let t_plus_one = un(Op::AddScalar(1.0), t);
12019 let half_one_plus_t = un(Op::MulScalar(0.5), t_plus_one);
12020 // 1 - t^2
12021 let t_sq = un(Op::Sqr, t);
12022 let ones = build_ones(graph, shape.clone(), dtype);
12023 let one_minus_t_sq = push_node(graph, Op::Sub, vec![ones, t_sq], shape.clone(), dtype);
12024 // du/dx = c + 3 c k x^2
12025 let scaled_x_sq = un(Op::MulScalar(3.0 * C * K), x_sq);
12026 let du = un(Op::AddScalar(C), scaled_x_sq);
12027 // 0.5 x (1 - t^2) du/dx
12028 let dt = push_node(
12029 graph,
12030 Op::Mul,
12031 vec![one_minus_t_sq, du],
12032 shape.clone(),
12033 dtype,
12034 );
12035 let x_dt = push_node(graph, Op::Mul, vec![x, dt], shape.clone(), dtype);
12036 let half_x_dt = un(Op::MulScalar(0.5), x_dt);
12037 let d_gelu = push_node(
12038 graph,
12039 Op::Add,
12040 vec![half_one_plus_t, half_x_dt],
12041 shape.clone(),
12042 dtype,
12043 );
12044 push_node(graph, Op::Mul, vec![upstream, d_gelu], shape, dtype)
12045}
12046
12047fn build_ones(graph: &SharedGraph, shape: Shape, dtype: DType) -> NodeId {
12048 build_filled_const(graph, shape, dtype, 1.0)
12049}
12050
12051/// Build a constant tensor of the given shape and dtype filled with
12052/// `value` (expressed as `f64` and converted to the target dtype). Used
12053/// by backward rules that need a scalar-valued broadcast, for example
12054/// `MeanAll`'s `1/n` factor expressed as "divide by an n-filled const."
12055///
12056/// Build RoPE cos/sin tables for a given `(base, start_pos, seq,
12057/// head_dim)`. Each returned `Vec<f32>` has shape `[seq, head_dim]`
12058/// (row-major) in the half-split layout [`NodeHandle::rope_with_tables`]
12059/// expects: positions `[:, :half]` and `[:, half:]` hold the same
12060/// value for the same `(p, i)`, so a single elementwise multiply with
12061/// `self` does the right thing alongside `rotate_half(self) * sin`.
12062///
12063/// Exposed as a free function so callers can share the tables across
12064/// many RoPE applications (e.g. every attention layer in a transformer
12065/// forward pass).
12066pub fn build_rope_tables(
12067 base: f64,
12068 start_pos: usize,
12069 seq: usize,
12070 head_dim: usize,
12071) -> (Vec<f32>, Vec<f32>) {
12072 assert!(
12073 head_dim.is_multiple_of(2),
12074 "build_rope_tables: head_dim {head_dim} must be even",
12075 );
12076 let half = head_dim / 2;
12077 let inv_freq: Vec<f64> = (0..half)
12078 .map(|i| base.powf(-2.0 * (i as f64) / (head_dim as f64)))
12079 .collect();
12080 build_rope_tables_with_inv_freq(&inv_freq, start_pos, seq, head_dim)
12081}
12082
12083/// [`build_rope_tables`] with the inverse frequencies supplied directly rather
12084/// than derived from a single `base`.
12085///
12086/// Every RoPE variant Fuel supports differs from the default in **exactly** this
12087/// vector: LLaMA-3.1's long-context scaling is a per-dimension transform of the
12088/// same `head_dim / 2` values, and the position loop below is bit-identical
12089/// either way. Splitting the frequency choice out is what lets a scaled model
12090/// reuse the whole decode path — the KV-cache forward, the held-graph persistent
12091/// forward, and their per-token rebinds — instead of needing a parallel copy of
12092/// each.
12093///
12094/// `inv_freq.len()` must be `head_dim / 2`.
12095pub fn build_rope_tables_with_inv_freq(
12096 inv_freq: &[f64],
12097 start_pos: usize,
12098 seq: usize,
12099 head_dim: usize,
12100) -> (Vec<f32>, Vec<f32>) {
12101 assert!(
12102 head_dim.is_multiple_of(2),
12103 "build_rope_tables_with_inv_freq: head_dim {head_dim} must be even",
12104 );
12105 let half = head_dim / 2;
12106 assert_eq!(
12107 inv_freq.len(),
12108 half,
12109 "build_rope_tables_with_inv_freq: inv_freq len {} != head_dim/2 {half}",
12110 inv_freq.len(),
12111 );
12112 let mut cos_data = vec![0.0_f32; seq * head_dim];
12113 let mut sin_data = vec![0.0_f32; seq * head_dim];
12114 for p in 0..seq {
12115 let pos = (start_pos + p) as f64;
12116 for (i, &freq) in inv_freq.iter().enumerate() {
12117 let theta = pos * freq;
12118 let c = theta.cos() as f32;
12119 let s = theta.sin() as f32;
12120 cos_data[p * head_dim + i] = c;
12121 cos_data[p * head_dim + i + half] = c;
12122 sin_data[p * head_dim + i] = s;
12123 sin_data[p * head_dim + i + half] = s;
12124 }
12125 }
12126 (cos_data, sin_data)
12127}
12128
12129/// Only float dtypes are supported here — integer/index tensors never
12130/// appear as gradients, so a `U32` call indicates a bug in a backward
12131/// rule rather than a missing feature.
12132///
12133/// Phase 7.5 G2: gradient consts are slot-populating Op::Const
12134/// nodes. Device is picked from any existing slot (the forward pass
12135/// always populated at least one slot-bearing leaf by the time
12136/// backward runs). For a CPU-rooted graph the device's
12137/// `storage_from_host_buffer_owned_dyn` is a zero-copy wrap; for
12138/// GPU-rooted, an H2D upload (matching today's eval_const path on
12139/// first realize).
12140fn build_filled_const(graph: &SharedGraph, shape: Shape, dtype: DType, value: f64) -> NodeId {
12141 let n = shape.elem_count();
12142 let buf = match dtype {
12143 DType::F32 => fuel_ir::HostBuffer::F32(vec![value as f32; n]),
12144 DType::F64 => fuel_ir::HostBuffer::F64(vec![value; n]),
12145 DType::BF16 => fuel_ir::HostBuffer::BF16(vec![bf16::from_f64(value); n]),
12146 DType::F16 => fuel_ir::HostBuffer::F16(vec![f16::from_f64(value); n]),
12147 other => panic!(
12148 "backward: build_filled_const: unsupported dtype {other:?} \
12149 (gradients are always floats — this would indicate a bug in \
12150 a backward rule that tried to differentiate through an \
12151 integer tensor)",
12152 ),
12153 };
12154 let device = pick_device_from_graph(graph);
12155 let backend_storage = device
12156 .storage_from_host_buffer_owned_dyn(buf)
12157 .expect("build_filled_const: storage_from_host_buffer_owned_dyn failed");
12158 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
12159 let id = push_node(graph, Op::Const, vec![], shape, dtype);
12160 graph.write().unwrap().set_storage(id, storage_arc);
12161 id
12162}
12163
12164/// G2 helper: walk the graph for any populated slot and return its
12165/// device. Used by gradient builders that don't have an explicit
12166/// device parameter — the graph always has at least one slot-bearing
12167/// Const leaf by the time backward() runs (the forward pass's inputs
12168/// are slot-rooted Const leaves), so this can be relied on.
12169fn pick_device_from_graph(graph: &SharedGraph) -> Arc<dyn fuel_backend_contract::DynBackendDevice> {
12170 let g = graph.read().unwrap();
12171 for i in 0..g.len() {
12172 if let Some(slot_arc) = g.storage_for(NodeId(i)) {
12173 return slot_arc.read().unwrap().device();
12174 }
12175 }
12176 panic!(
12177 "build_filled_const: graph has no populated storage slots; backward \
12178 requires at least one slot-bearing Const leaf to pick a gradient \
12179 device from. Was the forward pass built with G2-migrated \
12180 constructors (from_f32/etc. with explicit &Device)?"
12181 )
12182}
12183
12184/// Accumulate a new gradient contribution into the upstream map.
12185///
12186/// If `forward_id` already has an upstream gradient, emit an `Add` node to
12187/// sum the two contributions. If not, record the new one as-is. This is
12188/// the multi-variable chain rule in its operational form: when a forward
12189/// node has multiple downstream consumers, the gradients from each must
12190/// be summed.
12191fn accumulate_grad(
12192 upstream: &mut HashMap<NodeId, NodeId>,
12193 forward_id: NodeId,
12194 new_grad_id: NodeId,
12195 graph: &SharedGraph,
12196) {
12197 match upstream.get(&forward_id).copied() {
12198 None => {
12199 upstream.insert(forward_id, new_grad_id);
12200 }
12201 Some(existing_id) => {
12202 let shape = node_shape(graph, forward_id);
12203 let dtype = node_dtype(graph, forward_id);
12204 let combined = push_node(graph, Op::Add, vec![existing_id, new_grad_id], shape, dtype);
12205 upstream.insert(forward_id, combined);
12206 }
12207 }
12208}
12209
12210#[cfg(test)]
12211mod tests {
12212 use super::*;
12213
12214 /// Phase 7.5 G2: tests need a real device to allocate slot
12215 /// storage through the new constructor API. `cpu_dev()` returns a
12216 /// stable singleton CpuBackendDevice handle so every call site can
12217 /// just pass `cpu_dev()` without per-test boilerplate.
12218 fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
12219 static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
12220 std::sync::OnceLock::new();
12221 D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
12222 }
12223
12224 /// `Tensor::awq_matmul`'s public builder end-to-end: a well-formed call
12225 /// produces a `Fused(AWQ_MATMUL, ..)` node with the right output
12226 /// shape/dtype. The decompose MATH is tested at the registry level
12227 /// (`registry::awq_matmul::tests`); this just confirms the builder's
12228 /// own validation + node construction work from the public API.
12229 #[test]
12230 fn awq_matmul_builder_produces_expected_node() {
12231 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12232 .unwrap();
12233 let qweight = act
12234 .const_u32_like(vec![0u32; 8], Shape::from_dims(&[8, 1]))
12235 .unwrap();
12236 let qzeros = act
12237 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12238 .unwrap();
12239 let scales = act
12240 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12241 .unwrap();
12242 let out = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12243 assert_eq!(out.shape().dims(), &[2, 8]);
12244 assert_eq!(out.dtype(), DType::F32);
12245 assert!(matches!(
12246 out.graph.read().unwrap().node(out.id).op,
12247 Op::Fused(id, _) if id == crate::registry::FusedOps::AWQ_MATMUL
12248 ));
12249 }
12250
12251 /// Born-red: a non-U32 `qweight` must panic with a clear message, not
12252 /// silently misinterpret bytes.
12253 #[test]
12254 #[should_panic(expected = "qweight must be U32")]
12255 fn awq_matmul_builder_panics_on_wrong_qweight_dtype() {
12256 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12257 .unwrap();
12258 let qweight = act
12259 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[8, 1]))
12260 .unwrap();
12261 let qzeros = act
12262 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12263 .unwrap();
12264 let scales = act
12265 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12266 .unwrap();
12267 let _ = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12268 }
12269
12270 #[test]
12271 fn builders_agree_with_primitive_shape() {
12272 // No-drift guard (Convergence A, Task 6): every routed builder's output
12273 // shape/dtype must equal primitive_shape's answer for the same Op. If a
12274 // builder's inline math ever diverged from primitive_shape, this fails.
12275 let x = NodeHandle::from_f32(
12276 vec![0.0_f32; 2 * 3 * 4],
12277 Shape::from_dims(&[2, 3, 4]),
12278 cpu_dev(),
12279 )
12280 .unwrap();
12281 let checks: Vec<(NodeHandle, Op)> = vec![
12282 (
12283 x.slice(1, 0, 2),
12284 Op::Slice {
12285 dim: 1,
12286 start: 0,
12287 len: 2,
12288 },
12289 ),
12290 (x.mean_dim(2), Op::MeanDim(2)),
12291 (
12292 x.try_permute(&[2, 0, 1]).unwrap(),
12293 Op::Permute(vec![2, 0, 1]),
12294 ),
12295 (x.cast(DType::F16), Op::Cast(DType::F16)),
12296 ];
12297 for (t, op) in checks {
12298 let (ps_shape, ps_dtype) =
12299 crate::shape::primitive_shape(&op, &[x.shape()], &[x.dtype()]).unwrap();
12300 assert_eq!(t.shape(), ps_shape, "shape drift for {op:?}");
12301 assert_eq!(t.dtype(), ps_dtype, "dtype drift for {op:?}");
12302 }
12303 }
12304
12305 #[test]
12306 fn destructive_input_release_is_some_zero() {
12307 assert_eq!(Op::Release.destructive_input(), Some(0));
12308 }
12309
12310 /// Phase 7.5 storage-unification B2: target_backend side-table
12311 /// is sparse — empty by default, set explicitly per node.
12312 #[test]
12313 fn target_backend_side_table_starts_empty() {
12314 let mut g = Graph::new();
12315 let id = g.push(Node {
12316 op: Op::Const,
12317 inputs: vec![],
12318 shape: Shape::from_dims(&[1]),
12319 dtype: DType::F32,
12320 });
12321 assert_eq!(g.target_backend(id), None);
12322 assert_eq!(g.target_backend_count(), 0);
12323 }
12324
12325 /// set_target_backend then read returns the same value.
12326 #[test]
12327 fn target_backend_set_and_read() {
12328 let mut g = Graph::new();
12329 let id = g.push(Node {
12330 op: Op::Const,
12331 inputs: vec![],
12332 shape: Shape::from_dims(&[1]),
12333 dtype: DType::F32,
12334 });
12335 g.set_target_backend(id, BackendId::Cpu);
12336 assert_eq!(g.target_backend(id), Some(BackendId::Cpu));
12337 assert_eq!(g.target_backend_count(), 1);
12338 }
12339
12340 /// set_target_backend overwrites prior value.
12341 #[test]
12342 fn target_backend_overwrite() {
12343 let mut g = Graph::new();
12344 let id = g.push(Node {
12345 op: Op::Const,
12346 inputs: vec![],
12347 shape: Shape::from_dims(&[1]),
12348 dtype: DType::F32,
12349 });
12350 g.set_target_backend(id, BackendId::Cpu);
12351 g.set_target_backend(id, BackendId::Cuda);
12352 assert_eq!(g.target_backend(id), Some(BackendId::Cuda));
12353 assert_eq!(g.target_backend_count(), 1);
12354 }
12355
12356 /// Layouts side-table: default fallback returns
12357 /// `Layout::contiguous(node.shape)` for any node without an
12358 /// explicit entry.
12359 #[test]
12360 fn layout_default_is_contiguous_over_node_shape() {
12361 let mut g = Graph::new();
12362 let id = g.push(Node {
12363 op: Op::Const,
12364 inputs: vec![],
12365 shape: Shape::from_dims(&[2, 3]),
12366 dtype: DType::F32,
12367 });
12368 assert!(!g.has_explicit_layout(id));
12369 assert_eq!(g.explicit_layout_count(), 0);
12370 let l = g.layout(id);
12371 assert_eq!(l.shape().dims(), &[2, 3]);
12372 assert!(l.is_contiguous());
12373 assert_eq!(l.start_offset(), 0);
12374 }
12375
12376 /// set_layout records a strided Layout (e.g. for a transpose
12377 /// view). Subsequent reads return the explicit entry.
12378 #[test]
12379 fn layout_explicit_strided_is_remembered() {
12380 let mut g = Graph::new();
12381 let id = g.push(Node {
12382 op: Op::Transpose,
12383 inputs: vec![],
12384 shape: Shape::from_dims(&[3, 2]),
12385 dtype: DType::F32,
12386 });
12387 // Strided view: shape stays [3, 2] (the post-transpose view),
12388 // strides are [1, 3] (row-of-output is column-of-source).
12389 let l = Layout::new(
12390 Shape::from_dims(&[3, 2]),
12391 fuel_ir::StrideVec::from_slice(&[1_isize, 3]),
12392 0,
12393 );
12394 g.set_layout(id, l);
12395 assert!(g.has_explicit_layout(id));
12396 assert_eq!(g.explicit_layout_count(), 1);
12397 assert_eq!(g.layout(id).stride(), &[1, 3]);
12398 assert!(!g.layout(id).is_contiguous());
12399 }
12400
12401 /// set_layout twice with different layouts overwrites.
12402 #[test]
12403 fn layout_set_overwrites() {
12404 use fuel_ir::StrideVec;
12405 let mut g = Graph::new();
12406 let id = g.push(Node {
12407 op: Op::Transpose,
12408 inputs: vec![],
12409 shape: Shape::from_dims(&[2]),
12410 dtype: DType::F32,
12411 });
12412 g.set_layout(id, Layout::contiguous(Shape::from_dims(&[2])));
12413 g.set_layout(
12414 id,
12415 Layout::new(Shape::from_dims(&[2]), StrideVec::from_slice(&[3_isize]), 1),
12416 );
12417 assert_eq!(g.layout(id).start_offset(), 1);
12418 assert_eq!(g.explicit_layout_count(), 1);
12419 }
12420
12421 /// Phase 7.5 work item G — empty-map invariants. End-to-end
12422 /// tests of the storage map (with real `Storage` values) live in
12423 /// fuel-core's `tensor::node_handle_tests`, since constructing a
12424 /// real `Storage` requires a `DynBackendStorage` implementation
12425 /// from a backend crate, and fuel-graph deliberately depends only
12426 /// on fuel-core-types.
12427 #[test]
12428 fn graph_storage_map_starts_empty() {
12429 let g = Graph::new();
12430 assert_eq!(g.storage_len(), 0);
12431 assert!(!g.has_storage(NodeId(0)));
12432 assert!(g.storage_for(NodeId(0)).is_none());
12433 }
12434
12435 #[test]
12436 fn conv2d_builder_emits_conv2d_node_with_right_shape() {
12437 // k=3 s=1 p=1 keeps H and W.
12438 let x = NodeHandle::from_f32(
12439 vec![0.0_f32; 2 * 4 * 4],
12440 Shape::from_dims(&[1, 2, 4, 4]),
12441 cpu_dev(),
12442 )
12443 .unwrap();
12444 let w = x
12445 .const_f32_like(
12446 vec![0.0_f32; 3 * 2 * 3 * 3],
12447 Shape::from_dims(&[3, 2, 3, 3]),
12448 )
12449 .unwrap();
12450 let b = x
12451 .const_f32_like(vec![0.0_f32; 3], Shape::from_dims(&[3]))
12452 .unwrap();
12453 let y = x.conv2d(&w, Some(&b), (1, 1), (1, 1), 1);
12454 assert_eq!(y.shape().dims(), &[1, 3, 4, 4]);
12455 }
12456
12457 #[test]
12458 fn conv2d_builder_stride_and_no_padding() {
12459 // k=3 s=2 p=0 on H=W=8 gives (8-3)/2+1 = 3.
12460 let x = NodeHandle::from_f32(
12461 vec![0.0_f32; 2 * 8 * 8],
12462 Shape::from_dims(&[1, 2, 8, 8]),
12463 cpu_dev(),
12464 )
12465 .unwrap();
12466 let w = x
12467 .const_f32_like(
12468 vec![0.0_f32; 4 * 2 * 3 * 3],
12469 Shape::from_dims(&[4, 2, 3, 3]),
12470 )
12471 .unwrap();
12472 let y = x.conv2d(&w, None, (2, 2), (0, 0), 1);
12473 assert_eq!(y.shape().dims(), &[1, 4, 3, 3]);
12474 }
12475
12476 #[test]
12477 fn conv2d_builder_depthwise_groups() {
12478 // groups=Cin=Cout=4 is the depthwise case. Weight per channel is [Cin/groups=1, kH, kW].
12479 let x = NodeHandle::from_f32(
12480 vec![0.0_f32; 4 * 4 * 4],
12481 Shape::from_dims(&[1, 4, 4, 4]),
12482 cpu_dev(),
12483 )
12484 .unwrap();
12485 let w = x
12486 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 1, 3, 3]))
12487 .unwrap();
12488 let y = x.conv2d(&w, None, (1, 1), (1, 1), 4);
12489 assert_eq!(y.shape().dims(), &[1, 4, 4, 4]);
12490 }
12491
12492 #[test]
12493 fn conv_transpose2d_builder_emits_node_with_right_shape() {
12494 // Hin=4, Kh=3, s=2, pad=1, out_pad=1 → Hout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12495 let x = NodeHandle::from_f32(
12496 vec![0.0_f32; 2 * 4 * 4],
12497 Shape::from_dims(&[1, 2, 4, 4]),
12498 cpu_dev(),
12499 )
12500 .unwrap();
12501 let w = x
12502 .const_f32_like(
12503 vec![0.0_f32; 2 * 3 * 3 * 3],
12504 Shape::from_dims(&[2, 3, 3, 3]),
12505 )
12506 .unwrap();
12507 let y = x.conv_transpose2d(&w, (2, 2), (1, 1), (1, 1), (1, 1), 1);
12508 assert_eq!(y.shape().dims(), &[1, 3, 8, 8]);
12509 }
12510
12511 #[test]
12512 fn conv_transpose1d_builder_shape_stride_2_pad_1() {
12513 // Lin=4, K=3, s=2, pad=1, out_pad=1, dil=1
12514 // Lout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12515 let x = NodeHandle::from_f32(
12516 vec![0.0_f32; 2 * 4],
12517 Shape::from_dims(&[1, 2, 4]),
12518 cpu_dev(),
12519 )
12520 .unwrap();
12521 let w = x
12522 .const_f32_like(vec![0.0_f32; 2 * 3 * 3], Shape::from_dims(&[2, 3, 3]))
12523 .unwrap();
12524 let y = x.conv_transpose1d(&w, 2, 1, 1, 1, 1);
12525 assert_eq!(y.shape().dims(), &[1, 3, 8]);
12526 }
12527
12528 #[test]
12529 fn conv_transpose1d_builder_shape_stride_4_no_pad() {
12530 // Lin=2, K=4, s=4, pad=0, out_pad=0, dil=1
12531 // Lout = (2-1)*4 + (4-1) + 0 + 1 - 0 = 8.
12532 let x = NodeHandle::from_f32(vec![0.0_f32; 2], Shape::from_dims(&[1, 1, 2]), cpu_dev())
12533 .unwrap();
12534 let w = x
12535 .const_f32_like(vec![0.0_f32; 4], Shape::from_dims(&[1, 1, 4]))
12536 .unwrap();
12537 let y = x.conv_transpose1d(&w, 4, 0, 0, 1, 1);
12538 assert_eq!(y.shape().dims(), &[1, 1, 8]);
12539 }
12540
12541 #[test]
12542 fn conv_transpose1d_builder_with_groups() {
12543 // groups=2: input Cin=4 splits into 2 groups of 2; weight
12544 // Cin=4 first dim matches input; Cout/group=3 → total Cout=6.
12545 // Lin=3, K=3, s=1, pad=0, out_pad=0, dil=1 → Lout = (3-1)*1 + 2 + 0 + 1 = 5.
12546 let x = NodeHandle::from_f32(
12547 vec![0.0_f32; 4 * 3],
12548 Shape::from_dims(&[1, 4, 3]),
12549 cpu_dev(),
12550 )
12551 .unwrap();
12552 let w = x
12553 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 3, 3]))
12554 .unwrap();
12555 let y = x.conv_transpose1d(&w, 1, 0, 0, 1, 2);
12556 assert_eq!(y.shape().dims(), &[1, 6, 5]);
12557 }
12558
12559 #[test]
12560 fn conv2d_backward_grads_have_input_shapes() {
12561 // Forward Y = conv2d(X, W) with stride=1, pad=1, groups=1 keeps H,W.
12562 // Backward should produce dX with X's shape and dW with W's shape.
12563 let x = NodeHandle::from_f32(
12564 (0..(2 * 4 * 4))
12565 .map(|i| (i as f32) * 0.05 - 0.5)
12566 .collect::<Vec<f32>>(),
12567 Shape::from_dims(&[1, 2, 4, 4]),
12568 cpu_dev(),
12569 )
12570 .unwrap();
12571 let w = x
12572 .const_f32_like(
12573 (0..(3 * 2 * 3 * 3))
12574 .map(|i| (i as f32) * 0.07 - 0.4)
12575 .collect::<Vec<f32>>(),
12576 Shape::from_dims(&[3, 2, 3, 3]),
12577 )
12578 .unwrap();
12579 let y = x.conv2d(&w, None, (1, 1), (1, 1), 1);
12580 let scalar_out = y.sum_all();
12581 let grads = scalar_out.backward();
12582 let dx = grads.get(&x).expect("conv2d backward produced no dX");
12583 let dw = grads.get(&w).expect("conv2d backward produced no dW");
12584 assert_eq!(dx.shape().dims(), x.shape().dims());
12585 assert_eq!(dw.shape().dims(), w.shape().dims());
12586 }
12587
12588 #[test]
12589 fn destructive_input_move_is_some_zero() {
12590 assert_eq!(
12591 Op::Move {
12592 target: DeviceLocation::Cpu
12593 }
12594 .destructive_input(),
12595 Some(0)
12596 );
12597 }
12598
12599 #[test]
12600 fn destructive_input_non_destructive_ops_are_none() {
12601 assert_eq!(
12602 Op::Copy {
12603 target: DeviceLocation::Cpu
12604 }
12605 .destructive_input(),
12606 None
12607 );
12608 assert_eq!(Op::Add.destructive_input(), None);
12609 assert_eq!(Op::Mul.destructive_input(), None);
12610 assert_eq!(Op::MatMul.destructive_input(), None);
12611 assert_eq!(Op::Relu.destructive_input(), None);
12612 }
12613
12614 #[test]
12615 fn move_to_device_emits_op_move_node() {
12616 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12617 let moved = a.move_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12618 let g = moved.graph().read().unwrap();
12619 match &g.node(moved.id()).op {
12620 Op::Move { target } => {
12621 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12622 }
12623 other => panic!("expected Op::Move, got {other:?}"),
12624 }
12625 assert_eq!(g.node(moved.id()).inputs, vec![a.id()]);
12626 // Output has the input's shape (residency changes, data doesn't).
12627 assert_eq!(g.node(moved.id()).shape.elem_count(), 2);
12628 }
12629
12630 #[test]
12631 fn copy_to_device_emits_op_copy_node() {
12632 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12633 let b = a.copy_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12634 let g = b.graph().read().unwrap();
12635 match &g.node(b.id()).op {
12636 Op::Copy { target } => {
12637 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12638 }
12639 other => panic!("expected Op::Copy, got {other:?}"),
12640 }
12641 // Source stays resident: the original `a` node still in the graph
12642 // and is the input of the Copy node.
12643 assert_eq!(g.node(b.id()).inputs, vec![a.id()]);
12644 }
12645
12646 #[test]
12647 fn release_builder_emits_op_release_node() {
12648 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12649 let released = a.release();
12650 let g = released.graph().read().unwrap();
12651 assert!(matches!(g.node(released.id()).op, Op::Release));
12652 assert_eq!(g.node(released.id()).inputs, vec![a.id()]);
12653 // Output is a zero-element marker.
12654 assert_eq!(g.node(released.id()).shape.elem_count(), 0);
12655 }
12656
12657 #[test]
12658 fn placement_is_none_by_default() {
12659 let a =
12660 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12661 assert_eq!(a.placement(), None);
12662 }
12663
12664 #[test]
12665 fn on_device_sets_placement_hint() {
12666 let a =
12667 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12668 let b = a
12669 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12670 .unwrap();
12671 // Only tag the Add node; the const leaves remain unplaced.
12672 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
12673 assert_eq!(c.placement(), Some(DeviceLocation::Vulkan { gpu_id: 0 }));
12674 assert_eq!(a.placement(), None);
12675 assert_eq!(b.placement(), None);
12676 }
12677
12678 #[test]
12679 fn placement_survives_graph_re_reads() {
12680 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12681 let tagged = a.clone().on_device(DeviceLocation::Cpu);
12682 // Re-read from a fresh borrow — round-trips through the side-table.
12683 assert_eq!(
12684 tagged.graph().read().unwrap().placement(tagged.id()),
12685 Some(DeviceLocation::Cpu)
12686 );
12687 }
12688
12689 #[test]
12690 fn from_f32_creates_single_const_node() {
12691 let a =
12692 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12693 assert_eq!(a.graph().read().unwrap().len(), 1);
12694 assert_eq!(a.shape().dims(), &[3]);
12695 assert_eq!(a.dtype(), DType::F32);
12696 let node = a.graph().read().unwrap().node(a.id()).clone();
12697 // Phase 7.5 G2: factory now emits Op::Const + slot.
12698 assert!(matches!(node.op, Op::Const));
12699 assert!(node.inputs.is_empty());
12700 // The slot is populated with F32 storage.
12701 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12702 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
12703 }
12704
12705 #[test]
12706 fn add_appends_a_node_and_tracks_inputs() {
12707 let a =
12708 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12709 let b = a
12710 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12711 .unwrap();
12712 let c = a.add(&b);
12713 assert_eq!(c.graph().read().unwrap().len(), 3); // const, const, add
12714 let node = c.graph().read().unwrap().node(c.id()).clone();
12715 assert!(matches!(node.op, Op::Add));
12716 assert_eq!(node.inputs.len(), 2);
12717 assert_eq!(node.inputs[0], a.id());
12718 assert_eq!(node.inputs[1], b.id());
12719 assert_eq!(c.shape().dims(), &[3]);
12720 }
12721
12722 #[test]
12723 fn chained_ops_all_share_one_graph() {
12724 let a =
12725 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12726 let b = a
12727 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12728 .unwrap();
12729 let c = a.add(&b).mul(&a).sqr().relu();
12730 assert_eq!(c.graph().read().unwrap().len(), 6); // 2 consts + add + mul + sqr + relu
12731 assert_eq!(c.shape().dims(), &[3]);
12732 }
12733
12734 #[test]
12735 fn matmul_validates_shapes_and_produces_correct_output_shape() {
12736 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12737 let b = a
12738 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
12739 .unwrap();
12740 let c = a.matmul(&b);
12741 assert_eq!(c.shape().dims(), &[2, 4]);
12742 }
12743
12744 #[test]
12745 #[should_panic(expected = "shape mismatch")]
12746 fn add_panics_on_shape_mismatch() {
12747 let a =
12748 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12749 let b = a
12750 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12751 .unwrap();
12752 let _ = a.add(&b);
12753 }
12754
12755 #[test]
12756 #[should_panic(expected = "inner dim mismatch")]
12757 fn matmul_panics_on_inner_dim_mismatch() {
12758 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12759 let b = a
12760 .const_f32_like(vec![1.0; 8], Shape::from_dims(&[4, 2]))
12761 .unwrap();
12762 let _ = a.matmul(&b);
12763 }
12764
12765 #[test]
12766 #[should_panic(expected = "must live on the same graph")]
12767 fn cross_graph_op_is_rejected() {
12768 let a =
12769 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12770 let b =
12771 NodeHandle::from_f32(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12772 let _ = a.add(&b);
12773 }
12774
12775 // ----- graph identity + graph-scoped construction -----
12776 //
12777 // Two changes land together: (1) every Graph carries a monotonic GraphId so
12778 // an affinity failure can name WHICH graphs rather than only that they
12779 // differ; (2) constructors accept an existing graph, so a consumer never has
12780 // to discover `const_*_like` to build a second tensor.
12781
12782 #[test]
12783 fn each_new_graph_gets_a_distinct_id() {
12784 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12785 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12786 assert_ne!(a.graph_id(), b.graph_id());
12787 }
12788
12789 #[test]
12790 fn same_graph_tensors_share_one_id() {
12791 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12792 let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
12793 assert_eq!(a.graph_id(), b.graph_id());
12794 }
12795
12796 #[test]
12797 fn affinity_panic_names_both_graph_ids() {
12798 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12799 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12800 let (ia, ib) = (a.graph_id(), b.graph_id());
12801 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| a.add(&b)))
12802 .expect_err("cross-graph add must panic");
12803 let text = err
12804 .downcast_ref::<String>()
12805 .cloned()
12806 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
12807 .expect("panic payload is a string");
12808 assert!(
12809 text.contains(&format!("#{ia}")) && text.contains(&format!("#{ib}")),
12810 "affinity panic must name BOTH graph ids so the caller can see it made two; got: {text}",
12811 );
12812 }
12813
12814 #[test]
12815 fn from_f32_on_builds_into_the_given_graph() {
12816 let root =
12817 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12818 let w = NodeHandle::from_f32_on(
12819 root.graph(),
12820 vec![4.0, 5.0, 6.0],
12821 Shape::from_dims(&[3]),
12822 cpu_dev(),
12823 )
12824 .unwrap();
12825 assert_eq!(root.graph_id(), w.graph_id());
12826 assert!(Arc::ptr_eq(root.graph(), w.graph()));
12827 }
12828
12829 #[test]
12830 fn graph_scoped_construction_composes_without_an_anchor() {
12831 // The program that could not previously be written: build two tensors
12832 // and combine them, without discovering `const_*_like`.
12833 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12834 let a = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev())
12835 .unwrap();
12836 let b = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[3, 2]), cpu_dev())
12837 .unwrap();
12838 let y = a.matmul(&b);
12839 assert_eq!(y.shape().dims(), &[2, 2]);
12840 assert_eq!(y.graph_id(), a.graph_id());
12841 }
12842
12843 #[test]
12844 fn graph_scoped_constructors_cover_every_dtype() {
12845 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12846 let s = Shape::from_dims(&[1]);
12847 let f32t = NodeHandle::from_f32_on(&g, vec![1.0f32], s.clone(), cpu_dev()).unwrap();
12848 let f64t = NodeHandle::from_f64_on(&g, vec![1.0f64], s.clone(), cpu_dev()).unwrap();
12849 let bf16t =
12850 NodeHandle::from_bf16_on(&g, vec![half::bf16::from_f32(1.0)], s.clone(), cpu_dev())
12851 .unwrap();
12852 let f16t =
12853 NodeHandle::from_f16_on(&g, vec![half::f16::from_f32(1.0)], s.clone(), cpu_dev())
12854 .unwrap();
12855 let u32t = NodeHandle::from_u32_on(&g, vec![1u32], s, cpu_dev()).unwrap();
12856 for t in [&f64t, &bf16t, &f16t, &u32t] {
12857 assert_eq!(
12858 t.graph_id(),
12859 f32t.graph_id(),
12860 "all must share the given graph"
12861 );
12862 }
12863 assert_eq!(f64t.dtype(), DType::F64);
12864 assert_eq!(bf16t.dtype(), DType::BF16);
12865 assert_eq!(f16t.dtype(), DType::F16);
12866 assert_eq!(u32t.dtype(), DType::U32);
12867 }
12868
12869 // ----- multi-dtype graph builders -----
12870
12871 #[test]
12872 fn from_f64_tags_node_with_f64_dtype() {
12873 let a =
12874 NodeHandle::from_f64(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12875 assert_eq!(a.dtype(), DType::F64);
12876 let node = a.graph().read().unwrap().node(a.id()).clone();
12877 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
12878 assert!(matches!(node.op, Op::Const));
12879 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12880 assert_eq!(slot.read().unwrap().dtype(), DType::F64);
12881 }
12882
12883 #[test]
12884 fn from_bf16_tags_node_with_bf16_dtype() {
12885 let a = NodeHandle::from_bf16(
12886 vec![bf16::from_f32(1.0), bf16::from_f32(2.0)],
12887 Shape::from_dims(&[2]),
12888 cpu_dev(),
12889 )
12890 .unwrap();
12891 assert_eq!(a.dtype(), DType::BF16);
12892 let node = a.graph().read().unwrap().node(a.id()).clone();
12893 assert!(matches!(node.op, Op::Const));
12894 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12895 assert_eq!(slot.read().unwrap().dtype(), DType::BF16);
12896 }
12897
12898 #[test]
12899 fn from_f16_tags_node_with_f16_dtype() {
12900 let a = NodeHandle::from_f16(
12901 vec![f16::from_f32(1.0), f16::from_f32(2.0)],
12902 Shape::from_dims(&[2]),
12903 cpu_dev(),
12904 )
12905 .unwrap();
12906 assert_eq!(a.dtype(), DType::F16);
12907 let node = a.graph().read().unwrap().node(a.id()).clone();
12908 assert!(matches!(node.op, Op::Const));
12909 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12910 assert_eq!(slot.read().unwrap().dtype(), DType::F16);
12911 }
12912
12913 #[test]
12914 #[should_panic(expected = "dtype mismatch")]
12915 fn add_panics_on_mixed_dtype() {
12916 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12917 let b = a
12918 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12919 .unwrap();
12920 let _ = a.add(&b);
12921 }
12922
12923 // ----- transpose -----
12924
12925 #[test]
12926 fn transpose_swaps_shape_dims() {
12927 let a = NodeHandle::from_f32(
12928 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
12929 Shape::from_dims(&[2, 3]),
12930 cpu_dev(),
12931 )
12932 .unwrap();
12933 let t = a.transpose();
12934 assert_eq!(t.shape().dims(), &[3, 2]);
12935 let node = t.graph().read().unwrap().node(t.id()).clone();
12936 assert!(matches!(node.op, Op::Transpose));
12937 assert_eq!(node.inputs, vec![a.id()]);
12938 }
12939
12940 #[test]
12941 #[should_panic(expected = "rank ≥ 2")]
12942 fn transpose_rejects_rank_1() {
12943 let a =
12944 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12945 let _ = a.transpose();
12946 }
12947
12948 #[test]
12949 fn transpose_on_rank_3_swaps_last_two_dims() {
12950 // [2, 3, 4] → [2, 4, 3]
12951 let a = NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev())
12952 .unwrap();
12953 let t = a.transpose();
12954 assert_eq!(t.shape().dims(), &[2, 4, 3]);
12955 }
12956
12957 // ----- additional builder validation tests -----
12958
12959 #[test]
12960 fn matmul_rank_3_batched_shape() {
12961 // [2, 3, 4] @ [2, 4, 5] → [2, 3, 5]
12962 let a =
12963 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12964 let b = a
12965 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12966 .unwrap();
12967 let c = a.matmul(&b);
12968 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12969 }
12970
12971 #[test]
12972 #[should_panic(expected = "batch dim mismatch")]
12973 fn matmul_rank_3_rejects_batch_dim_mismatch() {
12974 let a =
12975 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12976 let b = a
12977 .const_f32_like(vec![0.0; 60], Shape::from_dims(&[3, 4, 5]))
12978 .unwrap();
12979 let _ = a.matmul(&b);
12980 }
12981
12982 #[test]
12983 fn matmul_auto_broadcasts_rank_2_rhs_against_batched_lhs() {
12984 // [batch=2, seq=3, k=4] @ [k=4, n=5] → [2, 3, 5]. This is the
12985 // canonical "linear layer across a batch" pattern and should
12986 // Just Work without an explicit broadcast_to on the RHS.
12987 let a =
12988 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12989 let b = a
12990 .const_f32_like(vec![0.0; 20], Shape::from_dims(&[4, 5]))
12991 .unwrap();
12992 let c = a.matmul(&b);
12993 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12994 }
12995
12996 #[test]
12997 fn matmul_auto_broadcasts_rank_2_lhs_against_batched_rhs() {
12998 // [m=3, k=4] @ [batch=2, k=4, n=5] → [2, 3, 5].
12999 let a = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13000 let b = a
13001 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
13002 .unwrap();
13003 let c = a.matmul(&b);
13004 assert_eq!(c.shape().dims(), &[2, 3, 5]);
13005 }
13006
13007 #[test]
13008 fn concat_output_shape_sums_along_dim() {
13009 // [2, 3] concat [2, 4] along dim 1 → [2, 7]
13010 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13011 let b = a
13012 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13013 .unwrap();
13014 let c = a.concat(&b, 1);
13015 assert_eq!(c.shape().dims(), &[2, 7]);
13016 }
13017
13018 #[test]
13019 #[should_panic(expected = "non-dim shapes")]
13020 fn concat_rejects_nondim_shape_mismatch() {
13021 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13022 let b = a
13023 .const_f32_like(vec![0.0; 12], Shape::from_dims(&[3, 4]))
13024 .unwrap();
13025 let _ = a.concat(&b, 1);
13026 }
13027
13028 #[test]
13029 #[should_panic(expected = "rank mismatch")]
13030 fn concat_rejects_rank_mismatch() {
13031 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13032 let b = a
13033 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[6]))
13034 .unwrap();
13035 let _ = a.concat(&b, 0);
13036 }
13037
13038 #[test]
13039 fn slice_shrinks_only_the_slice_dim() {
13040 // [3, 4] slice dim 1, start 1, len 2 → [3, 2]
13041 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13042 let s = x.slice(1, 1, 2);
13043 assert_eq!(s.shape().dims(), &[3, 2]);
13044 }
13045
13046 #[test]
13047 #[should_panic(expected = "exceeds dim size")]
13048 fn slice_rejects_out_of_bounds_range() {
13049 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13050 let _ = x.slice(1, 1, 3); // start=1, len=3 → would need dim>=4
13051 }
13052
13053 #[test]
13054 fn broadcast_add_shape_promotes_to_common_shape() {
13055 // [4, 1] + [1, 3] → [4, 3]
13056 let a = NodeHandle::from_f32(vec![0.0; 4], Shape::from_dims(&[4, 1]), cpu_dev()).unwrap();
13057 let b = a
13058 .const_f32_like(vec![0.0; 3], Shape::from_dims(&[1, 3]))
13059 .unwrap();
13060 let c = a.broadcast_add(&b);
13061 assert_eq!(c.shape().dims(), &[4, 3]);
13062 }
13063
13064 #[test]
13065 fn broadcast_sub_pads_shorter_shape_with_leading_ones() {
13066 // [3] - [2, 3] → [2, 3]
13067 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13068 let b = a
13069 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[2, 3]))
13070 .unwrap();
13071 let c = a.broadcast_sub(&b);
13072 assert_eq!(c.shape().dims(), &[2, 3]);
13073 }
13074
13075 #[test]
13076 #[should_panic(expected = "incompatible shapes")]
13077 fn broadcast_add_rejects_incompatible_shapes() {
13078 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13079 let b = a
13080 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13081 .unwrap();
13082 let _ = a.broadcast_add(&b);
13083 }
13084
13085 #[test]
13086 fn argmax_dim_is_u32_and_removes_reduced_dim() {
13087 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13088 let am = x.argmax_dim(1);
13089 assert_eq!(am.dtype(), DType::U32);
13090 assert_eq!(am.shape().dims(), &[2]);
13091 }
13092
13093 #[test]
13094 #[should_panic(expected = "out of bounds")]
13095 fn argmax_dim_rejects_bad_dim() {
13096 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13097 let _ = x.argmax_dim(5);
13098 }
13099
13100 #[test]
13101 fn index_add_shape_validation() {
13102 let base = NodeHandle::from_f32(vec![0.0; 10], Shape::from_dims(&[10]), cpu_dev()).unwrap();
13103 let idx = base
13104 .const_u32_like(vec![1, 3, 5], Shape::from_dims(&[3]))
13105 .unwrap();
13106 let src = base
13107 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13108 .unwrap();
13109 let out = base.index_add(0, &idx, &src);
13110 assert_eq!(out.shape().dims(), &[10]);
13111 }
13112
13113 #[test]
13114 #[should_panic(expected = "dtypes must match")]
13115 fn index_add_rejects_dtype_mismatch() {
13116 let base = NodeHandle::from_f32(vec![0.0; 5], Shape::from_dims(&[5]), cpu_dev()).unwrap();
13117 let idx = base
13118 .const_u32_like(vec![0, 2], Shape::from_dims(&[2]))
13119 .unwrap();
13120 let src = base
13121 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13122 .unwrap();
13123 let _ = base.index_add(0, &idx, &src);
13124 }
13125
13126 #[test]
13127 fn scatter_add_validates_index_matches_src() {
13128 let base =
13129 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13130 let idx = base
13131 .const_u32_like(vec![0, 2, 1, 0], Shape::from_dims(&[2, 2]))
13132 .unwrap();
13133 let src = base
13134 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13135 .unwrap();
13136 let out = base.scatter_add(1, &idx, &src);
13137 assert_eq!(out.shape().dims(), &[2, 3]);
13138 }
13139
13140 #[test]
13141 #[should_panic(expected = "same shape")]
13142 fn scatter_add_rejects_index_src_shape_mismatch() {
13143 let base =
13144 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13145 let idx = base
13146 .const_u32_like(vec![0, 1], Shape::from_dims(&[2]))
13147 .unwrap();
13148 let src = base
13149 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13150 .unwrap();
13151 let _ = base.scatter_add(1, &idx, &src);
13152 }
13153
13154 #[test]
13155 fn reduce_sum_to_validates_compatibility() {
13156 // [3, 4] can reduce to [4] (sum along dim 0) or [3, 1] (sum along dim 1).
13157 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13158 let r1 = x.reduce_sum_to(Shape::from_dims(&[4]));
13159 assert_eq!(r1.shape().dims(), &[4]);
13160 let r2 = x.reduce_sum_to(Shape::from_dims(&[3, 1]));
13161 assert_eq!(r2.shape().dims(), &[3, 1]);
13162 }
13163
13164 #[test]
13165 #[should_panic(expected = "incompatible")]
13166 fn reduce_sum_to_rejects_non_broadcast_target() {
13167 // [3, 4] cannot reduce to [3, 2] — target must be broadcast-into-source.
13168 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13169 let _ = x.reduce_sum_to(Shape::from_dims(&[3, 2]));
13170 }
13171
13172 #[test]
13173 fn unsqueeze_inserts_size_one_dim() {
13174 let x = NodeHandle::from_f32(
13175 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13176 Shape::from_dims(&[2, 3]),
13177 cpu_dev(),
13178 )
13179 .unwrap();
13180 // Insert at position 0: [2, 3] -> [1, 2, 3]
13181 let y0 = x.unsqueeze(0);
13182 assert_eq!(y0.shape().dims(), &[1, 2, 3]);
13183 // Insert at position 1: [2, 3] -> [2, 1, 3]
13184 let y1 = x.unsqueeze(1);
13185 assert_eq!(y1.shape().dims(), &[2, 1, 3]);
13186 // Insert at the end (rank): [2, 3] -> [2, 3, 1]
13187 let y2 = x.unsqueeze(2);
13188 assert_eq!(y2.shape().dims(), &[2, 3, 1]);
13189 // Op variant correctness.
13190 let g = x.graph().read().unwrap();
13191 assert!(matches!(g.node(y0.id()).op, Op::Unsqueeze { dim: 0 }));
13192 assert!(matches!(g.node(y1.id()).op, Op::Unsqueeze { dim: 1 }));
13193 assert!(matches!(g.node(y2.id()).op, Op::Unsqueeze { dim: 2 }));
13194 }
13195
13196 #[test]
13197 #[should_panic(expected = "out of bounds")]
13198 fn unsqueeze_rejects_dim_above_rank() {
13199 let x = NodeHandle::from_f32(vec![1.0; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
13200 // dim=2 > rank=1 → panic.
13201 let _ = x.unsqueeze(2);
13202 }
13203
13204 #[test]
13205 fn unsqueeze_layout_side_table_populated() {
13206 // After Graph::push auto-derives the Layout side-table for view
13207 // ops, an unsqueeze node should have an explicit layout entry
13208 // with a stride-0 axis at the inserted position.
13209 let x = NodeHandle::from_f32(
13210 vec![1.0, 2.0, 3.0, 4.0],
13211 Shape::from_dims(&[2, 2]),
13212 cpu_dev(),
13213 )
13214 .unwrap();
13215 let y = x.unsqueeze(1);
13216 let g = x.graph().read().unwrap();
13217 assert!(
13218 g.has_explicit_layout(y.id()),
13219 "Graph::push should auto-populate layout for view ops"
13220 );
13221 let l = g.layout(y.id());
13222 assert_eq!(l.shape().dims(), &[2, 1, 2]);
13223 // Stride at the inserted axis should be 0 (per the convention
13224 // chosen in Layout::unsqueeze).
13225 assert_eq!(l.stride()[1], 0);
13226 }
13227
13228 #[test]
13229 fn reduce_max_to_validates_compatibility() {
13230 // [3, 4] can reduce to [4] (max along dim 0) or [3, 1] (max along dim 1).
13231 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13232 let r1 = x.reduce_max_to(Shape::from_dims(&[4]));
13233 assert_eq!(r1.shape().dims(), &[4]);
13234 assert!(matches!(
13235 r1.graph().read().unwrap().node(r1.id()).op,
13236 Op::ReduceMaxTo(_)
13237 ));
13238 let r2 = x.reduce_max_to(Shape::from_dims(&[3, 1]));
13239 assert_eq!(r2.shape().dims(), &[3, 1]);
13240 }
13241
13242 #[test]
13243 #[should_panic(expected = "incompatible")]
13244 fn reduce_max_to_rejects_non_broadcast_target() {
13245 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13246 let _ = x.reduce_max_to(Shape::from_dims(&[3, 2]));
13247 }
13248
13249 #[test]
13250 fn reshape_preserves_element_count() {
13251 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13252 let r = x.reshape(Shape::from_dims(&[2, 6]));
13253 assert_eq!(r.shape().dims(), &[2, 6]);
13254 }
13255
13256 #[test]
13257 #[should_panic(expected = "element count mismatch")]
13258 fn reshape_rejects_different_element_count() {
13259 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13260 let _ = x.reshape(Shape::from_dims(&[3, 3]));
13261 }
13262
13263 #[test]
13264 #[should_panic(expected = "same graph")]
13265 fn concat_across_graphs_panics() {
13266 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13267 let b = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13268 let _ = a.concat(&b, 0);
13269 }
13270
13271 #[test]
13272 fn scalar_ops_preserve_shape_and_dtype() {
13273 let x =
13274 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13275 let y = x.add_scalar(5.0).mul_scalar(2.0).powi(2).clamp(0.0, 100.0);
13276 assert_eq!(y.shape().dims(), &[3]);
13277 assert_eq!(y.dtype(), DType::F32);
13278 }
13279
13280 #[test]
13281 fn maximum_requires_matching_shapes() {
13282 let a =
13283 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13284 let b = a
13285 .const_f32_like(vec![4.0, 1.0, 5.0], Shape::from_dims(&[3]))
13286 .unwrap();
13287 let m = a.maximum(&b);
13288 assert_eq!(m.shape().dims(), &[3]);
13289 }
13290
13291 #[test]
13292 #[should_panic(expected = "shape mismatch")]
13293 fn maximum_rejects_shape_mismatch() {
13294 let a =
13295 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13296 let b = a
13297 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13298 .unwrap();
13299 let _ = a.maximum(&b);
13300 }
13301
13302 // ----- topo_order -----
13303
13304 #[test]
13305 fn topo_order_places_inputs_before_dependents() {
13306 // Build: c = (a + b) * a
13307 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13308 let b = a
13309 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13310 .unwrap();
13311 let sum = a.add(&b);
13312 let c = sum.mul(&a);
13313 let order = topo_order(&c.graph().read().unwrap(), c.id());
13314 // The order should contain exactly 4 nodes (a, b, sum, c) and
13315 // place each input strictly before its dependents.
13316 assert_eq!(order.len(), 4);
13317 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13318 assert!(pos(a.id()) < pos(sum.id()));
13319 assert!(pos(b.id()) < pos(sum.id()));
13320 assert!(pos(sum.id()) < pos(c.id()));
13321 assert!(pos(a.id()) < pos(c.id()));
13322 }
13323
13324 #[test]
13325 fn topo_order_visits_each_node_once_when_shared() {
13326 // (a + a) — `a` appears twice in the Add's inputs but the topo
13327 // pass should still visit it exactly once.
13328 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13329 let double = a.add(&a);
13330 let order = topo_order(&double.graph().read().unwrap(), double.id());
13331 assert_eq!(order.len(), 2);
13332 assert_eq!(order[0], a.id());
13333 assert_eq!(order[1], double.id());
13334 }
13335
13336 #[test]
13337 fn topo_order_multi_unions_multiple_roots() {
13338 // Build a DAG where two "output" nodes share a common input.
13339 //
13340 // a ─┬─> add1 (= a + b) ← root_1
13341 // └─> add2 (= a + c) ← root_2
13342 // b ───> add1
13343 // c ───> add2
13344 //
13345 // topo_order_multi(&[add1, add2]) must contain all 5 nodes
13346 // (a, b, c, add1, add2) with a before add1/add2 and b before
13347 // add1 and c before add2.
13348 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13349 let b = a
13350 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13351 .unwrap();
13352 let c = a
13353 .const_f32_like(vec![5.0, 6.0], Shape::from_dims(&[2]))
13354 .unwrap();
13355 let add1 = a.add(&b);
13356 let add2 = a.add(&c);
13357 let order = topo_order_multi(&add1.graph().read().unwrap(), &[add1.id(), add2.id()]);
13358 assert_eq!(order.len(), 5);
13359 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13360 assert!(pos(a.id()) < pos(add1.id()));
13361 assert!(pos(a.id()) < pos(add2.id()));
13362 assert!(pos(b.id()) < pos(add1.id()));
13363 assert!(pos(c.id()) < pos(add2.id()));
13364 }
13365
13366 // ----- backward -----
13367
13368 #[test]
13369 fn backward_of_lone_const_seeds_ones() {
13370 // backward(a) gives a = 1s (the root's upstream is a ones tensor,
13371 // which is the gradient stored for the root itself).
13372 let a =
13373 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13374 let grads = a.backward();
13375 let g_a = grads.get(&a).expect("root gets a seed gradient");
13376 // The seed is a Const ones node of matching shape. Phase 7.5
13377 // G2: gradient consts are slot-rooted Op::Const — no
13378 // host-side ConstData on the node.
13379 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13380 assert!(matches!(node.op, Op::Const));
13381 let slot = g_a.graph().read().unwrap().storage_for(g_a.id()).unwrap();
13382 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
13383 assert_eq!(g_a.shape().dims(), &[3]);
13384 }
13385
13386 #[test]
13387 fn backward_of_add_passes_upstream_through() {
13388 // c = a + b ⇒ dc/da = 1, dc/db = 1.
13389 // Upstream seed is a ones tensor. So grad_a and grad_b are both
13390 // the same ones node (no new math emitted for Add's backward).
13391 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13392 let b = a
13393 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13394 .unwrap();
13395 let c = a.add(&b);
13396 let grads = c.backward();
13397 let g_a = grads.get(&a).unwrap();
13398 let g_b = grads.get(&b).unwrap();
13399 assert_eq!(g_a.id(), g_b.id(), "Add backward routes upstream unchanged");
13400 assert_eq!(g_a.shape().dims(), &[2]);
13401 }
13402
13403 #[test]
13404 fn backward_of_mul_emits_two_mul_nodes() {
13405 // c = a * b ⇒ dc/da = b, dc/db = a (upstream is 1s).
13406 // The backward pass should emit two new Mul nodes (upstream * b,
13407 // upstream * a).
13408 let a = NodeHandle::from_f32(vec![2.0, 3.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13409 let b = a
13410 .const_f32_like(vec![5.0, 7.0], Shape::from_dims(&[2]))
13411 .unwrap();
13412 let c = a.mul(&b);
13413 let nodes_before = c.graph().read().unwrap().len();
13414 let grads = c.backward();
13415 let nodes_after = grads.graph.read().unwrap().len();
13416 // Backward adds: one ones const + two Mul nodes = 3 new nodes.
13417 assert_eq!(nodes_after - nodes_before, 3);
13418 let g_a = grads.get(&a).unwrap();
13419 let g_b = grads.get(&b).unwrap();
13420 // Both gradient nodes should be Mul nodes.
13421 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13422 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13423 assert!(matches!(node_a.op, Op::Mul));
13424 assert!(matches!(node_b.op, Op::Mul));
13425 }
13426
13427 #[test]
13428 fn backward_accumulates_when_node_used_twice() {
13429 // c = a * a ⇒ dc/da = 2a via two separate contributions.
13430 // After backward, the gradient for a should be an Add node
13431 // combining the two Mul contributions (one from each input slot
13432 // of the forward Mul).
13433 let a = NodeHandle::from_f32(vec![3.0, 5.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13434 let c = a.mul(&a);
13435 let grads = c.backward();
13436 let g_a = grads.get(&a).unwrap();
13437 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13438 // The final gradient for `a` is an Add combining the two
13439 // upstream-times-other-input contributions.
13440 assert!(
13441 matches!(node.op, Op::Add),
13442 "expected accumulated gradient to be an Add node, got {:?}",
13443 node.op,
13444 );
13445 }
13446
13447 #[test]
13448 fn backward_of_matmul_emits_transpose_and_matmul_nodes() {
13449 // Forward: Y = A @ B, A:[2,3], B:[3,4], Y:[2,4].
13450 // Backward: dA = dY @ B^T (shape [2,3]), dB = A^T @ dY (shape [3,4]).
13451 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13452 let b = a
13453 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13454 .unwrap();
13455 let y = a.matmul(&b);
13456 let grads = y.backward();
13457 let g_a = grads.get(&a).unwrap();
13458 let g_b = grads.get(&b).unwrap();
13459 // Gradient shapes must match the forward shapes.
13460 assert_eq!(g_a.shape().dims(), &[2, 3]);
13461 assert_eq!(g_b.shape().dims(), &[3, 4]);
13462 // Both should be MatMul nodes (the outermost op of each gradient).
13463 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13464 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13465 assert!(matches!(node_a.op, Op::MatMul));
13466 assert!(matches!(node_b.op, Op::MatMul));
13467 }
13468
13469 // ----- new builder validation -----
13470
13471 #[test]
13472 fn cast_tags_node_with_target_dtype() {
13473 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13474 let b = a.cast(DType::F64);
13475 assert_eq!(b.dtype(), DType::F64);
13476 assert_eq!(b.shape().dims(), &[2]);
13477 let node = b.graph().read().unwrap().node(b.id()).clone();
13478 assert!(matches!(node.op, Op::Cast(DType::F64)));
13479 }
13480
13481 #[test]
13482 fn broadcast_to_accepts_right_aligned_expansion() {
13483 // [3] broadcasts to [2, 3]: pad with leading 1, expand.
13484 let a =
13485 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13486 let b = a.broadcast_to(Shape::from_dims(&[2, 3]));
13487 assert_eq!(b.shape().dims(), &[2, 3]);
13488 }
13489
13490 #[test]
13491 fn broadcast_to_accepts_size_one_expansion() {
13492 // [3, 1] broadcasts to [3, 4]: size-1 dim expands.
13493 let a = NodeHandle::from_f32(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3, 1]), cpu_dev())
13494 .unwrap();
13495 let b = a.broadcast_to(Shape::from_dims(&[3, 4]));
13496 assert_eq!(b.shape().dims(), &[3, 4]);
13497 }
13498
13499 #[test]
13500 #[should_panic(expected = "incompatible")]
13501 fn broadcast_to_rejects_incompatible_dim() {
13502 // [3] cannot broadcast to [2, 4] — the source dim 3 must match 4.
13503 let a =
13504 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13505 let _ = a.broadcast_to(Shape::from_dims(&[2, 4]));
13506 }
13507
13508 #[test]
13509 fn sum_all_produces_rank_zero_output() {
13510 let a =
13511 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13512 let s = a.sum_all();
13513 assert_eq!(s.shape().dims(), &[] as &[usize]);
13514 }
13515
13516 #[test]
13517 fn sum_dim_removes_reduced_dim_from_shape() {
13518 let a =
13519 NodeHandle::from_f32(vec![1.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13520 // Reducing dim 1 should give shape [2, 4].
13521 let s = a.sum_dim(1);
13522 assert_eq!(s.shape().dims(), &[2, 4]);
13523 }
13524
13525 #[test]
13526 #[should_panic(expected = "out of bounds")]
13527 fn sum_dim_rejects_bad_dim() {
13528 let a =
13529 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13530 let _ = a.sum_dim(5);
13531 }
13532
13533 #[test]
13534 fn softmax_and_layer_norm_preserve_shape() {
13535 let a = NodeHandle::from_f32(
13536 vec![1.0, 2.0, 3.0, 4.0],
13537 Shape::from_dims(&[2, 2]),
13538 cpu_dev(),
13539 )
13540 .unwrap();
13541 assert_eq!(a.softmax_last_dim().shape().dims(), &[2, 2]);
13542 assert_eq!(a.layer_norm_last_dim(1e-5).shape().dims(), &[2, 2]);
13543 }
13544
13545 #[test]
13546 fn neg_sub_div_sqrt_log_sin_cos_tanh_sigmoid_all_build() {
13547 // Smoke test: every new builder produces a node with the expected
13548 // shape and dtype. Numerical correctness is exercised in exec.rs.
13549 let a =
13550 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13551 let b = a
13552 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13553 .unwrap();
13554 for tensor in [
13555 a.neg(),
13556 a.sub(&b),
13557 a.div(&b),
13558 a.sqrt(),
13559 a.log(),
13560 a.sin(),
13561 a.cos(),
13562 a.tanh(),
13563 a.sigmoid(),
13564 a.step(),
13565 ] {
13566 assert_eq!(tensor.shape().dims(), &[3]);
13567 assert_eq!(tensor.dtype(), DType::F32);
13568 }
13569 }
13570
13571 // ----- index tensors and indexing ops -----
13572
13573 #[test]
13574 fn from_u32_tags_node_with_u32_dtype() {
13575 let a = NodeHandle::from_u32(vec![1, 2, 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13576 assert_eq!(a.dtype(), DType::U32);
13577 let node = a.graph().read().unwrap().node(a.id()).clone();
13578 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13579 assert!(matches!(node.op, Op::Const));
13580 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13581 assert_eq!(slot.read().unwrap().dtype(), DType::U32);
13582 }
13583
13584 #[test]
13585 fn index_select_produces_shape_with_dim_replaced() {
13586 let data =
13587 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13588 let idx = data
13589 .const_u32_like(vec![0, 2, 1, 0, 2], Shape::from_dims(&[5]))
13590 .unwrap();
13591 let out = data.index_select(0, &idx);
13592 assert_eq!(out.shape().dims(), &[5, 4]);
13593 assert_eq!(out.dtype(), DType::F32);
13594 }
13595
13596 #[test]
13597 #[should_panic(expected = "must be U32")]
13598 fn index_select_rejects_float_index() {
13599 let data =
13600 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13601 let bad = data
13602 .const_f32_like(vec![0.0, 1.0], Shape::from_dims(&[2]))
13603 .unwrap();
13604 let _ = data.index_select(0, &bad);
13605 }
13606
13607 #[test]
13608 #[should_panic(expected = "must be rank 1")]
13609 fn index_select_rejects_multi_dim_index() {
13610 let data =
13611 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13612 let idx = data
13613 .const_u32_like(vec![0, 1, 0, 1], Shape::from_dims(&[2, 2]))
13614 .unwrap();
13615 let _ = data.index_select(0, &idx);
13616 }
13617
13618 #[test]
13619 fn gather_output_shape_matches_index_shape() {
13620 let data =
13621 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13622 // Index shape [2, 5] — same rank as data (rank 2).
13623 let idx = data
13624 .const_u32_like(vec![0; 10], Shape::from_dims(&[2, 5]))
13625 .unwrap();
13626 let out = data.gather(1, &idx);
13627 assert_eq!(out.shape().dims(), &[2, 5]);
13628 }
13629
13630 #[test]
13631 #[should_panic(expected = "same rank")]
13632 fn gather_rejects_rank_mismatch() {
13633 let data =
13634 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13635 // Rank-1 index for rank-2 data → error.
13636 let idx = data
13637 .const_u32_like(vec![0, 1, 0], Shape::from_dims(&[3]))
13638 .unwrap();
13639 let _ = data.gather(1, &idx);
13640 }
13641
13642 #[test]
13643 fn backward_of_relu_emits_step_node() {
13644 // Before: this used to panic. After adding Step + Relu backward,
13645 // it should successfully emit a backward graph rooted in a Mul
13646 // whose second input is a Step node.
13647 let a =
13648 NodeHandle::from_f32(vec![-1.0, 2.0, -3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13649 let y = a.relu();
13650 let grads = y.backward();
13651 let g_a = grads.get(&a).unwrap();
13652 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13653 assert!(matches!(node.op, Op::Mul));
13654 // Find a Step node somewhere in the node's inputs.
13655 let any_step = node
13656 .inputs
13657 .iter()
13658 .any(|&id| matches!(g_a.graph().read().unwrap().node(id).op, Op::Step,));
13659 assert!(any_step, "Relu backward must reference a Step node");
13660 }
13661
13662 #[test]
13663 fn recip_and_abs_builders_produce_unary_nodes() {
13664 // Smoke test: NodeHandle::recip()/abs() build single-input nodes
13665 // with the expected op variant and shape passthrough.
13666 let a =
13667 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13668 let r = a.recip();
13669 let b = a.abs();
13670 assert_eq!(r.shape().dims(), &[3]);
13671 assert_eq!(b.shape().dims(), &[3]);
13672 let r_node = r.graph().read().unwrap().node(r.id()).clone();
13673 let b_node = b.graph().read().unwrap().node(b.id()).clone();
13674 assert!(matches!(r_node.op, Op::Recip));
13675 assert!(matches!(b_node.op, Op::Abs));
13676 assert_eq!(r_node.inputs, vec![a.id()]);
13677 assert_eq!(b_node.inputs, vec![a.id()]);
13678 }
13679
13680 #[test]
13681 fn backward_of_recip_is_neg_of_upstream_times_y_squared() {
13682 // y = 1/x ⇒ dy/dx = -y². The backward graph should be a Neg
13683 // wrapping a Mul whose inputs include a Sqr node — and the Sqr
13684 // should reference the forward Recip output, not a fresh recompute.
13685 let a = NodeHandle::from_f32(vec![2.0, 4.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13686 let y = a.recip();
13687 let y_id = y.id();
13688 let grads = y.backward();
13689 let g_a = grads.get(&a).unwrap();
13690 let g = g_a.graph().read().unwrap();
13691 let neg_node = g.node(g_a.id()).clone();
13692 assert!(
13693 matches!(neg_node.op, Op::Neg),
13694 "outermost backward op must be Neg"
13695 );
13696 let mul_id = neg_node.inputs[0];
13697 let mul_node = g.node(mul_id).clone();
13698 assert!(matches!(mul_node.op, Op::Mul));
13699 // One of the Mul's inputs is a Sqr node fed by the forward Recip.
13700 let sqr_id = mul_node
13701 .inputs
13702 .iter()
13703 .copied()
13704 .find(|&id| matches!(g.node(id).op, Op::Sqr))
13705 .expect("backward chain must contain a Sqr node");
13706 let sqr_node = g.node(sqr_id).clone();
13707 assert_eq!(
13708 sqr_node.inputs,
13709 vec![y_id],
13710 "Sqr's input must be the forward Recip output, not a recompute"
13711 );
13712 }
13713
13714 #[test]
13715 fn backward_of_abs_emits_sign_mul() {
13716 // y = |x|, dy/dx = sign(x). After PR B2 landed Op::Sign, the
13717 // backward chain shrinks from 5 nodes (step+neg+step+sub+mul)
13718 // to 2 (sign+mul): grad_x = upstream * sign(x), where Sign is
13719 // a single primitive that returns -1/0/1 directly.
13720 let a = NodeHandle::from_f32(vec![-2.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13721 let y = a.abs();
13722 let grads = y.backward();
13723 let g_a = grads.get(&a).unwrap();
13724 let g = g_a.graph().read().unwrap();
13725 let mul_node = g.node(g_a.id()).clone();
13726 assert!(matches!(mul_node.op, Op::Mul));
13727 // Exactly one input of the Mul is a Sign node (the other is
13728 // the upstream gradient — a Const-rooted ones-tensor here).
13729 let sign_count = mul_node
13730 .inputs
13731 .iter()
13732 .filter(|&&id| matches!(g.node(id).op, Op::Sign))
13733 .count();
13734 assert_eq!(
13735 sign_count, 1,
13736 "Abs backward must reference exactly 1 Sign node, got {sign_count}"
13737 );
13738 // The Sign node should feed off the original input `a`.
13739 let sign_id = mul_node
13740 .inputs
13741 .iter()
13742 .copied()
13743 .find(|&id| matches!(g.node(id).op, Op::Sign))
13744 .unwrap();
13745 assert_eq!(
13746 g.node(sign_id).inputs,
13747 vec![a.id()],
13748 "Sign's input must be the forward input `a`"
13749 );
13750 }
13751
13752 #[test]
13753 fn eq_builder_produces_bool_output_with_input_shape() {
13754 // GAP-168(c): NodeHandle::eq builds a binary node whose dtype is Bool
13755 // regardless of input dtype (CireSnave's ruling — "Fuel uses Bool
13756 // where possible"), with shape == lhs.shape() (and == rhs.shape()).
13757 let a =
13758 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13759 let b = a
13760 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13761 .unwrap();
13762 let m = a.eq(&b);
13763 assert_eq!(m.shape().dims(), &[3]);
13764 assert_eq!(m.dtype(), DType::Bool, "eq output must be Bool");
13765 let m_node = m.graph().read().unwrap().node(m.id()).clone();
13766 assert!(matches!(m_node.op, Op::Equal));
13767 assert_eq!(m_node.inputs, vec![a.id(), b.id()]);
13768 }
13769
13770 #[test]
13771 fn all_six_comparisons_produce_bool() {
13772 // GAP-168(c): eq/ne/lt/le/gt/ge every one returns DType::Bool, not the
13773 // legacy U8 mask. Shape is preserved (== lhs == rhs). One assertion per
13774 // operator so a regression names the operator that drifted.
13775 let a =
13776 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13777 let b = a
13778 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13779 .unwrap();
13780 for (name, m) in [
13781 ("eq", a.eq(&b)),
13782 ("ne", a.ne(&b)),
13783 ("lt", a.lt(&b)),
13784 ("le", a.le(&b)),
13785 ("gt", a.gt(&b)),
13786 ("ge", a.ge(&b)),
13787 ] {
13788 assert_eq!(m.dtype(), DType::Bool, "{name} output must be Bool");
13789 assert_eq!(m.shape().dims(), &[3], "{name} preserves input shape");
13790 }
13791 }
13792
13793 #[test]
13794 fn try_unsqueeze_returns_err_on_dim_above_rank() {
13795 // try_unsqueeze surfaces bad dim as Err; unsqueeze panics
13796 // on the same input. Both share the validation message.
13797 let a =
13798 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13799 let err = a.try_unsqueeze(5).expect_err("dim above rank must error");
13800 assert!(
13801 format!("{err:?}").contains("out of bounds"),
13802 "error must mention bounds, got: {err:?}"
13803 );
13804 // Happy path still works.
13805 let ok = a.try_unsqueeze(0).expect("dim=0 valid for any rank");
13806 assert_eq!(ok.shape().dims(), &[1, 3]);
13807 }
13808
13809 #[test]
13810 fn try_reshape_returns_err_on_count_mismatch() {
13811 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
13812 .unwrap();
13813 let err = a
13814 .try_reshape(Shape::from_dims(&[3]))
13815 .expect_err("count mismatch must error");
13816 assert!(
13817 format!("{err:?}").contains("element count mismatch"),
13818 "error must mention count mismatch, got: {err:?}"
13819 );
13820 let ok = a
13821 .try_reshape(Shape::from_dims(&[2, 2]))
13822 .expect("matching count is ok");
13823 assert_eq!(ok.shape().dims(), &[2, 2]);
13824 }
13825
13826 #[test]
13827 fn try_broadcast_to_returns_err_on_incompatible_shape() {
13828 let a =
13829 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13830 let err = a
13831 .try_broadcast_to(Shape::from_dims(&[2, 4]))
13832 .expect_err("source dim 3 cannot broadcast to dim 4");
13833 assert!(
13834 format!("{err:?}").contains("incompatible"),
13835 "error must mention incompatibility, got: {err:?}"
13836 );
13837 let ok = a
13838 .try_broadcast_to(Shape::from_dims(&[2, 3]))
13839 .expect("dim 3 broadcasts to dim 3");
13840 assert_eq!(ok.shape().dims(), &[2, 3]);
13841 }
13842
13843 #[test]
13844 fn try_transpose_returns_err_on_rank_below_2() {
13845 let a =
13846 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13847 let err = a
13848 .try_transpose()
13849 .expect_err("rank-1 input cannot transpose");
13850 assert!(
13851 format!("{err:?}").contains("rank ≥ 2"),
13852 "error must mention rank requirement, got: {err:?}"
13853 );
13854 let m = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13855 let mt = m.try_transpose().expect("rank-2 transposes ok");
13856 assert_eq!(mt.shape().dims(), &[3, 2]);
13857 }
13858
13859 #[test]
13860 fn try_permute_returns_err_on_bad_axes() {
13861 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13862 // Wrong axes length:
13863 let err = a.try_permute(&[0]).expect_err("axes length mismatch");
13864 assert!(
13865 format!("{err:?}").contains("must equal tensor rank"),
13866 "error must mention length, got: {err:?}"
13867 );
13868 // Out-of-bounds axis:
13869 let err = a.try_permute(&[0, 5]).expect_err("axis 5 out of rank 2");
13870 assert!(format!("{err:?}").contains("out of bounds"));
13871 // Duplicate axis:
13872 let err = a.try_permute(&[0, 0]).expect_err("duplicate axis");
13873 assert!(format!("{err:?}").contains("duplicate"));
13874 // Happy path:
13875 let ok = a.try_permute(&[1, 0]).expect("valid permutation");
13876 assert_eq!(ok.shape().dims(), &[3, 2]);
13877 }
13878
13879 #[test]
13880 fn squeeze_drops_size_one_dim_metadata_only() {
13881 // Build [2, 1, 3] → squeeze(1) → [2, 3]. Op::Squeeze, view-op,
13882 // shape pruned, dtype preserved, single input slot.
13883 let a =
13884 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13885 let s = a.squeeze(1).expect("squeeze on size-1 dim");
13886 assert_eq!(s.shape().dims(), &[2, 3]);
13887 assert_eq!(s.dtype(), DType::F32);
13888 let node = s.graph().read().unwrap().node(s.id()).clone();
13889 assert!(matches!(node.op, Op::Squeeze { dim: 1 }));
13890 assert_eq!(node.inputs, vec![a.id()]);
13891 // Squeeze joins the view-op set so the Layout side-table is
13892 // populated automatically.
13893 assert!(
13894 node.op.is_view_op(),
13895 "Op::Squeeze must register as a view op"
13896 );
13897 }
13898
13899 #[test]
13900 fn squeeze_rejects_non_size_one_dim() {
13901 // Result-returning: bad dim surfaces as Err, not panic.
13902 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13903 let err = a
13904 .squeeze(1)
13905 .expect_err("squeezing a non-size-1 dim must error");
13906 assert!(
13907 format!("{err:?}").contains("expected 1"),
13908 "error message should mention the size-1 expectation, got: {err:?}"
13909 );
13910 }
13911
13912 #[test]
13913 fn squeeze_rejects_dim_above_rank() {
13914 let a =
13915 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13916 let err = a.squeeze(5).expect_err("dim above rank must error");
13917 assert!(
13918 format!("{err:?}").contains("out of bounds"),
13919 "error message should mention bounds, got: {err:?}"
13920 );
13921 }
13922
13923 #[test]
13924 fn backward_through_squeeze_emits_unsqueeze() {
13925 // y = squeeze(x, 1). Backward: re-insert dim 1 via Unsqueeze.
13926 // Gradient shape must equal x.shape exactly.
13927 let a =
13928 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13929 let y = a.squeeze(1).expect("squeeze on size-1 dim");
13930 let grads = y.backward();
13931 let g_a = grads.get(&a).expect("gradient for a");
13932 assert_eq!(
13933 g_a.shape().dims(),
13934 &[2, 1, 3],
13935 "Squeeze backward gradient must restore the original shape"
13936 );
13937 // The chain is: ones-seed (post-squeeze, shape [2,3])
13938 // → Unsqueeze(dim=1) → shape [2, 1, 3].
13939 let g_node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13940 assert!(
13941 matches!(g_node.op, Op::Unsqueeze { dim: 1 }),
13942 "Squeeze backward must be Unsqueeze at the same dim"
13943 );
13944 }
13945
13946 #[test]
13947 fn floor_builder_produces_unary_node_same_dtype() {
13948 // NodeHandle::floor builds a unary node preserving shape + dtype.
13949 let a =
13950 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13951 let f = a.floor();
13952 assert_eq!(f.shape().dims(), &[3]);
13953 assert_eq!(f.dtype(), DType::F32);
13954 let node = f.graph().read().unwrap().node(f.id()).clone();
13955 assert!(matches!(node.op, Op::Floor));
13956 assert_eq!(node.inputs, vec![a.id()]);
13957 }
13958
13959 #[test]
13960 fn backward_through_floor_drops_gradient_silently() {
13961 // Op::Floor has zero gradient almost everywhere; the inline
13962 // backward arm is a no-op. backward() must succeed and the
13963 // input gets no gradient (the input's upstream is never
13964 // populated through the Floor node).
13965 let a =
13966 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13967 let y = a.floor();
13968 let grads = y.backward();
13969 // a's gradient is dropped — no entry in the GradMap.
13970 assert!(
13971 grads.get(&a).is_none(),
13972 "Floor must not propagate gradient to its input"
13973 );
13974 }
13975
13976 #[test]
13977 fn where_cond_builder_produces_ternary_with_a_dtype() {
13978 // self is a Bool cond (GAP-168(c)); a/b are F32. Output dtype = F32
13979 // (= a's dtype), shape = self.shape() (= a.shape() = b.shape()).
13980 // Op::Where node carries 3 inputs in order (cond, a, b).
13981 let a =
13982 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13983 let b = a
13984 .const_f32_like(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3]))
13985 .unwrap();
13986 let eq_a_b = a.eq(&b); // Bool mask
13987 let picked = eq_a_b.where_cond(&a, &b);
13988 assert_eq!(picked.shape().dims(), &[3]);
13989 assert_eq!(picked.dtype(), DType::F32, "Where output dtype = a/b dtype");
13990 let node = picked.graph().read().unwrap().node(picked.id()).clone();
13991 assert!(matches!(node.op, Op::Where));
13992 assert_eq!(node.inputs.len(), 3);
13993 assert_eq!(
13994 node.inputs,
13995 vec![eq_a_b.id(), a.id(), b.id()],
13996 "Where input order: (cond, a, b)"
13997 );
13998 }
13999
14000 #[test]
14001 fn backward_reuses_exp_forward_output() {
14002 // Exp's backward rule uses the forward output directly. The
14003 // gradient for x should be a Mul whose inputs include the
14004 // forward Exp node (not a new Exp node).
14005 let a = NodeHandle::from_f32(vec![0.0, 1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14006 let e = a.exp();
14007 let exp_forward_id = e.id();
14008 let grads = e.backward();
14009 let g_a = grads.get(&a).unwrap();
14010 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
14011 assert!(matches!(node.op, Op::Mul));
14012 // One of the Mul's inputs should be the original forward Exp node.
14013 assert!(
14014 node.inputs.contains(&exp_forward_id),
14015 "Exp backward should reference the forward output ({exp_forward_id:?}), \
14016 got inputs {:?}",
14017 node.inputs,
14018 );
14019 }
14020
14021 // ---- Op::WriteSlice (Phase E.3.2) ---------------------------------------
14022
14023 #[test]
14024 fn write_slice_destructive_input_is_zero() {
14025 let op = Op::WriteSlice {
14026 ranges: vec![(0, 1), (0, 32), (0, 128)],
14027 dyn_offset: None,
14028 };
14029 assert_eq!(op.destructive_input(), Some(0));
14030 }
14031
14032 #[test]
14033 fn write_slice_short_name() {
14034 let op = Op::WriteSlice {
14035 ranges: vec![(0, 1)],
14036 dyn_offset: None,
14037 };
14038 assert_eq!(op.short_name(), "WriteSlice");
14039 }
14040
14041 #[test]
14042 fn write_slice_emits_op_writeslice_node() {
14043 // dest shape [4, 3]; source shape [1, 3]; write at row 2.
14044 let dest =
14045 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14046 let src = dest
14047 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14048 .unwrap();
14049 let out = dest
14050 .write_slice(&src, vec![(2, 3), (0, 3)])
14051 .expect("write_slice should accept matching shapes");
14052 let g = out.graph().read().unwrap();
14053 match &g.node(out.id()).op {
14054 Op::WriteSlice { ranges, dyn_offset } => {
14055 assert_eq!(ranges, &vec![(2, 3), (0, 3)]);
14056 assert_eq!(dyn_offset, &None);
14057 }
14058 other => panic!("expected Op::WriteSlice, got {other:?}"),
14059 }
14060 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14061 // Output shape == destination shape; bytes are post-write same buffer.
14062 assert_eq!(g.node(out.id()).shape.dims(), &[4, 3]);
14063 }
14064
14065 #[test]
14066 fn write_slice_dyn_records_dynamic_offset() {
14067 use fuel_ir::{DynScalar, SymId};
14068 // dest capacity [8, 3]; source [1, 3]; dynamic start on axis 0.
14069 let dest =
14070 NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[8, 3]), cpu_dev()).unwrap();
14071 let src = dest
14072 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14073 .unwrap();
14074 let sym = SymId(0);
14075 // ranges[0].0 is ignored (start is dynamic); width = 1 - 0 = 1
14076 // matches source dim 0. Axis 1 is static, full width.
14077 let out = dest
14078 .write_slice_dyn(&src, vec![(0, 1), (0, 3)], 0, DynScalar::Sym(sym))
14079 .expect("write_slice_dyn should accept matching widths");
14080 let g = out.graph().read().unwrap();
14081 match &g.node(out.id()).op {
14082 Op::WriteSlice { ranges, dyn_offset } => {
14083 assert_eq!(ranges, &vec![(0, 1), (0, 3)]);
14084 assert_eq!(dyn_offset, &Some((0, DynScalar::Sym(sym))));
14085 }
14086 other => panic!("expected Op::WriteSlice, got {other:?}"),
14087 }
14088 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14089 assert_eq!(g.node(out.id()).shape.dims(), &[8, 3]);
14090 }
14091
14092 #[test]
14093 fn write_slice_dyn_rejects_slab_wider_than_capacity() {
14094 use fuel_ir::{DynScalar, SymId};
14095 // dest capacity on axis 0 is 2, but the dynamic-axis slab is
14096 // width 4 — can never fit regardless of the runtime offset.
14097 let dest =
14098 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14099 let src = dest
14100 .const_f32_like(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]))
14101 .unwrap();
14102 let err = dest.write_slice_dyn(&src, vec![(0, 4), (0, 3)], 0, DynScalar::Sym(SymId(0)));
14103 assert!(
14104 err.is_err(),
14105 "dynamic-axis slab wider than capacity must error at build"
14106 );
14107 }
14108
14109 #[test]
14110 fn write_slice_dyn_rejects_axis_out_of_bounds() {
14111 use fuel_ir::{DynScalar, SymId};
14112 let dest =
14113 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14114 let src = dest
14115 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14116 .unwrap();
14117 let err = dest.write_slice_dyn(&src, vec![(0, 1), (0, 3)], 5, DynScalar::Sym(SymId(0)));
14118 assert!(err.is_err(), "dyn_axis past rank must error");
14119 }
14120
14121 #[test]
14122 fn flash_attn_dyn_records_runtime_k_len() {
14123 use fuel_ir::{DynScalar, SymId};
14124 // q [1, 2, 3, 4]; K/V capacity [1, 1, 8, 4] (GQA Hq=2, Hkv=1).
14125 let q = NodeHandle::from_f32(
14126 vec![0.0_f32; 2 * 3 * 4],
14127 Shape::from_dims(&[1, 2, 3, 4]),
14128 cpu_dev(),
14129 )
14130 .unwrap();
14131 let k = q
14132 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14133 .unwrap();
14134 let v = q
14135 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14136 .unwrap();
14137 let sym = SymId(0);
14138 let out = q.flash_attn_dyn(
14139 &k,
14140 &v,
14141 None,
14142 /*scale*/ 0.5,
14143 /*causal*/ true,
14144 None,
14145 None,
14146 None,
14147 DynScalar::Sym(sym),
14148 );
14149 // Output adopts q's shape, not the capacity.
14150 assert_eq!(out.shape().dims(), &[1, 2, 3, 4]);
14151 let g = out.graph().read().unwrap();
14152 match &g.node(out.id()).op {
14153 Op::Fused(fid, crate::registry::FusedOpParams::FlashAttn { causal, k_len, .. })
14154 if *fid == crate::registry::FusedOps::FLASH_ATTN =>
14155 {
14156 assert!(*causal);
14157 assert_eq!(k_len, &Some(DynScalar::Sym(sym)));
14158 }
14159 other => panic!("expected Op::Fused(FLASH_ATTN, FlashAttn), got {other:?}"),
14160 }
14161 assert_eq!(g.node(out.id()).inputs, vec![q.id(), k.id(), v.id()]);
14162 }
14163
14164 #[test]
14165 #[should_panic(expected = "k_len")]
14166 fn flash_attn_dyn_concrete_k_len_exceeding_capacity_panics() {
14167 use fuel_ir::DynScalar;
14168 let q = NodeHandle::from_f32(
14169 vec![0.0_f32; 2 * 4],
14170 Shape::from_dims(&[1, 1, 2, 4]),
14171 cpu_dev(),
14172 )
14173 .unwrap();
14174 let k = q
14175 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14176 .unwrap();
14177 let v = q
14178 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14179 .unwrap();
14180 // Concrete k_len=5 > capacity 4 → build-time panic.
14181 let _ = q.flash_attn_dyn(
14182 &k,
14183 &v,
14184 None,
14185 1.0,
14186 true,
14187 None,
14188 None,
14189 None,
14190 DynScalar::Concrete(5),
14191 );
14192 }
14193
14194 #[test]
14195 fn write_slice_rejects_rank_mismatch() {
14196 let dest =
14197 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14198 let src = dest
14199 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
14200 .unwrap();
14201 // ranges has rank 2 (matches dest) but source has rank 1.
14202 let err = dest.write_slice(&src, vec![(0, 1), (0, 3)]);
14203 assert!(err.is_err(), "rank mismatch must error");
14204 }
14205
14206 // ---- cross-graph operands must fail at BUILD time, never hang -----------
14207 //
14208 // Node ids are indices into ONE graph's arena, so an operand built on a
14209 // DIFFERENT graph records an id that indexes an unrelated node (or none),
14210 // producing a malformed dependency graph. The failure surfaces as neither
14211 // a panic nor an error: the executor **HANGS at realize**, waiting on a
14212 // dependency that can never resolve — low CPU, no stack, no message. That
14213 // is strictly worse than a panic, and it violates two rules at once:
14214 // "validate at graph-build time" and never-hang.
14215 //
14216 // `matmul`, `qmatmul`, `conv2d`, `paged_attn`, and everything routed via
14217 // `binary_op` already assert this. These builders did not — a real cost: a
14218 // peer session spent a long bisect localizing exactly this on `write_slice`.
14219 //
14220 // These tests only BUILD, never realize, so before the fix they fail fast
14221 // instead of hanging the suite.
14222
14223 #[test]
14224 fn write_slice_rejects_cross_graph_source() {
14225 let dest =
14226 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14227 // A SECOND `from_*` mints a second graph — the easy mistake to make,
14228 // and currently the un-diagnosable one.
14229 let foreign =
14230 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]), cpu_dev())
14231 .unwrap();
14232 assert_ne!(
14233 dest.graph_id(),
14234 foreign.graph_id(),
14235 "fixture must be cross-graph"
14236 );
14237
14238 let err = dest.write_slice(&foreign, vec![(2, 3), (0, 3)]);
14239 assert!(
14240 err.is_err(),
14241 "cross-graph source must be a build-time Err, not a realize-time hang",
14242 );
14243 let msg = format!("{}", err.unwrap_err());
14244 assert!(
14245 msg.contains("same graph"),
14246 "error should say the operands must share a graph, got: {msg}",
14247 );
14248 }
14249
14250 #[test]
14251 fn masked_fill_rejects_cross_graph_mask() {
14252 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14253 let foreign_mask =
14254 NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14255 assert_ne!(
14256 x.graph_id(),
14257 foreign_mask.graph_id(),
14258 "fixture must be cross-graph"
14259 );
14260
14261 let err = x.masked_fill(&foreign_mask, Scalar::F32(0.0));
14262 assert!(
14263 err.is_err(),
14264 "cross-graph mask must be a build-time Err, not a realize-time hang",
14265 );
14266 // MUST assert the reason, not just is_err(): this fixture also has a
14267 // dtype mismatch, so a bare `is_err()` passes for the WRONG reason and
14268 // would stay green even with no graph check at all.
14269 let msg = format!("{}", err.unwrap_err());
14270 assert!(
14271 msg.contains("same graph"),
14272 "must fail on GRAPH affinity, not incidentally on dtype, got: {msg}",
14273 );
14274 }
14275
14276 #[test]
14277 fn masked_fill_rejects_scale_dtype_at_build() {
14278 // F8E8M0 is a block-scale dtype: it HAS a scalar value (so the
14279 // value-dtype check passes) but no zero, so the MaskedFill backward
14280 // cannot produce a gradient. Reject at build time — and this must fail
14281 // on the dtype guard specifically: graph / shape / mask-Bool / value-dtype
14282 // are all satisfied, so a bare `is_err()` can only be the guard firing.
14283 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14284 let scale = x.cast(DType::F8E8M0);
14285 let mask = x.cast(DType::Bool);
14286 let value = Scalar::one(DType::F8E8M0).unwrap();
14287
14288 let err = scale.masked_fill(&mask, value);
14289 assert!(
14290 err.is_err(),
14291 "masked_fill on a scale dtype must be a build-time Err"
14292 );
14293 let msg = format!("{}", err.unwrap_err());
14294 assert!(
14295 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14296 "must fail on the packed/scale dtype guard, got: {msg}",
14297 );
14298 }
14299
14300 /// GAP-075 fix B: pin the REJECT verdict for every unfillable dtype
14301 /// individually (not a bucket count). The guard is semantic — packed
14302 /// formats (F4/F6*) have no representable fill value; block-scales
14303 /// (F8E8M0/F8E6M2) have no zero for the zero-filling backward — so each must
14304 /// be a build-time Err on the dtype GUARD specifically (its message names
14305 /// the op). Per-dtype pinning protects the classification: a future dtype
14306 /// misfiled into the allow arm can't hide behind a passing tally, and a new
14307 /// dtype with no verdict is caught by the compiler (the match is exhaustive,
14308 /// no wildcard). Paired with the allow test below (opposite assertion), the
14309 /// two are mutually non-vacuous.
14310 #[test]
14311 fn masked_fill_rejects_every_unfillable_dtype() {
14312 for dt in [
14313 DType::F4,
14314 DType::F6E2M3,
14315 DType::F6E3M2,
14316 DType::F8E8M0,
14317 DType::F8E6M2,
14318 ] {
14319 let x =
14320 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14321 let t = x.cast(dt);
14322 let mask = x.cast(DType::Bool);
14323 // The dtype guard fires before the value-dtype check, so a dummy
14324 // value is fine; the message assertion proves it was the guard.
14325 let err = t.masked_fill(&mask, Scalar::F32(0.0));
14326 assert!(err.is_err(), "masked_fill must reject {dt:?} at build time");
14327 let msg = format!("{}", err.unwrap_err());
14328 assert!(
14329 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14330 "{dt:?} must fail on the semantic dtype guard, got: {msg}",
14331 );
14332 }
14333 }
14334
14335 /// GAP-075 fix B: the allow arm is a graph-build PERMISSION (masked_fill is
14336 /// semantically well-defined — a fill value + a zero), NOT a claim a backend
14337 /// can allocate/run the dtype. F32 is the live consumer path (attention
14338 /// masking); I32 is an allowed verdict no consumer currently exercises —
14339 /// locking it preserves today's answer without asserting integer masked_fill
14340 /// is known to compute correctly (a backend lacking I32 storage still
14341 /// declines loudly at allocation, downstream of this permission).
14342 #[test]
14343 fn masked_fill_permits_fillable_dtypes_as_permission_not_capability() {
14344 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14345 let mask = x.cast(DType::Bool);
14346 assert!(
14347 x.masked_fill(&mask, Scalar::F32(0.0)).is_ok(),
14348 "F32 masked_fill must build (the live consumer path)",
14349 );
14350 let xi = x.cast(DType::I32);
14351 assert!(
14352 xi.masked_fill(&mask, Scalar::one(DType::I32).unwrap())
14353 .is_ok(),
14354 "I32 masked_fill must build — permission preserved, not a correctness claim",
14355 );
14356 }
14357
14358 #[test]
14359 #[should_panic(expected = "same graph")]
14360 fn rope_with_tables_panics_on_cross_graph_tables() {
14361 // Returns `NodeHandle`, so it follows the convention of the already-checked
14362 // builders (`matmul`, `paged_attn`) and asserts. A panic names the
14363 // problem at the build site; the status quo hangs later saying nothing.
14364 let x = NodeHandle::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[1, 1, 2, 4]), cpu_dev())
14365 .unwrap();
14366 let cos =
14367 NodeHandle::from_f32(vec![1.0_f32; 8], Shape::from_dims(&[2, 4]), cpu_dev()).unwrap();
14368 let sin = x
14369 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]))
14370 .unwrap();
14371 let _ = x.rope_with_tables(&cos, &sin);
14372 }
14373
14374 #[test]
14375 fn write_slice_rejects_slab_width_mismatch() {
14376 let dest =
14377 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14378 // Source has 2 elements along axis 0, but slab is width 1.
14379 let src = dest
14380 .const_f32_like(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]))
14381 .unwrap();
14382 let err = dest.write_slice(&src, vec![(2, 3), (0, 3)]);
14383 assert!(err.is_err(), "slab-width mismatch must error");
14384 }
14385
14386 #[test]
14387 fn write_slice_rejects_range_past_dest_extent() {
14388 let dest =
14389 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14390 let src = dest
14391 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14392 .unwrap();
14393 // axis 0: dest extent is 4; range [4, 5) is out of bounds.
14394 let err = dest.write_slice(&src, vec![(4, 5), (0, 3)]);
14395 assert!(err.is_err(), "range past dest extent must error");
14396 }
14397
14398 #[test]
14399 fn write_slice_derives_ordering_after_other_readers() {
14400 // Graph:
14401 // dest = ...; src = ...
14402 // ro = dest.relu() (non-destructive reader of dest)
14403 // w = dest.write_slice(&src, [(0,1),(0,3)]) (destructive on dest)
14404 // Expected ordering: w must run after ro.
14405 let dest =
14406 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14407 let src = dest
14408 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14409 .unwrap();
14410 let ro = dest.relu();
14411 let w = dest.write_slice(&src, vec![(0, 1), (0, 3)]).unwrap();
14412 let ord = crate::opt::derive_ordering(&dest.graph().read().unwrap(), &[ro.id(), w.id()]);
14413 let deps = ord.deps_of(w.id());
14414 assert_eq!(
14415 deps.len(),
14416 1,
14417 "write_slice should have one ordering dep (the relu)"
14418 );
14419 assert_eq!(
14420 deps[0],
14421 ro.id(),
14422 "write_slice must run after the non-destructive reader"
14423 );
14424 }
14425
14426 // ---- In-place ops Phase 1 -----------------------------------------------
14427 //
14428 // Smoke tests for the 5 new in-place unary variants
14429 // (`Op::ReluInplace`, `Op::SiluInplace`, `Op::GeluTanhInplace`,
14430 // `Op::TanhInplace`, `Op::SigmoidInplace`) and `FusedOps::INPLACE_AFFINE`.
14431 // Phase 1 only ships the structural plumbing (Op IR + destructive_input +
14432 // short_name + scheduler integration); dispatch + autograd land in Phases
14433 // 3 + 4. See `docs/session-prompts/in-place-ops-infrastructure.md`.
14434
14435 #[test]
14436 fn inplace_unary_destructive_input_is_zero() {
14437 for op in [
14438 Op::ReluInplace,
14439 Op::SiluInplace,
14440 Op::GeluTanhInplace,
14441 Op::TanhInplace,
14442 Op::SigmoidInplace,
14443 Op::NegInplace,
14444 Op::AbsInplace,
14445 Op::SqrInplace,
14446 Op::SqrtInplace,
14447 Op::RsqrtInplace,
14448 Op::RecipInplace,
14449 Op::ExpInplace,
14450 Op::LogInplace,
14451 Op::SinInplace,
14452 Op::CosInplace,
14453 Op::SignInplace,
14454 Op::FloorInplace,
14455 Op::CeilInplace,
14456 Op::RoundInplace,
14457 Op::ErfInplace,
14458 Op::GeluInplace,
14459 ] {
14460 assert_eq!(
14461 op.destructive_input(),
14462 Some(0),
14463 "in-place unary {op:?} must declare input 0 destructive",
14464 );
14465 }
14466 }
14467
14468 #[test]
14469 fn inplace_unary_short_names_round_trip() {
14470 assert_eq!(Op::ReluInplace.short_name(), "ReluInplace");
14471 assert_eq!(Op::SiluInplace.short_name(), "SiluInplace");
14472 assert_eq!(Op::GeluTanhInplace.short_name(), "GeluTanhInplace");
14473 assert_eq!(Op::TanhInplace.short_name(), "TanhInplace");
14474 assert_eq!(Op::SigmoidInplace.short_name(), "SigmoidInplace");
14475 assert_eq!(Op::NegInplace.short_name(), "NegInplace");
14476 assert_eq!(Op::AbsInplace.short_name(), "AbsInplace");
14477 assert_eq!(Op::SqrInplace.short_name(), "SqrInplace");
14478 assert_eq!(Op::SqrtInplace.short_name(), "SqrtInplace");
14479 assert_eq!(Op::RsqrtInplace.short_name(), "RsqrtInplace");
14480 assert_eq!(Op::RecipInplace.short_name(), "RecipInplace");
14481 assert_eq!(Op::ExpInplace.short_name(), "ExpInplace");
14482 assert_eq!(Op::LogInplace.short_name(), "LogInplace");
14483 assert_eq!(Op::SinInplace.short_name(), "SinInplace");
14484 assert_eq!(Op::CosInplace.short_name(), "CosInplace");
14485 assert_eq!(Op::SignInplace.short_name(), "SignInplace");
14486 assert_eq!(Op::FloorInplace.short_name(), "FloorInplace");
14487 assert_eq!(Op::CeilInplace.short_name(), "CeilInplace");
14488 assert_eq!(Op::RoundInplace.short_name(), "RoundInplace");
14489 assert_eq!(Op::ErfInplace.short_name(), "ErfInplace");
14490 assert_eq!(Op::GeluInplace.short_name(), "GeluInplace");
14491 assert_eq!(
14492 Op::ClampInplace { min: 0.0, max: 1.0 }.short_name(),
14493 "ClampInplace"
14494 );
14495 assert_eq!(Op::PowIInplace(3).short_name(), "PowIInplace");
14496 }
14497
14498 #[test]
14499 fn inplace_affine_fused_op_destructive_input_is_zero() {
14500 let op = Op::Fused(
14501 crate::registry::FusedOps::INPLACE_AFFINE,
14502 crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 },
14503 );
14504 assert_eq!(op.destructive_input(), Some(0));
14505 }
14506
14507 #[test]
14508 fn destructive_input_for_fused_is_registry_declared() {
14509 // GAP-076: a fused op's destructiveness is a MANDATORY declared field on
14510 // its registry entry, and `Op::destructive_input` reads that field via
14511 // `default_registry()` rather than a hardcoded id match that could drift
14512 // out of sync. This locks BOTH directions of the declaration plus the
14513 // routing that reads it. Regression lock, not a born-red: no op was
14514 // misclassified before the fix — its value is that a future wrong
14515 // declaration (or a reverted routing) reddens HERE instead of surfacing
14516 // as an intermittent scheduler data race that points nowhere near this
14517 // code. The exhaustive match in `Op::destructive_input` and the
14518 // mandatory struct field are the compile-time seams; this is the belt.
14519 use crate::registry::{FusedOps, default_registry};
14520 let reg = default_registry();
14521 assert_eq!(
14522 reg.entry(FusedOps::INPLACE_AFFINE)
14523 .expect("INPLACE_AFFINE is registered")
14524 .destructive_input,
14525 Some(0),
14526 "InplaceAffine must declare itself destructive on input 0",
14527 );
14528 assert_eq!(
14529 reg.entry(FusedOps::SOFTMAX_LAST_DIM)
14530 .expect("SOFTMAX_LAST_DIM is registered")
14531 .destructive_input,
14532 None,
14533 "a functional fused op must declare itself non-destructive",
14534 );
14535 // Routing reads the declared field (not a hardcoded id match).
14536 let op = Op::Fused(
14537 FusedOps::INPLACE_AFFINE,
14538 crate::registry::FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 },
14539 );
14540 assert_eq!(op.destructive_input(), Some(0));
14541 }
14542
14543 #[test]
14544 fn inplace_affine_params_key_dedupe_on_same_mul_add() {
14545 // Two `InplaceAffine` params with identical (mul, add) hash to the
14546 // same key; differing values produce distinct keys. Lets CSE / the
14547 // existing op_key infrastructure collapse identical in-place affines
14548 // (when callers wire them through the equivalent graph machinery).
14549 let a = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14550 let b = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14551 let c = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 0.5 };
14552 assert_eq!(a.key(), b.key(), "identical mul/add must dedupe");
14553 assert_ne!(a.key(), c.key(), "different add must produce distinct key");
14554 }
14555
14556 // ---- Phase 4 — autograd through in-place ops ----
14557 //
14558 // The view-aware `derive_ordering` (Phase 4a) ensures backward
14559 // grad nodes that read forward inputs run BEFORE any in-place
14560 // mutation of those inputs. The backward arms in
14561 // `NodeHandle::backward` (Phase 4b) emit the same gradient graph as
14562 // the non-inplace cousins. These tests prove that calling
14563 // `.backward()` through an in-place node:
14564 // (1) does NOT panic (was previously guarded by the Phase 1
14565 // defensive panic);
14566 // (2) emits the same gradient-node structure as the non-inplace
14567 // cousin (matching node counts + op types as a structural
14568 // proxy for numerical equivalence — the actual numerics are
14569 // exercised by the live oracle tests in fuel-storage).
14570
14571 #[test]
14572 fn backward_through_relu_inplace_does_not_panic() {
14573 // y = x.relu_inplace(); loss = y.sum_all(); loss.backward()
14574 // Phase 1's defensive panic is removed; backward emits
14575 // Op::Step(x) + Op::Mul(upstream, step) — same as Op::Relu.
14576 let x =
14577 NodeHandle::from_f32(vec![1.0, -2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14578 let y = x.relu_inplace();
14579 let loss = y.sum_all();
14580 let grads = loss.backward();
14581 let g_x = grads.get(&x).expect("gradient for x should be present");
14582 // Same structural form as Op::Relu's backward: gradient node
14583 // is an Op::Mul (upstream × step(x)).
14584 let g_node = g_x.graph().read().unwrap().node(g_x.id()).clone();
14585 assert!(
14586 matches!(g_node.op, Op::Mul),
14587 "relu backward grad is Mul; got {:?}",
14588 g_node.op
14589 );
14590 }
14591
14592 #[test]
14593 fn backward_through_sigmoid_inplace_does_not_panic() {
14594 let x = NodeHandle::from_f32(vec![0.5, -0.5], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14595 let y = x.sigmoid_inplace();
14596 let loss = y.sum_all();
14597 let grads = loss.backward();
14598 let g_x = grads.get(&x);
14599 assert!(g_x.is_some());
14600 }
14601
14602 #[test]
14603 fn backward_through_tanh_inplace_does_not_panic() {
14604 let x =
14605 NodeHandle::from_f32(vec![0.1, 0.2, 0.3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14606 let y = x.tanh_inplace();
14607 let loss = y.sum_all();
14608 let grads = loss.backward();
14609 let g_x = grads.get(&x);
14610 assert!(g_x.is_some());
14611 }
14612
14613 #[test]
14614 fn backward_through_silu_inplace_does_not_panic() {
14615 let x = NodeHandle::from_f32(vec![0.1, 0.2], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14616 let y = x.silu_inplace();
14617 let loss = y.sum_all();
14618 let grads = loss.backward();
14619 let g_x = grads.get(&x);
14620 assert!(g_x.is_some());
14621 }
14622
14623 /// The reverse walk has hand-written arms for some fused ids and lowers the
14624 /// rest through their total `decompose` first; WHICH ids take the second path
14625 /// is whatever the registry declares as `BackwardKind::Decompose`. Pin that
14626 /// set so adding or flipping one is a deliberate change that also adds its
14627 /// finite-difference test (SSM recipes: `fuel-tensor` scan tests;
14628 /// FusedSoftmaxCrossEntropy: `fuel-training`; NF4/AWQ matmul and causal
14629 /// conv1d: `fuel-tensor` `*_gradient_matches_finite_difference`).
14630 #[test]
14631 fn decompose_declared_fused_ops_are_exactly_the_tested_set() {
14632 use crate::registry::{BackwardKind, FusedOps, default_registry};
14633 let declared: Vec<_> = default_registry()
14634 .entries_iter()
14635 .filter(|e| e.backward == BackwardKind::Decompose)
14636 .map(|e| e.id)
14637 .collect();
14638 let expected = [
14639 FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
14640 FusedOps::SELECTIVE_SCAN,
14641 FusedOps::SSD_CHUNK_SCAN,
14642 FusedOps::NF4_MATMUL,
14643 FusedOps::AWQ_MATMUL,
14644 FusedOps::CAUSAL_CONV1D,
14645 ];
14646 assert_eq!(declared.len(), expected.len(), "declared: {declared:?}");
14647 for id in expected {
14648 assert!(declared.contains(&id), "{id:?} lost its Decompose backward");
14649 assert!(
14650 lowers_for_backward(id),
14651 "{id:?} not lowered by the pre-pass"
14652 );
14653 }
14654 // Control: a hand-armed op is not lowered.
14655 assert!(!lowers_for_backward(FusedOps::SOFTMAX_LAST_DIM));
14656 }
14657
14658 #[test]
14659 fn backward_through_gelu_tanh_inplace_does_not_panic() {
14660 // Numerics are checked against finite differences in fuel-tensor
14661 // (`gelu_tanh_inplace_backward_matches_finite_difference`).
14662 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14663 let y = x.gelu_tanh_inplace();
14664 let loss = y.sum_all();
14665 let grads = loss.backward();
14666 assert!(grads.get(&x).is_some());
14667 }
14668
14669 #[test]
14670 fn backward_through_gelu_tanh_does_not_panic() {
14671 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14672 let loss = x.gelu_tanh().sum_all();
14673 let grads = loss.backward();
14674 assert!(grads.get(&x).is_some());
14675 }
14676
14677 #[test]
14678 fn backward_through_relu_inplace_emits_same_graph_shape_as_functional() {
14679 // Structural parity: relu_inplace backward emits the same node
14680 // count + same op variants as relu backward, since the
14681 // gradient formula is identical.
14682 let x_inp =
14683 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14684 let y_inp = x_inp.relu_inplace();
14685 let loss_inp = y_inp.sum_all();
14686 let nodes_before_inp = loss_inp.graph().read().unwrap().len();
14687 let _ = loss_inp.backward();
14688 let added_inp = loss_inp.graph().read().unwrap().len() - nodes_before_inp;
14689
14690 let x_fn =
14691 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14692 let y_fn = x_fn.relu();
14693 let loss_fn = y_fn.sum_all();
14694 let nodes_before_fn = loss_fn.graph().read().unwrap().len();
14695 let _ = loss_fn.backward();
14696 let added_fn = loss_fn.graph().read().unwrap().len() - nodes_before_fn;
14697
14698 assert_eq!(
14699 added_inp, added_fn,
14700 "ReluInplace backward should add the same number of nodes as Relu backward ({added_fn}), got {added_inp}",
14701 );
14702 }
14703
14704 #[test]
14705 fn relu_inplace_builder_emits_op_reluinplace() {
14706 let x = NodeHandle::from_f32(
14707 vec![1.0_f32, -1.0, 2.0, -2.0],
14708 Shape::from_dims(&[4]),
14709 cpu_dev(),
14710 )
14711 .unwrap();
14712 let y = x.relu_inplace();
14713 let g = y.graph().read().unwrap();
14714 let node = g.node(y.id());
14715 assert!(matches!(node.op, Op::ReluInplace));
14716 assert_eq!(node.inputs, vec![x.id()]);
14717 assert_eq!(node.shape.dims(), &[4]);
14718 assert_eq!(node.dtype, DType::F32);
14719 }
14720
14721 #[test]
14722 fn affine_inplace_builder_emits_fused_inplace_affine() {
14723 let x = NodeHandle::from_f32(
14724 vec![1.0_f32, 2.0, 3.0, 4.0],
14725 Shape::from_dims(&[4]),
14726 cpu_dev(),
14727 )
14728 .unwrap();
14729 let y = x.affine_inplace(2.0, 0.5);
14730 let g = y.graph().read().unwrap();
14731 let node = g.node(y.id());
14732 match &node.op {
14733 Op::Fused(id, crate::registry::FusedOpParams::InplaceAffine { mul, add }) => {
14734 assert_eq!(*id, crate::registry::FusedOps::INPLACE_AFFINE);
14735 assert_eq!(*mul, 2.0);
14736 assert_eq!(*add, 0.5);
14737 }
14738 other => panic!("expected Op::Fused(INPLACE_AFFINE, InplaceAffine), got {other:?}"),
14739 }
14740 assert_eq!(node.inputs, vec![x.id()]);
14741 assert_eq!(node.shape.dims(), &[4]);
14742 }
14743
14744 #[test]
14745 fn all_inplace_unary_builders_round_trip_through_op_variants() {
14746 // One smoke per variant — each builder emits exactly the
14747 // matching `Op::*Inplace` variant, single input, shape +
14748 // dtype unchanged.
14749 let x = NodeHandle::from_f32(vec![0.5_f32; 8], Shape::from_dims(&[8]), cpu_dev()).unwrap();
14750 fn check(y: NodeHandle, x_id: NodeId, expect: fn(&Op) -> bool) {
14751 let g = y.graph().read().unwrap();
14752 let node = g.node(y.id());
14753 assert!(expect(&node.op), "wrong Op variant: {:?}", node.op);
14754 assert_eq!(node.inputs, vec![x_id]);
14755 assert_eq!(node.shape.dims(), &[8]);
14756 assert_eq!(node.dtype, DType::F32);
14757 }
14758 check(x.relu_inplace(), x.id(), |o| matches!(o, Op::ReluInplace));
14759 check(x.silu_inplace(), x.id(), |o| matches!(o, Op::SiluInplace));
14760 check(x.gelu_tanh_inplace(), x.id(), |o| {
14761 matches!(o, Op::GeluTanhInplace)
14762 });
14763 check(x.tanh_inplace(), x.id(), |o| matches!(o, Op::TanhInplace));
14764 check(x.sigmoid_inplace(), x.id(), |o| {
14765 matches!(o, Op::SigmoidInplace)
14766 });
14767 check(x.neg_inplace(), x.id(), |o| matches!(o, Op::NegInplace));
14768 check(x.abs_inplace(), x.id(), |o| matches!(o, Op::AbsInplace));
14769 check(x.sqr_inplace(), x.id(), |o| matches!(o, Op::SqrInplace));
14770 check(x.sqrt_inplace(), x.id(), |o| matches!(o, Op::SqrtInplace));
14771 check(x.rsqrt_inplace(), x.id(), |o| matches!(o, Op::RsqrtInplace));
14772 check(x.recip_inplace(), x.id(), |o| matches!(o, Op::RecipInplace));
14773 check(x.exp_inplace(), x.id(), |o| matches!(o, Op::ExpInplace));
14774 check(x.log_inplace(), x.id(), |o| matches!(o, Op::LogInplace));
14775 check(x.sin_inplace(), x.id(), |o| matches!(o, Op::SinInplace));
14776 check(x.cos_inplace(), x.id(), |o| matches!(o, Op::CosInplace));
14777 check(x.sign_inplace(), x.id(), |o| matches!(o, Op::SignInplace));
14778 check(x.floor_inplace(), x.id(), |o| matches!(o, Op::FloorInplace));
14779 check(x.ceil_inplace(), x.id(), |o| matches!(o, Op::CeilInplace));
14780 check(x.round_inplace(), x.id(), |o| matches!(o, Op::RoundInplace));
14781 check(x.erf_inplace(), x.id(), |o| matches!(o, Op::ErfInplace));
14782 check(x.gelu_inplace(), x.id(), |o| matches!(o, Op::GeluInplace));
14783 check(x.clamp_inplace(-1.0, 1.0), x.id(), |o| {
14784 matches!(o, Op::ClampInplace { .. })
14785 });
14786 check(x.powi_inplace(3), x.id(), |o| {
14787 matches!(o, Op::PowIInplace(3))
14788 });
14789 }
14790
14791 /// Backward smoke for the expanded in-place op family — each variant
14792 /// (except zero-grad ones) must produce a gradient node for x without
14793 /// panicking. Zero-grad variants (Sign/Floor/Ceil/Round) drop the
14794 /// gradient entirely (no entry in the GradMap), mirroring their
14795 /// non-inplace cousins.
14796 #[test]
14797 fn backward_through_expanded_inplace_unary_emits_grad() {
14798 fn check_emits_grad(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14799 let x =
14800 NodeHandle::from_f32(vec![0.5_f32, 1.5, 2.5], Shape::from_dims(&[3]), cpu_dev())
14801 .unwrap();
14802 let y = make(&x);
14803 let loss = y.sum_all();
14804 let grads = loss.backward();
14805 assert!(grads.get(&x).is_some(), "backward must emit gradient for x");
14806 }
14807 check_emits_grad(|x| x.neg_inplace());
14808 check_emits_grad(|x| x.abs_inplace());
14809 check_emits_grad(|x| x.sqr_inplace());
14810 check_emits_grad(|x| x.sqrt_inplace());
14811 check_emits_grad(|x| x.rsqrt_inplace());
14812 check_emits_grad(|x| x.recip_inplace());
14813 check_emits_grad(|x| x.exp_inplace());
14814 check_emits_grad(|x| x.log_inplace());
14815 check_emits_grad(|x| x.sin_inplace());
14816 check_emits_grad(|x| x.cos_inplace());
14817 check_emits_grad(|x| x.erf_inplace());
14818 check_emits_grad(|x| x.gelu_inplace());
14819 check_emits_grad(|x| x.clamp_inplace(-1.0, 2.0));
14820 check_emits_grad(|x| x.powi_inplace(3));
14821 }
14822
14823 #[test]
14824 fn backward_through_zero_grad_inplace_drops_gradient() {
14825 fn check_drops(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14826 let x =
14827 NodeHandle::from_f32(vec![1.5_f32, 2.5, -3.5], Shape::from_dims(&[3]), cpu_dev())
14828 .unwrap();
14829 let y = make(&x);
14830 let loss = y.sum_all();
14831 let grads = loss.backward();
14832 assert!(
14833 grads.get(&x).is_none(),
14834 "zero-grad in-place op must not emit gradient"
14835 );
14836 }
14837 check_drops(|x| x.sign_inplace());
14838 check_drops(|x| x.floor_inplace());
14839 check_drops(|x| x.ceil_inplace());
14840 check_drops(|x| x.round_inplace());
14841 }
14842
14843 #[test]
14844 fn inplace_unary_derives_ordering_after_non_destructive_readers() {
14845 // Graph:
14846 // x = const f32 [4]
14847 // y_a = x.relu() (non-destructive reader of x)
14848 // y_b = manually-pushed Op::ReluInplace on x (destructive)
14849 // Expected: y_b must run after y_a.
14850 let x = NodeHandle::from_f32(
14851 vec![1.0_f32, -1.0, 2.0, -2.0],
14852 Shape::from_dims(&[4]),
14853 cpu_dev(),
14854 )
14855 .unwrap();
14856 let y_a = x.relu();
14857 let y_b_id = x.graph().write().unwrap().push(Node {
14858 op: Op::ReluInplace,
14859 inputs: vec![x.id()],
14860 shape: Shape::from_dims(&[4]),
14861 dtype: DType::F32,
14862 });
14863 let ord = crate::opt::derive_ordering(&x.graph().read().unwrap(), &[y_a.id(), y_b_id]);
14864 let deps = ord.deps_of(y_b_id);
14865 assert_eq!(deps.len(), 1, "in-place unary should have one ordering dep");
14866 assert_eq!(
14867 deps[0],
14868 y_a.id(),
14869 "in-place unary must run after the non-destructive reader"
14870 );
14871 }
14872
14873 // ------------------------------------------------------------------
14874 // Multi-output nodes (Option C, Session 1)
14875 // ------------------------------------------------------------------
14876
14877 use fuel_backend_contract::storage::Storage as CoreStorage;
14878 use fuel_ir::storage::OutputView;
14879
14880 /// Build a real CPU `Storage` of `n` F32 zeros so `Storage`-level
14881 /// tests can attach + read bundle metadata against a live backend
14882 /// allocator. The dtype is fixed at F32 because every existing
14883 /// `OutputView` test below uses F32 for slot 0; bundle dtype is
14884 /// validated at `with_bundle` time against this primary dtype.
14885 fn cpu_f32_storage(n: usize) -> CoreStorage {
14886 let dev = cpu_dev();
14887 let buf = fuel_ir::HostBuffer::F32(vec![0.0_f32; n]);
14888 let inner = dev
14889 .storage_from_host_buffer_owned_dyn(buf)
14890 .expect("test fixture: F32 storage_from_host_buffer_owned_dyn failed");
14891 CoreStorage::from_dyn(inner)
14892 }
14893
14894 /// Build a 2-slot bundle: slot 0 `[2, 3]` F32 `y`-shape, slot 1
14895 /// `[2, 4]` F32 `last_state`-shape. Returns the views and the
14896 /// total element count (used to size the backing CPU buffer so
14897 /// slot 1's byte range stays inside the bundle's bytes).
14898 fn two_slot_views() -> (Vec<OutputView>, usize) {
14899 let s0 = Shape::from_dims(&[2, 3]);
14900 let s1 = Shape::from_dims(&[2, 4]);
14901 let v0 = OutputView {
14902 byte_offset: 0,
14903 len_elements: s0.elem_count(),
14904 dtype: DType::F32,
14905 shape: s0.clone(),
14906 layout: Layout::contiguous(s0),
14907 name: Some("y"),
14908 };
14909 let v1 = OutputView {
14910 byte_offset: v0.len_bytes(),
14911 len_elements: s1.elem_count(),
14912 dtype: DType::F32,
14913 shape: s1.clone(),
14914 layout: Layout::contiguous(s1),
14915 name: Some("last_state"),
14916 };
14917 let total = v0.len_elements + v1.len_elements;
14918 (vec![v0, v1], total)
14919 }
14920
14921 /// `Storage::is_bundled` is false by default; `slot_count` is 1;
14922 /// `bundle` / `bundle_arc` / `slot_view` / `slot_dtype` all return
14923 /// `None` for the non-multi-output case.
14924 #[test]
14925 fn storage_single_output_defaults() {
14926 let s = cpu_f32_storage(8);
14927 assert!(!s.is_bundled());
14928 assert_eq!(s.slot_count(), 1);
14929 assert!(s.bundle().is_none());
14930 assert!(s.bundle_arc().is_none());
14931 assert!(s.slot_view(0).is_none());
14932 assert_eq!(s.slot_dtype(0), None);
14933 assert_eq!(s.primary_dtype(), DType::F32);
14934 assert_eq!(s.dtype(), DType::F32);
14935 }
14936
14937 /// `Storage::with_bundle` attaches the side-table and per-slot
14938 /// lookups report the declared shape/dtype.
14939 #[test]
14940 fn storage_with_bundle_attaches_views() {
14941 let (views, total) = two_slot_views();
14942 let s = cpu_f32_storage(total)
14943 .with_bundle(views.clone().into())
14944 .expect("with_bundle should accept matching slot-0 dtype");
14945 assert!(s.is_bundled());
14946 assert_eq!(s.slot_count(), 2);
14947 let slot0 = s.slot_view(0).unwrap();
14948 assert_eq!(slot0.shape, Shape::from_dims(&[2, 3]));
14949 assert_eq!(slot0.dtype, DType::F32);
14950 assert_eq!(slot0.byte_offset, 0);
14951 assert_eq!(slot0.name, Some("y"));
14952 let slot1 = s.slot_view(1).unwrap();
14953 assert_eq!(slot1.shape, Shape::from_dims(&[2, 4]));
14954 assert_eq!(slot1.byte_offset, 24); // 6 F32s = 24 bytes
14955 assert_eq!(slot1.name, Some("last_state"));
14956 // Out-of-range slot reads `None`, doesn't panic.
14957 assert!(s.slot_view(2).is_none());
14958 assert_eq!(s.slot_dtype(2), None);
14959 }
14960
14961 /// `Storage::with_bundle` rejects an empty bundle slice (a
14962 /// zero-slot bundle is a contract bug — use a single-output
14963 /// Storage if there's nothing to project).
14964 #[test]
14965 fn storage_with_bundle_rejects_empty() {
14966 let s = cpu_f32_storage(1);
14967 let empty: Arc<[OutputView]> = Arc::from(Vec::<OutputView>::new().into_boxed_slice());
14968 let err = s
14969 .with_bundle(empty)
14970 .expect_err("empty bundle slice must error");
14971 let msg = format!("{err}");
14972 assert!(msg.contains("non-empty"), "error message: {msg}");
14973 }
14974
14975 /// `Storage::with_bundle` rejects slot 0 dtype that disagrees with
14976 /// the inner backend dtype — the bundle invariant "slot 0 dtype ==
14977 /// primary_dtype()" must hold.
14978 #[test]
14979 fn storage_with_bundle_rejects_dtype_mismatch() {
14980 let s = cpu_f32_storage(8);
14981 let bad = OutputView {
14982 byte_offset: 0,
14983 len_elements: 4,
14984 dtype: DType::F64,
14985 shape: Shape::from_dims(&[2, 2]),
14986 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
14987 name: None,
14988 };
14989 let err = s
14990 .with_bundle(Arc::from(vec![bad].into_boxed_slice()))
14991 .expect_err("slot 0 dtype mismatch must error");
14992 let msg = format!("{err}");
14993 assert!(msg.contains("dtype"), "error message: {msg}");
14994 }
14995
14996 /// `Graph::output_views` is `None` for ordinary single-output
14997 /// nodes; `multi_output_count` is 0.
14998 #[test]
14999 fn graph_output_views_defaults() {
15000 let mut g = Graph::new();
15001 let id = g.push(Node {
15002 op: Op::Const,
15003 inputs: vec![],
15004 shape: Shape::from_dims(&[2, 3]),
15005 dtype: DType::F32,
15006 });
15007 assert!(g.output_views(id).is_none());
15008 assert!(!g.is_multi_output(id));
15009 assert_eq!(g.multi_output_count(), 0);
15010 }
15011
15012 /// `Graph::set_output_views` round-trips: read returns what was
15013 /// written; `is_multi_output` flips.
15014 #[test]
15015 fn graph_set_output_views_roundtrip() {
15016 let mut g = Graph::new();
15017 let id = g.push(Node {
15018 op: Op::Const,
15019 inputs: vec![],
15020 shape: Shape::from_dims(&[2, 3]),
15021 dtype: DType::F32,
15022 });
15023 let (views, _) = two_slot_views();
15024 g.set_output_views(id, views.clone().into())
15025 .expect("valid 2-slot specs");
15026 assert!(g.is_multi_output(id));
15027 assert_eq!(g.multi_output_count(), 1);
15028 let read = g.output_views(id).expect("entry present");
15029 assert_eq!(read.len(), 2);
15030 assert_eq!(read[1].shape, Shape::from_dims(&[2, 4]));
15031 }
15032
15033 /// `Graph::set_output_views` rejects slot 0 dtype/shape that
15034 /// disagree with the producer node's primary shape/dtype.
15035 #[test]
15036 fn graph_set_output_views_validates_primary() {
15037 let mut g = Graph::new();
15038 let id = g.push(Node {
15039 op: Op::Const,
15040 inputs: vec![],
15041 shape: Shape::from_dims(&[2, 3]),
15042 dtype: DType::F32,
15043 });
15044 // dtype mismatch on slot 0
15045 let bad_dtype = OutputView {
15046 byte_offset: 0,
15047 len_elements: 6,
15048 dtype: DType::F64,
15049 shape: Shape::from_dims(&[2, 3]),
15050 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15051 name: None,
15052 };
15053 let err = g
15054 .set_output_views(id, vec![bad_dtype].into())
15055 .expect_err("primary dtype mismatch must error");
15056 let msg = format!("{err}");
15057 assert!(msg.contains("dtype"), "error message: {msg}");
15058 // shape mismatch on slot 0
15059 let bad_shape = OutputView {
15060 byte_offset: 0,
15061 len_elements: 4,
15062 dtype: DType::F32,
15063 shape: Shape::from_dims(&[2, 2]),
15064 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15065 name: None,
15066 };
15067 let err = g
15068 .set_output_views(id, vec![bad_shape].into())
15069 .expect_err("primary shape mismatch must error");
15070 let msg = format!("{err}");
15071 assert!(msg.contains("shape"), "error message: {msg}");
15072 }
15073
15074 /// `NodeHandle::view(slot)` against a producer that hasn't been
15075 /// declared multi-output returns Err — fails fast at build time.
15076 #[test]
15077 fn tensor_view_on_non_multi_output_errors() {
15078 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15079 let id = graph.write().unwrap().push(Node {
15080 op: Op::Const,
15081 inputs: vec![],
15082 shape: Shape::from_dims(&[2, 3]),
15083 dtype: DType::F32,
15084 });
15085 let producer = NodeHandle::from_existing(Arc::clone(&graph), id);
15086 let err = producer
15087 .view(0)
15088 .expect_err("view on non-multi-output producer must error");
15089 let msg = format!("{err}");
15090 assert!(msg.contains("multi-output"), "error message: {msg}");
15091 }
15092
15093 /// `NodeHandle::view(slot)` with slot OOB returns Err.
15094 #[test]
15095 fn tensor_view_oob_slot_errors() {
15096 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15097 let producer_id = {
15098 let mut g = graph.write().unwrap();
15099 let id = g.push(Node {
15100 op: Op::Const,
15101 inputs: vec![],
15102 shape: Shape::from_dims(&[2, 3]),
15103 dtype: DType::F32,
15104 });
15105 let (views, _) = two_slot_views();
15106 g.set_output_views(id, views.into())
15107 .expect("valid 2-slot specs");
15108 id
15109 };
15110 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15111 let err = producer
15112 .view(2)
15113 .expect_err("slot 2 of a 2-slot producer must error");
15114 let msg = format!("{err}");
15115 assert!(msg.contains("out of range"), "error message: {msg}");
15116 }
15117
15118 /// `NodeHandle::view(slot)` produces a tensor whose shape/dtype match
15119 /// the slot spec; producer's primary shape stays as slot 0's. The
15120 /// View node holds the producer in `inputs[0]`.
15121 #[test]
15122 fn tensor_view_shape_dtype_from_slot() {
15123 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15124 let producer_id = {
15125 let mut g = graph.write().unwrap();
15126 let id = g.push(Node {
15127 op: Op::Const,
15128 inputs: vec![],
15129 shape: Shape::from_dims(&[2, 3]),
15130 dtype: DType::F32,
15131 });
15132 let (views, _) = two_slot_views();
15133 g.set_output_views(id, views.into())
15134 .expect("valid 2-slot specs");
15135 id
15136 };
15137 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15138 let v0 = producer.view(0).expect("slot 0 view");
15139 assert_eq!(v0.shape(), Shape::from_dims(&[2, 3]));
15140 assert_eq!(v0.dtype(), DType::F32);
15141 let v1 = producer.view(1).expect("slot 1 view");
15142 assert_eq!(v1.shape(), Shape::from_dims(&[2, 4]));
15143 assert_eq!(v1.dtype(), DType::F32);
15144 // View node carries the producer in inputs[0] and the slot
15145 // index in the Op variant — verify the Graph state directly.
15146 let g = graph.read().unwrap();
15147 let v1_node = g.node(v1.id());
15148 assert_eq!(v1_node.inputs, vec![producer_id]);
15149 assert!(matches!(v1_node.op, Op::View { slot: 1 }));
15150 // Slot 0 starts at byte_offset 0 + contiguous → layout
15151 // matches Layout::contiguous(slot0.shape) → no side-table
15152 // entry (the contiguous fallback covers it).
15153 assert!(!g.has_explicit_layout(v0.id()));
15154 // Slot 1 starts at byte_offset 24 (= 6 F32 elements past
15155 // slot 0). Session 4 bakes that into the layout's
15156 // start_offset so a downstream kernel reading the producer's
15157 // bytes as F32 elements lands on slot 1's first byte. Side-
15158 // table entry is mandatory.
15159 assert!(g.has_explicit_layout(v1.id()));
15160 let l1 = g.layout(v1.id());
15161 assert_eq!(
15162 l1.start_offset(),
15163 6,
15164 "slot 1 byte_offset 24 / 4 = 6 F32 elements"
15165 );
15166 assert_eq!(l1.shape(), &Shape::from_dims(&[2, 4]));
15167 }
15168
15169 /// `NodeHandle::view(slot)` over a slot whose layout is non-contiguous
15170 /// (strided) populates the Graph's layout side-table with the
15171 /// slot's layout — so downstream consumers see the strided view.
15172 #[test]
15173 fn tensor_view_propagates_non_contiguous_slot_layout() {
15174 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15175 let strided_shape = Shape::from_dims(&[2, 3]);
15176 let strided_layout = Layout::contiguous(strided_shape.clone())
15177 .transpose(0, 1)
15178 .expect("transpose [2,3] -> [3,2]");
15179 // Slot 0 = primary (contiguous, matches producer's Node shape).
15180 let s0 = OutputView {
15181 byte_offset: 0,
15182 len_elements: strided_shape.elem_count(),
15183 dtype: DType::F32,
15184 shape: strided_shape.clone(),
15185 layout: Layout::contiguous(strided_shape.clone()),
15186 name: Some("primary"),
15187 };
15188 // Slot 1 = strided projection. Same byte range as slot 0; the
15189 // shape after transpose is [3, 2]; layout's start offset stays
15190 // within the slot.
15191 let s1 = OutputView {
15192 byte_offset: 0,
15193 len_elements: strided_shape.elem_count(),
15194 dtype: DType::F32,
15195 shape: Shape::from_dims(&[3, 2]),
15196 layout: strided_layout.clone(),
15197 name: Some("strided_view"),
15198 };
15199 let producer_id = {
15200 let mut g = graph.write().unwrap();
15201 let id = g.push(Node {
15202 op: Op::Const,
15203 inputs: vec![],
15204 shape: strided_shape.clone(),
15205 dtype: DType::F32,
15206 });
15207 g.set_output_views(id, vec![s0, s1].into())
15208 .expect("valid 2-slot strided spec");
15209 id
15210 };
15211 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15212 let v1 = producer.view(1).expect("strided slot view");
15213 let g = graph.read().unwrap();
15214 assert!(
15215 g.has_explicit_layout(v1.id()),
15216 "strided slot must populate Graph::layouts side-table",
15217 );
15218 let read_layout = g.layout(v1.id());
15219 assert_eq!(read_layout.shape(), strided_layout.shape());
15220 assert_eq!(read_layout.stride(), strided_layout.stride());
15221 }
15222
15223 /// `NodeHandle::view_owned(slot)` produces the same shape/dtype as
15224 /// `NodeHandle::view(slot)` but its output layout is ALWAYS contiguous
15225 /// — the forward memcpy produces a fresh standalone buffer, so
15226 /// the slot's (possibly strided) layout is not propagated.
15227 #[test]
15228 fn tensor_view_owned_layout_is_contiguous() {
15229 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15230 let strided_shape = Shape::from_dims(&[2, 3]);
15231 let strided_layout = Layout::contiguous(strided_shape.clone())
15232 .transpose(0, 1)
15233 .expect("transpose [2,3] -> [3,2]");
15234 let s0 = OutputView {
15235 byte_offset: 0,
15236 len_elements: strided_shape.elem_count(),
15237 dtype: DType::F32,
15238 shape: strided_shape.clone(),
15239 layout: Layout::contiguous(strided_shape.clone()),
15240 name: None,
15241 };
15242 let s1 = OutputView {
15243 byte_offset: 0,
15244 len_elements: strided_shape.elem_count(),
15245 dtype: DType::F32,
15246 shape: Shape::from_dims(&[3, 2]),
15247 layout: strided_layout,
15248 name: None,
15249 };
15250 let producer_id = {
15251 let mut g = graph.write().unwrap();
15252 let id = g.push(Node {
15253 op: Op::Const,
15254 inputs: vec![],
15255 shape: strided_shape,
15256 dtype: DType::F32,
15257 });
15258 g.set_output_views(id, vec![s0, s1].into())
15259 .expect("valid 2-slot specs");
15260 id
15261 };
15262 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15263 let v1 = producer.view_owned(1).expect("ViewOwned slot 1");
15264 assert_eq!(v1.shape(), Shape::from_dims(&[3, 2]));
15265 assert_eq!(v1.dtype(), DType::F32);
15266 let g = graph.read().unwrap();
15267 // ViewOwned is a fresh allocation — no explicit layout entry,
15268 // contiguous layout falls through.
15269 assert!(!g.has_explicit_layout(v1.id()));
15270 let owned_node = g.node(v1.id());
15271 assert!(matches!(owned_node.op, Op::ViewOwned { slot: 1 }));
15272 }
15273
15274 // ------------------------------------------------------------------
15275 // Session 2: bundled allocator + FusedOpEntry::output_views +
15276 // View-vs-ViewOwned planner pass. The tests use the bundled
15277 // storage allocator and a synthetic 2-output FusedOp entry — no
15278 // real fused-op author migrates in Session 2; the
15279 // selective-scan-ssd-chunk-multi-output-followup session lights
15280 // up the first real consumer.
15281 // ------------------------------------------------------------------
15282
15283 use fuel_backend_contract::storage::allocate_bundled_storage;
15284 use fuel_ir::storage::OutputViewSpec;
15285
15286 /// `allocate_bundled_storage` allocates one Storage on the device,
15287 /// attaches the bundle, and slot lookups report the spec-derived
15288 /// byte_offsets.
15289 #[test]
15290 fn allocate_bundled_storage_two_slot_roundtrip() {
15291 let dev = cpu_dev();
15292 let specs = vec![
15293 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15294 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15295 ];
15296 let s =
15297 allocate_bundled_storage(dev.as_ref(), &specs).expect("two-slot F32 alloc succeeds");
15298 assert!(s.is_bundled());
15299 assert_eq!(s.slot_count(), 2);
15300 assert_eq!(s.primary_dtype(), DType::F32);
15301 let v0 = s.slot_view(0).unwrap();
15302 let v1 = s.slot_view(1).unwrap();
15303 assert_eq!(v0.byte_offset, 0);
15304 assert_eq!(v0.shape, Shape::from_dims(&[2, 3]));
15305 assert_eq!(v1.byte_offset, 24);
15306 assert_eq!(v1.shape, Shape::from_dims(&[2, 4]));
15307 }
15308
15309 /// `allocate_bundled_storage` handles mixed F32 + F64 slots — slot
15310 /// 0 is primary (F32), slot 1's bytes are aligned to its F64
15311 /// boundary, and the underlying allocation has enough flat F32
15312 /// elements to cover the total bundle bytes.
15313 #[test]
15314 fn allocate_bundled_storage_mixed_dtype() {
15315 let dev = cpu_dev();
15316 let specs = vec![
15317 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[6])),
15318 OutputViewSpec::contiguous(DType::F64, Shape::from_dims(&[3])),
15319 ];
15320 let s = allocate_bundled_storage(dev.as_ref(), &specs).expect("mixed-dtype alloc succeeds");
15321 assert_eq!(s.primary_dtype(), DType::F32);
15322 let v0 = s.slot_view(0).unwrap();
15323 let v1 = s.slot_view(1).unwrap();
15324 assert_eq!(v0.dtype, DType::F32);
15325 assert_eq!(v1.dtype, DType::F64);
15326 assert_eq!(v0.byte_offset, 0);
15327 // F32[6] = 24 bytes; 24 is already multiple of 8, so v1
15328 // starts at 24 without further padding.
15329 assert_eq!(v1.byte_offset, 24);
15330 }
15331
15332 /// `allocate_bundled_storage` propagates compose_bundle errors —
15333 /// an empty spec list errors out before touching the device.
15334 #[test]
15335 fn allocate_bundled_storage_rejects_empty() {
15336 let dev = cpu_dev();
15337 let err = allocate_bundled_storage(dev.as_ref(), &[]).expect_err("empty specs error");
15338 assert!(format!("{err}").contains("non-empty"));
15339 }
15340
15341 /// The two SelectiveScan / SsdChunkScan migrations from item 3
15342 /// (2026-06-01) are the first `default_registry` entries to
15343 /// declare `output_views`. Any new multi-output op author should
15344 /// extend the expected set here.
15345 #[test]
15346 fn default_registry_multi_output_entries() {
15347 let reg = crate::registry::default_registry();
15348 let mut multi_out_names: Vec<&'static str> = reg
15349 .entries_iter()
15350 .filter(|e| e.output_views.is_some())
15351 .map(|e| e.name)
15352 .collect();
15353 multi_out_names.sort();
15354 assert_eq!(
15355 multi_out_names,
15356 vec!["SelectiveScan", "SsdChunkScan"],
15357 "the multi-output registry set should match the item-3 \
15358 migrations (SelectiveScan + SsdChunkScan); add new \
15359 multi-output ops to this list as they migrate",
15360 );
15361 }
15362
15363 /// Authoring-contract invariant: for every multi-output entry in
15364 /// the process-wide registry, `shape_rule(inputs)` MUST equal
15365 /// `output_views(inputs)[0].shape` and `dtype_rule(inputs)` MUST
15366 /// equal `output_views(inputs)[0].dtype`. Slot 0 is the primary
15367 /// and the bundled-allocation contract assumes the producer's
15368 /// `Node.shape`/`Node.dtype` reflect it.
15369 #[test]
15370 fn multi_output_entries_slot_0_matches_primary_rules() {
15371 use crate::registry::FusedOpParams;
15372 let reg = crate::registry::default_registry();
15373
15374 // Each multi-output entry needs a representative input batch
15375 // (shapes + dtypes + params) that satisfies its
15376 // shape_rule/dtype_rule preconditions. The check below runs
15377 // once per entry using these fixtures.
15378 struct Fixture {
15379 shapes: Vec<Shape>,
15380 dtypes: Vec<DType>,
15381 params: FusedOpParams,
15382 }
15383 fn selective_scan_fixture() -> Fixture {
15384 Fixture {
15385 shapes: vec![
15386 Shape::from_dims(&[2, 4, 8]), // u: [batch, seqlen, dim]
15387 Shape::from_dims(&[2, 4, 8]), // delta: same
15388 Shape::from_dims(&[8, 16]), // a: [dim, dstate]
15389 Shape::from_dims(&[2, 4, 16]), // b: [batch, seqlen, dstate]
15390 Shape::from_dims(&[2, 4, 16]), // c: same
15391 ],
15392 dtypes: vec![DType::F32; 5],
15393 params: FusedOpParams::SelectiveScan {
15394 delta_softplus: false,
15395 },
15396 }
15397 }
15398 fn ssd_chunk_scan_fixture() -> Fixture {
15399 Fixture {
15400 shapes: vec![
15401 Shape::from_dims(&[2, 4, 3, 8]), // x: [batch, seqlen, heads, head_dim]
15402 Shape::from_dims(&[2, 4, 3]), // dt: [batch, seqlen, heads]
15403 Shape::from_dims(&[3]), // a: [heads]
15404 Shape::from_dims(&[2, 4, 3, 16]), // b: [batch, seqlen, heads, state_dim]
15405 Shape::from_dims(&[2, 4, 3, 16]), // c: same
15406 ],
15407 dtypes: vec![DType::F32; 5],
15408 params: FusedOpParams::SsdChunkScan { chunk_size: 4 },
15409 }
15410 }
15411
15412 for entry in reg.entries_iter().filter(|e| e.output_views.is_some()) {
15413 let fx = match entry.name {
15414 "SelectiveScan" => selective_scan_fixture(),
15415 "SsdChunkScan" => ssd_chunk_scan_fixture(),
15416 other => panic!(
15417 "multi_output_entries_slot_0_matches_primary_rules: \
15418 no fixture for new multi-output entry {other:?}. \
15419 Add one to this test as you register a new op.",
15420 ),
15421 };
15422 let primary_shape = (entry.shape_rule)(&fx.shapes, &fx.params);
15423 let primary_dtype = (entry.dtype_rule)(&fx.dtypes, &fx.params);
15424 let specs = entry.output_views.unwrap()(&fx.shapes, &fx.dtypes, &fx.params);
15425 assert!(
15426 !specs.is_empty(),
15427 "{}: output_views returned empty Vec (multi-output ops \
15428 must have ≥ 1 slot)",
15429 entry.name,
15430 );
15431 assert_eq!(
15432 specs[0].shape, primary_shape,
15433 "{}: output_views[0].shape {:?} must equal shape_rule \
15434 {:?} (slot 0 is the primary; Node::shape reflects it)",
15435 entry.name, specs[0].shape, primary_shape,
15436 );
15437 assert_eq!(
15438 specs[0].dtype, primary_dtype,
15439 "{}: output_views[0].dtype {:?} must equal dtype_rule \
15440 {:?} (slot 0 is the primary; Node::dtype reflects it)",
15441 entry.name, specs[0].dtype, primary_dtype,
15442 );
15443 // Layout-shape coherence: each slot's layout shape must
15444 // equal its declared shape (the same invariant
15445 // set_output_views enforces at graph-build time).
15446 for (i, spec) in specs.iter().enumerate() {
15447 assert_eq!(
15448 spec.layout.shape(),
15449 &spec.shape,
15450 "{}: slot {i} layout.shape() {:?} disagrees with \
15451 declared spec.shape {:?}",
15452 entry.name,
15453 spec.layout.shape(),
15454 spec.shape,
15455 );
15456 }
15457 }
15458 }
15459
15460 /// Build a synthetic multi-output `FusedOpEntry` to exercise the
15461 /// authoring contract end-to-end without polluting the production
15462 /// registry. The output_views fn returns a 2-slot spec list whose
15463 /// slot 0 matches shape_rule / dtype_rule (the primary).
15464 fn synthetic_two_output_entry() -> crate::registry::FusedOpEntry {
15465 fn shape(_: &[Shape], _: &crate::registry::FusedOpParams) -> Shape {
15466 Shape::from_dims(&[2, 3])
15467 }
15468 fn dtype(_: &[DType], _: &crate::registry::FusedOpParams) -> DType {
15469 DType::F32
15470 }
15471 fn ovs(
15472 _: &[Shape],
15473 _: &[DType],
15474 _: &crate::registry::FusedOpParams,
15475 ) -> Vec<OutputViewSpec> {
15476 vec![
15477 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15478 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15479 ]
15480 }
15481 crate::registry::FusedOpEntry {
15482 destructive_input: None,
15483 id: crate::registry::FusedOps::SOFTMAX_LAST_DIM, // any id; not registered
15484 name: "<synthetic-2-output>",
15485 family: crate::registry::FusedOpFamily::Forward,
15486 pattern: crate::registry::SubgraphPattern::Callable(|_g, _id| None),
15487 decompose: |_g, id, _p| id,
15488 backward: crate::registry::BackwardKind::NotDifferentiable,
15489 shape_rule: shape,
15490 dtype_rule: dtype,
15491 output_views: Some(ovs),
15492 }
15493 }
15494
15495 /// The synthetic entry's `output_views` matches the
15496 /// `shape_rule`/`dtype_rule` contract on slot 0.
15497 #[test]
15498 fn synthetic_entry_output_views_matches_primary_contract() {
15499 let entry = synthetic_two_output_entry();
15500 let ovs_fn = entry.output_views.expect("synthetic entry is multi-output");
15501 let specs = ovs_fn(&[], &[], &crate::registry::FusedOpParams::SoftmaxLastDim);
15502 assert_eq!(specs.len(), 2);
15503 assert_eq!(
15504 specs[0].dtype,
15505 (entry.dtype_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15506 );
15507 assert_eq!(
15508 specs[0].shape,
15509 (entry.shape_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15510 );
15511 }
15512
15513 /// Build a producer Const node and declare it multi-output via
15514 /// `Graph::set_output_views`. Returns the producer's NodeId and a
15515 /// SharedGraph handle.
15516 fn multi_output_producer(slots: Vec<OutputView>) -> (SharedGraph, NodeId) {
15517 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15518 let id = {
15519 let mut g = graph.write().unwrap();
15520 let id = g.push(Node {
15521 op: Op::Const,
15522 inputs: vec![],
15523 shape: slots[0].shape.clone(),
15524 dtype: slots[0].dtype,
15525 });
15526 g.set_output_views(id, slots.into())
15527 .expect("valid synthetic specs");
15528 id
15529 };
15530 (graph, id)
15531 }
15532
15533 /// Two slots, both consumed at the same topo depth → planner does
15534 /// nothing (symmetric lifetimes, bundle drops naturally).
15535 #[test]
15536 fn promote_views_symmetric_lifetimes_is_noop() {
15537 let slot_specs = vec![
15538 OutputView {
15539 byte_offset: 0,
15540 len_elements: 6,
15541 dtype: DType::F32,
15542 shape: Shape::from_dims(&[2, 3]),
15543 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15544 name: Some("y"),
15545 },
15546 OutputView {
15547 byte_offset: 24,
15548 len_elements: 8,
15549 dtype: DType::F32,
15550 shape: Shape::from_dims(&[2, 4]),
15551 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15552 name: Some("state"),
15553 },
15554 ];
15555 let (graph, producer_id) = multi_output_producer(slot_specs);
15556 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15557 // Each slot has exactly one View, consumed at the same depth
15558 // (a no-op Relu downstream of each).
15559 let v0 = producer.view(0).expect("slot 0 view");
15560 let v1 = producer.view(1).expect("slot 1 view");
15561 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15562 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15563 let roots = {
15564 let mut g = graph.write().unwrap();
15565 let r0 = g.push(Node {
15566 op: Op::Relu,
15567 inputs: vec![v0_id],
15568 shape: v0_shape,
15569 dtype: v0_dtype,
15570 });
15571 let r1 = g.push(Node {
15572 op: Op::Relu,
15573 inputs: vec![v1_id],
15574 shape: v1_shape,
15575 dtype: v1_dtype,
15576 });
15577 vec![r0, r1]
15578 };
15579 let promotions = {
15580 let mut g = graph.write().unwrap();
15581 crate::opt::promote_views_for_liveness(&mut g, &roots)
15582 };
15583 assert_eq!(
15584 promotions, 0,
15585 "symmetric lifetimes shouldn't promote anything"
15586 );
15587 }
15588
15589 /// Asymmetric lifetimes: slot 0 consumed early, slot 1 consumed
15590 /// late → planner promotes slot 1's View to ViewOwned.
15591 #[test]
15592 fn promote_views_asymmetric_promotes_long_lived_slot() {
15593 let slot_specs = vec![
15594 OutputView {
15595 byte_offset: 0,
15596 len_elements: 6,
15597 dtype: DType::F32,
15598 shape: Shape::from_dims(&[2, 3]),
15599 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15600 name: Some("y"),
15601 },
15602 OutputView {
15603 byte_offset: 24,
15604 len_elements: 6,
15605 dtype: DType::F32,
15606 shape: Shape::from_dims(&[2, 3]),
15607 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15608 name: Some("state"),
15609 },
15610 ];
15611 let (graph, producer_id) = multi_output_producer(slot_specs);
15612 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15613 let v_y = producer.view(0).expect("slot 0 view");
15614 let v_state = producer.view(1).expect("slot 1 view");
15615 // Slot 0 ("y") consumed at depth 1 (single Relu).
15616 // Slot 1 ("state") consumed at a much deeper chain — Relu →
15617 // Relu → Relu. Topo positions push state's last-use later
15618 // than y's, triggering promotion of state's View.
15619 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15620 let (v_state_id, v_state_shape, v_state_dtype) =
15621 (v_state.id(), v_state.shape(), v_state.dtype());
15622 let roots = {
15623 let mut g = graph.write().unwrap();
15624 let y_relu = g.push(Node {
15625 op: Op::Relu,
15626 inputs: vec![v_y_id],
15627 shape: v_y_shape,
15628 dtype: v_y_dtype,
15629 });
15630 let s1 = g.push(Node {
15631 op: Op::Relu,
15632 inputs: vec![v_state_id],
15633 shape: v_state_shape.clone(),
15634 dtype: v_state_dtype,
15635 });
15636 let s2 = g.push(Node {
15637 op: Op::Relu,
15638 inputs: vec![s1],
15639 shape: v_state_shape.clone(),
15640 dtype: v_state_dtype,
15641 });
15642 let s3 = g.push(Node {
15643 op: Op::Relu,
15644 inputs: vec![s2],
15645 shape: v_state_shape,
15646 dtype: v_state_dtype,
15647 });
15648 vec![y_relu, s3]
15649 };
15650 let promotions = {
15651 let mut g = graph.write().unwrap();
15652 crate::opt::promote_views_for_liveness(&mut g, &roots)
15653 };
15654 assert_eq!(
15655 promotions, 1,
15656 "exactly the long-lived slot 1 View should promote"
15657 );
15658 // Slot 1's consumer (the first Relu in the long chain) now
15659 // reads a fresh Op::ViewOwned node, not the old Op::View.
15660 let g = graph.read().unwrap();
15661 // Find the new ViewOwned node — it was pushed AFTER the
15662 // existing nodes, so it's the last node in the arena. Its op
15663 // must be Op::ViewOwned { slot: 1 } and its input must be the
15664 // producer.
15665 let last_id = NodeId(g.len() - 1);
15666 let last_node = g.node(last_id);
15667 assert!(matches!(last_node.op, Op::ViewOwned { slot: 1 }));
15668 assert_eq!(last_node.inputs, vec![producer_id]);
15669 // The slot 0 View is untouched — still Op::View.
15670 let v_y_node = g.node(v_y_id);
15671 assert!(matches!(v_y_node.op, Op::View { slot: 0 }));
15672 // The old slot 1 View stays in the arena (orphaned). No
15673 // consumer points at it anymore.
15674 let v_state_node = g.node(v_state_id);
15675 assert!(matches!(v_state_node.op, Op::View { slot: 1 }));
15676 }
15677
15678 /// Running the pass twice on the same graph promotes nothing on
15679 /// the second call — `Op::ViewOwned` is a fixpoint (skipped by
15680 /// the planner because `is_owned` is true).
15681 #[test]
15682 fn promote_views_idempotent() {
15683 let slot_specs = vec![
15684 OutputView {
15685 byte_offset: 0,
15686 len_elements: 4,
15687 dtype: DType::F32,
15688 shape: Shape::from_dims(&[2, 2]),
15689 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15690 name: None,
15691 },
15692 OutputView {
15693 byte_offset: 16,
15694 len_elements: 4,
15695 dtype: DType::F32,
15696 shape: Shape::from_dims(&[2, 2]),
15697 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15698 name: None,
15699 },
15700 ];
15701 let (graph, producer_id) = multi_output_producer(slot_specs);
15702 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15703 let v_y = producer.view(0).expect("slot 0 view");
15704 let v_state = producer.view(1).expect("slot 1 view");
15705 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15706 let (v_state_id, v_state_shape, v_state_dtype) =
15707 (v_state.id(), v_state.shape(), v_state.dtype());
15708 let roots = {
15709 let mut g = graph.write().unwrap();
15710 let y_r = g.push(Node {
15711 op: Op::Relu,
15712 inputs: vec![v_y_id],
15713 shape: v_y_shape,
15714 dtype: v_y_dtype,
15715 });
15716 let s1 = g.push(Node {
15717 op: Op::Relu,
15718 inputs: vec![v_state_id],
15719 shape: v_state_shape.clone(),
15720 dtype: v_state_dtype,
15721 });
15722 let s2 = g.push(Node {
15723 op: Op::Relu,
15724 inputs: vec![s1],
15725 shape: v_state_shape,
15726 dtype: v_state_dtype,
15727 });
15728 vec![y_r, s2]
15729 };
15730 let first = {
15731 let mut g = graph.write().unwrap();
15732 crate::opt::promote_views_for_liveness(&mut g, &roots)
15733 };
15734 let second = {
15735 let mut g = graph.write().unwrap();
15736 crate::opt::promote_views_for_liveness(&mut g, &roots)
15737 };
15738 assert_eq!(first, 1, "first call promotes the long-lived slot");
15739 assert_eq!(
15740 second, 0,
15741 "second call is idempotent — no further promotions"
15742 );
15743 }
15744
15745 /// Graph with no multi-output producers: pass returns 0 and
15746 /// touches nothing.
15747 #[test]
15748 fn promote_views_noop_on_graph_without_multi_output() {
15749 let mut g = Graph::new();
15750 let a = g.push(Node {
15751 op: Op::Const,
15752 inputs: vec![],
15753 shape: Shape::from_dims(&[2, 3]),
15754 dtype: DType::F32,
15755 });
15756 let r = g.push(Node {
15757 op: Op::Relu,
15758 inputs: vec![a],
15759 shape: Shape::from_dims(&[2, 3]),
15760 dtype: DType::F32,
15761 });
15762 let n_before = g.len();
15763 let promotions = crate::opt::promote_views_for_liveness(&mut g, &[r]);
15764 assert_eq!(promotions, 0);
15765 assert_eq!(g.len(), n_before, "no node should have been added");
15766 }
15767
15768 // ------------------------------------------------------------------
15769 // Session 3: scheduler / destructive-cleanup integration —
15770 // bundle-aware liveness. A destructive op on a multi-output
15771 // producer (or any of its Views) must run after every reader of
15772 // every other View, because all Views share the bundle's storage
15773 // Arc. Op::ViewOwned is excluded — it forks a fresh standalone
15774 // Storage at execute time.
15775 // ------------------------------------------------------------------
15776
15777 /// Helper: build two contiguous slot specs for a producer of
15778 /// `Node::shape = [2, 3] F32`. Slot 0 is the primary (matches the
15779 /// producer's Node::shape/dtype, required by set_output_views);
15780 /// slot 1 carries a sibling shape that doesn't collide with the
15781 /// primary.
15782 fn two_slot_views_2x3_and_2x4() -> Vec<OutputView> {
15783 vec![
15784 OutputView {
15785 byte_offset: 0,
15786 len_elements: 6,
15787 dtype: DType::F32,
15788 shape: Shape::from_dims(&[2, 3]),
15789 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15790 name: Some("y"),
15791 },
15792 OutputView {
15793 byte_offset: 24,
15794 len_elements: 8,
15795 dtype: DType::F32,
15796 shape: Shape::from_dims(&[2, 4]),
15797 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15798 name: Some("state"),
15799 },
15800 ]
15801 }
15802
15803 /// Op::Release targeting a multi-output producer pins after every
15804 /// consumer of any View of that producer. Without bundle-aware
15805 /// aliasing the Views' downstream Relu nodes would be missed and
15806 /// could race the Release.
15807 #[test]
15808 fn derive_ordering_release_of_bundled_producer_pins_after_view_consumers() {
15809 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15810 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15811 let v0 = producer.view(0).expect("slot 0 view");
15812 let v1 = producer.view(1).expect("slot 1 view");
15813 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15814 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15815 let (r0, r1, release_id) = {
15816 let mut g = graph.write().unwrap();
15817 let r0 = g.push(Node {
15818 op: Op::Relu,
15819 inputs: vec![v0_id],
15820 shape: v0_shape,
15821 dtype: v0_dtype,
15822 });
15823 let r1 = g.push(Node {
15824 op: Op::Relu,
15825 inputs: vec![v1_id],
15826 shape: v1_shape,
15827 dtype: v1_dtype,
15828 });
15829 let release = g.push(Node {
15830 op: Op::Release,
15831 inputs: vec![producer_id],
15832 shape: Shape::from_dims(&[0]),
15833 dtype: DType::F32,
15834 });
15835 (r0, r1, release)
15836 };
15837 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r0, r1, release_id]);
15838 let deps = ord.deps_of(release_id);
15839 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15840 assert!(
15841 dep_set.contains(&r0),
15842 "Release must run after the slot-0 View's consumer (r0)",
15843 );
15844 assert!(
15845 dep_set.contains(&r1),
15846 "Release must run after the slot-1 View's consumer (r1) — \
15847 both Views share the bundle Arc",
15848 );
15849 }
15850
15851 /// Destructive op targeting one of a bundle's Op::View nodes
15852 /// pins after every sibling View's consumers too — every View
15853 /// of the producer shares the bundle's Arc, so writing through
15854 /// one of them clobbers the bytes the others read.
15855 #[test]
15856 fn derive_ordering_destructive_on_view_pins_sibling_view_consumers() {
15857 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15858 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15859 let v0 = producer.view(0).expect("slot 0 view");
15860 let v1 = producer.view(1).expect("slot 1 view");
15861 let (v0_id, _v0_shape, _v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15862 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15863 // Destructive op (Release) targets v0 directly — its
15864 // alias set must reach v1's consumer via the producer-sibling
15865 // hop in collect_alias_set.
15866 let (r1, release_id) = {
15867 let mut g = graph.write().unwrap();
15868 let r1 = g.push(Node {
15869 op: Op::Relu,
15870 inputs: vec![v1_id],
15871 shape: v1_shape,
15872 dtype: v1_dtype,
15873 });
15874 let release = g.push(Node {
15875 op: Op::Release,
15876 inputs: vec![v0_id],
15877 shape: Shape::from_dims(&[0]),
15878 dtype: DType::F32,
15879 });
15880 (r1, release)
15881 };
15882 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r1, release_id]);
15883 let deps = ord.deps_of(release_id);
15884 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15885 assert!(
15886 dep_set.contains(&r1),
15887 "Release targeting slot-0 View must pin after sibling slot-1 \
15888 View's consumer (r1) — both share the bundle's storage Arc",
15889 );
15890 }
15891
15892 /// Op::ViewOwned does NOT extend the alias set: its forward
15893 /// memcpy produces an independent Storage. derive_ordering must
15894 /// still pin Release after the ViewOwned itself (via the standard
15895 /// data-dependency: ViewOwned consumes the producer), but
15896 /// downstream consumers of the ViewOwned are NOT in the alias
15897 /// set's reader sweep — they read independent bytes and may run
15898 /// freely after the Release.
15899 #[test]
15900 fn derive_ordering_view_owned_is_not_alias_extending() {
15901 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15902 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15903 // Slot 0 → View (shared Arc); slot 1 → ViewOwned (independent).
15904 let v_view = producer.view(0).expect("slot 0 view");
15905 let v_owned = producer.view_owned(1).expect("slot 1 viewowned");
15906 let (v_view_id, _, _) = (v_view.id(), v_view.shape(), v_view.dtype());
15907 let (v_owned_id, v_owned_shape, v_owned_dtype) =
15908 (v_owned.id(), v_owned.shape(), v_owned.dtype());
15909 let (consumer_of_owned, release_id) = {
15910 let mut g = graph.write().unwrap();
15911 let consumer = g.push(Node {
15912 op: Op::Relu,
15913 inputs: vec![v_owned_id],
15914 shape: v_owned_shape,
15915 dtype: v_owned_dtype,
15916 });
15917 let release = g.push(Node {
15918 op: Op::Release,
15919 inputs: vec![producer_id],
15920 shape: Shape::from_dims(&[0]),
15921 dtype: DType::F32,
15922 });
15923 (consumer, release)
15924 };
15925 let ord =
15926 crate::opt::derive_ordering(&graph.read().unwrap(), &[consumer_of_owned, release_id]);
15927 let deps = ord.deps_of(release_id);
15928 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15929 // Release MUST wait for ViewOwned to run (ViewOwned reads
15930 // the producer's bytes during its memcpy).
15931 assert!(
15932 dep_set.contains(&v_owned_id),
15933 "Release must pin after ViewOwned — ViewOwned reads the \
15934 producer's bundle during its memcpy phase",
15935 );
15936 // Release must NOT depend on the ViewOwned's downstream
15937 // consumer — that consumer reads ViewOwned's independent
15938 // bytes, not the producer's bundle.
15939 assert!(
15940 !dep_set.contains(&consumer_of_owned),
15941 "Release must NOT pin after consumers of ViewOwned — \
15942 ViewOwned forks a fresh Storage; its consumers don't \
15943 read the producer's bundle",
15944 );
15945 // Op::View's consumers stay reached via the alias chain; here
15946 // there are none (v_view has no consumer), so v_view itself
15947 // is the only alias-set entry beyond the producer.
15948 let _ = v_view_id;
15949 }
15950
15951 /// Long-tail bundle-aware schedule: a producer with three Views,
15952 /// each consumed by a chain of different depth, and a destructive
15953 /// Release on the producer. The Release must end up after every
15954 /// terminal consumer of every chain — bundle-as-single-eviction-
15955 /// unit semantics fall out of derive_ordering's alias-set walk
15956 /// reaching each chain's leaf via the producer-then-View hop.
15957 #[test]
15958 fn derive_ordering_bundle_release_pins_after_all_chains() {
15959 // Build a 3-slot bundle. Slot 0 primary [2,3] F32 satisfies
15960 // the producer's Node::shape/dtype constraint; slots 1 + 2
15961 // add sibling shapes.
15962 let slot_specs = vec![
15963 OutputView {
15964 byte_offset: 0,
15965 len_elements: 6,
15966 dtype: DType::F32,
15967 shape: Shape::from_dims(&[2, 3]),
15968 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15969 name: Some("a"),
15970 },
15971 OutputView {
15972 byte_offset: 24,
15973 len_elements: 4,
15974 dtype: DType::F32,
15975 shape: Shape::from_dims(&[2, 2]),
15976 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15977 name: Some("b"),
15978 },
15979 OutputView {
15980 byte_offset: 40,
15981 len_elements: 8,
15982 dtype: DType::F32,
15983 shape: Shape::from_dims(&[2, 4]),
15984 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15985 name: Some("c"),
15986 },
15987 ];
15988 let (graph, producer_id) = multi_output_producer(slot_specs);
15989 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15990 let v0 = producer.view(0).unwrap();
15991 let v1 = producer.view(1).unwrap();
15992 let v2 = producer.view(2).unwrap();
15993 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15994 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15995 let (v2_id, v2_shape, v2_dtype) = (v2.id(), v2.shape(), v2.dtype());
15996 let (leaf_a, leaf_b, leaf_c, release_id) = {
15997 let mut g = graph.write().unwrap();
15998 let leaf_a = g.push(Node {
15999 op: Op::Relu,
16000 inputs: vec![v0_id],
16001 shape: v0_shape,
16002 dtype: v0_dtype,
16003 });
16004 let b1 = g.push(Node {
16005 op: Op::Relu,
16006 inputs: vec![v1_id],
16007 shape: v1_shape.clone(),
16008 dtype: v1_dtype,
16009 });
16010 let leaf_b = g.push(Node {
16011 op: Op::Relu,
16012 inputs: vec![b1],
16013 shape: v1_shape,
16014 dtype: v1_dtype,
16015 });
16016 let c1 = g.push(Node {
16017 op: Op::Relu,
16018 inputs: vec![v2_id],
16019 shape: v2_shape.clone(),
16020 dtype: v2_dtype,
16021 });
16022 let c2 = g.push(Node {
16023 op: Op::Relu,
16024 inputs: vec![c1],
16025 shape: v2_shape.clone(),
16026 dtype: v2_dtype,
16027 });
16028 let leaf_c = g.push(Node {
16029 op: Op::Relu,
16030 inputs: vec![c2],
16031 shape: v2_shape,
16032 dtype: v2_dtype,
16033 });
16034 let release = g.push(Node {
16035 op: Op::Release,
16036 inputs: vec![producer_id],
16037 shape: Shape::from_dims(&[0]),
16038 dtype: DType::F32,
16039 });
16040 (leaf_a, leaf_b, leaf_c, release)
16041 };
16042 let ord = crate::opt::derive_ordering(
16043 &graph.read().unwrap(),
16044 &[leaf_a, leaf_b, leaf_c, release_id],
16045 );
16046 let deps = ord.deps_of(release_id);
16047 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16048 // The direct readers of any View are the FIRST relu in each
16049 // chain — those are the nodes that read the bundle's bytes.
16050 // Every consumer further down reads its predecessor's
16051 // standalone output Storage, so they aren't in the alias-set
16052 // reader sweep. Verify the Release pins on the direct
16053 // readers — sufficient for bundle-single-eviction safety
16054 // because the chains are themselves data-dep ordered after
16055 // their direct readers.
16056 assert!(
16057 dep_set.contains(&leaf_a),
16058 "single-Relu chain a: leaf is the direct reader",
16059 );
16060 // For the b/c chains, the direct readers are the first Relus
16061 // (b1 / c1), not the leaves. The Release must include those.
16062 // Find them by walking inputs from leaves.
16063 let g = graph.read().unwrap();
16064 let b1 = g.node(leaf_b).inputs[0];
16065 let (c2, c1) = {
16066 let c2 = g.node(leaf_c).inputs[0];
16067 let c1 = g.node(c2).inputs[0];
16068 (c2, c1)
16069 };
16070 let _ = c2;
16071 assert!(
16072 dep_set.contains(&b1),
16073 "two-Relu chain b: first Relu is the direct bundle reader",
16074 );
16075 assert!(
16076 dep_set.contains(&c1),
16077 "three-Relu chain c: first Relu is the direct bundle reader",
16078 );
16079 }
16080
16081 // ------------------------------------------------------------------
16082 // Item 4 — Op::View / Op::ViewOwned autograd emits Op::ScatterIntoSlot
16083 // ------------------------------------------------------------------
16084
16085 /// The View's backward arm pushes an `Op::ScatterIntoSlot { slot }`
16086 /// node into the gradient graph as the producer's input gradient.
16087 /// Synthetic test: build a 2-slot producer + Op::View(slot 1) +
16088 /// a Relu downstream + invoke NodeHandle::backward + walk the produced
16089 /// gradient graph and assert a ScatterIntoSlot was emitted.
16090 #[test]
16091 fn op_view_backward_emits_scatter_into_slot() {
16092 let producer_t =
16093 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
16094 let graph: SharedGraph = Arc::clone(producer_t.graph());
16095 let producer_id = producer_t.id();
16096 let view_id = {
16097 let mut g = graph.write().unwrap();
16098 let specs = two_slot_views_2x3_and_2x4();
16099 g.set_output_views(producer_id, specs.into())
16100 .expect("output_views");
16101 drop(g);
16102 let v1 = producer_t.view(1).expect("slot 1 view");
16103 v1.id()
16104 };
16105 // Build a tiny tape-tracked loss = sum(relu(v1)).
16106 let v1_tensor = NodeHandle::from_existing(Arc::clone(&graph), view_id);
16107 let relu_t = v1_tensor.relu();
16108 let loss_t = relu_t.sum_all();
16109
16110 // Take backward — exercises the View's backward arm.
16111 let grads = loss_t.backward();
16112
16113 // The producer's input gradient should be reachable via a
16114 // chain that includes an Op::ScatterIntoSlot { slot: 1 } node.
16115 let producer_tensor = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16116 let grad_for_producer = grads
16117 .get(&producer_tensor)
16118 .expect("producer has an accumulated gradient");
16119 let grad_id = grad_for_producer.id();
16120 let g = graph.read().unwrap();
16121 let scatter_present = matches!(g.node(grad_id).op, Op::ScatterIntoSlot { slot: 1 }) || {
16122 // Walk one hop back through `Op::Add` accumulations
16123 // if any.
16124 let n = g.node(grad_id);
16125 n.inputs
16126 .iter()
16127 .any(|inp| matches!(g.node(*inp).op, Op::ScatterIntoSlot { slot: 1 }))
16128 };
16129 assert!(
16130 scatter_present,
16131 "View(slot=1) backward must emit an Op::ScatterIntoSlot {{ slot: 1 }} \
16132 into the gradient graph; got grad node op = {:?}",
16133 g.node(grad_id).op,
16134 );
16135 }
16136
16137 // ----- Op::Branch inert scaffold (Phase A PR-A0 of the
16138 // "plan IS the graph" rebuild) -----
16139
16140 /// Back-compat by construction: a graph with ZERO `Op::Branch`
16141 /// nodes builds with exactly the arena it had before the variant
16142 /// existed. The locked design guarantees "a graph with zero
16143 /// Op::Branch nodes is exactly today's single-route graph" — this
16144 /// test pins that: the same builder calls produce the same node
16145 /// count, the same topo order, and not a single `Op::Branch` node.
16146 /// GAP-003 STEP 1: the panic IS reachable from the public API today.
16147 ///
16148 /// `NodeHandle::from_f32` returns `Self`, so a length/shape mismatch has
16149 /// nowhere to go but `assert_eq!` inside `from_host_buffer_on`. This test
16150 /// PASSES today and is deleted by the fix -- it exists to prove the defect
16151 /// is live from a caller's seat, not merely present in the source.
16152 /// GAP-003: a length/shape mismatch DECLINES instead of panicking.
16153 ///
16154 /// ⚠️ This started life as a `#[should_panic]` probe proving the defect was
16155 /// reachable from the public API. The bulk `.unwrap()` pass then appended
16156 /// `.unwrap()` to it, and it KEPT PASSING -- for the wrong reason: unwrapping
16157 /// an `Err` panics, and the `Err` message contains the expected substring, so
16158 /// the assertion could no longer tell "the API panics" from "I unwrapped a
16159 /// Result". A vacuous green produced by the very edit that fixed the defect.
16160 ///
16161 /// It now asserts the `Err` DIRECTLY, with no `unwrap`, and matches on the
16162 /// LENGTH-MISMATCH message specifically -- not merely on `is_err()`. That
16163 /// distinction is load-bearing: `from_host_buffer_on` has a second failure
16164 /// path (`storage_from_host_buffer_owned_dyn`), so a bare `is_err()` could
16165 /// not tell this decline from that one.
16166 #[test]
16167 fn gap003_from_f32_declines_a_length_mismatch() {
16168 // 2 elements declared as a 3-element shape.
16169 let err = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[3]), cpu_dev())
16170 .expect_err("a length/shape mismatch must DECLINE, not construct");
16171 let msg = err.to_string();
16172 assert!(
16173 msg.contains("does not match shape element count"),
16174 "the decline must name the LENGTH MISMATCH specifically, got: {msg}"
16175 );
16176 assert!(
16177 msg.contains('2') && msg.contains('3'),
16178 "and both operands: {msg}"
16179 );
16180
16181 // CONTROL: a MATCHING length still constructs, so the guard is not
16182 // "this constructor always fails".
16183 assert!(
16184 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).is_ok()
16185 );
16186 }
16187
16188 #[test]
16189 fn zero_branch_graph_builds_unchanged() {
16190 // Build: c = (a + b) * a — the same DAG the topo-order tests
16191 // use, exercised here purely to prove the arena is untouched by
16192 // the new variant.
16193 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
16194 let b = a
16195 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
16196 .unwrap();
16197 let sum = a.add(&b);
16198 let c = sum.mul(&a);
16199
16200 let g = c.graph();
16201 let guard = g.read().unwrap();
16202
16203 // Exactly four nodes (a, b, sum, c) — no implicit Branch
16204 // anywhere.
16205 assert_eq!(
16206 guard.len(),
16207 4,
16208 "zero-Branch graph must have the same node count as before"
16209 );
16210
16211 // Topo order is unchanged and contains zero Branch nodes.
16212 let order = topo_order(&guard, c.id());
16213 assert_eq!(order.len(), 4);
16214 let branch_count = order
16215 .iter()
16216 .filter(|&&id| matches!(guard.node(id).op, Op::Branch { .. }))
16217 .count();
16218 assert_eq!(branch_count, 0, "no builder constructs Op::Branch in PR-A0");
16219
16220 // The ops are exactly the ones the builders emitted (no
16221 // structural rewrite slipped in a merge node).
16222 assert!(matches!(guard.node(a.id()).op, Op::Const));
16223 assert!(matches!(guard.node(b.id()).op, Op::Const));
16224 assert!(matches!(guard.node(sum.id()).op, Op::Add));
16225 assert!(matches!(guard.node(c.id()).op, Op::Mul));
16226 }
16227
16228 /// The variant exists and its infallible accessor behaves: a
16229 /// hand-constructed `Op::Branch` reports `short_name() == "Branch"`,
16230 /// and the multi-path encoding (arms = `inputs`, explicit
16231 /// `reconverge_at`) round-trips through the arena. This is the only
16232 /// place in PR-A0 that constructs the variant — the production
16233 /// builders land in PR-A1.
16234 #[test]
16235 fn branch_variant_exists_and_short_name_works() {
16236 // short_name / the Op::short_name() facade both return the
16237 // stable "Branch" constant.
16238 let reconverge = NodeId(7);
16239 let branch_op = Op::Branch {
16240 reconverge_at: reconverge,
16241 };
16242 assert_eq!(branch_op.short_name(), "Branch");
16243 assert_eq!(op_short_name(&branch_op), "Branch");
16244
16245 // Structural nodes carry no destructive input (matches the
16246 // other structural ops: Const / View / ScatterIntoSlot).
16247 assert_eq!(branch_op.destructive_input(), None);
16248
16249 // Encode a 2-arm merge directly on the arena: two route exits
16250 // as `inputs`, the reconvergence node named explicitly. Prove
16251 // the encoding survives a push + read-back unchanged.
16252 let mut g = Graph::new();
16253 let arm0 = g.push(Node {
16254 op: Op::Const,
16255 inputs: vec![],
16256 shape: Shape::from_dims(&[2]),
16257 dtype: DType::F32,
16258 });
16259 let arm1 = g.push(Node {
16260 op: Op::Const,
16261 inputs: vec![],
16262 shape: Shape::from_dims(&[2]),
16263 dtype: DType::F32,
16264 });
16265 let merged = g.push(Node {
16266 op: Op::Const,
16267 inputs: vec![],
16268 shape: Shape::from_dims(&[2]),
16269 dtype: DType::F32,
16270 });
16271 let branch = g.push(Node {
16272 op: Op::Branch {
16273 reconverge_at: merged,
16274 },
16275 inputs: vec![arm0, arm1],
16276 shape: Shape::from_dims(&[2]),
16277 dtype: DType::F32,
16278 });
16279
16280 let node = g.node(branch);
16281 assert_eq!(node.op.short_name(), "Branch");
16282 // Arms are the node's inputs (each input = one route's exit).
16283 assert_eq!(node.inputs, vec![arm0, arm1]);
16284 // The explicit reconvergence node is carried on the op.
16285 match node.op {
16286 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, merged),
16287 ref other => panic!("expected Op::Branch, got {other:?}"),
16288 }
16289 }
16290
16291 // ----- Op::Branch builders + build-time validation
16292 // (Phase A PR-A1 of the "plan IS the graph" rebuild) -----
16293
16294 /// Hand-build a 2-arm diamond directly on the arena and return the
16295 /// pieces the branch builders will stitch together:
16296 /// `diverge` → {`arm0`, `arm1`} → `reconverge`. The reconverge node
16297 /// already reads arm0 as input 0, which is exactly the runnability
16298 /// invariant the builders must preserve (a finalized-but-unpicked
16299 /// branch still realizes on arm 0). Every node is `[2] f32` so the
16300 /// cast-to-uniform check has agreeing shape/dtype across arms.
16301 fn diamond_2arm() -> (Graph, NodeId, NodeId, NodeId, NodeId) {
16302 let mut g = Graph::new();
16303 let diverge = g.push(Node {
16304 op: Op::Const,
16305 inputs: vec![],
16306 shape: Shape::from_dims(&[2]),
16307 dtype: DType::F32,
16308 });
16309 // arm0 = relu(diverge), arm1 = silu(diverge): two interior nodes,
16310 // each reachable only through its own arm from the diverge point.
16311 let arm0 = g.push(Node {
16312 op: Op::Relu,
16313 inputs: vec![diverge],
16314 shape: Shape::from_dims(&[2]),
16315 dtype: DType::F32,
16316 });
16317 let arm1 = g.push(Node {
16318 op: Op::Silu,
16319 inputs: vec![diverge],
16320 shape: Shape::from_dims(&[2]),
16321 dtype: DType::F32,
16322 });
16323 // reconverge reads arm0 (runnability: arm 0 is always input 0).
16324 let reconverge = g.push(Node {
16325 op: Op::Relu,
16326 inputs: vec![arm0],
16327 shape: Shape::from_dims(&[2]),
16328 dtype: DType::F32,
16329 });
16330 (g, diverge, arm0, arm1, reconverge)
16331 }
16332
16333 /// (a) A 2-arm diamond round-trips through
16334 /// `open_branch`/`add_arm`/`finalize_branches`: it produces exactly
16335 /// one valid `Op::Branch` node whose `inputs` are the arm exits in
16336 /// order and whose `reconverge_at` is the named merge node.
16337 #[test]
16338 fn two_arm_diamond_round_trips_to_branch_node() {
16339 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16340 let before = g.len();
16341
16342 let mut b = g.open_branch(diverge);
16343 b.add_arm(arm0);
16344 b.add_arm(arm1);
16345 let branch = b
16346 .finalize_branches(&mut g, reconverge)
16347 .expect("well-formed 2-arm branch must finalize")
16348 .expect("2 arms survive — not collapsed to a single arm");
16349
16350 // Exactly one node was appended (the Branch); no orphan debris.
16351 assert_eq!(g.len(), before + 1);
16352
16353 let node = g.node(branch);
16354 assert!(matches!(node.op, Op::Branch { .. }));
16355 // Arms are the node's inputs, in add order: arm0 first.
16356 assert_eq!(node.inputs, vec![arm0, arm1]);
16357 match node.op {
16358 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, reconverge),
16359 ref other => panic!("expected Op::Branch, got {other:?}"),
16360 }
16361 // The merge node still carries arm0's shape/dtype (cast-to-uniform
16362 // validated, not rewritten).
16363 assert_eq!(node.shape, g.node(arm0).shape);
16364 assert_eq!(node.dtype, g.node(arm0).dtype);
16365 }
16366
16367 /// (b) A `reconverge_at` that is NOT a descendant of the diverge
16368 /// point returns `Error::InvalidBranch` — never a panic.
16369 #[test]
16370 fn reconverge_not_descendant_of_diverge_is_typed_err() {
16371 let (mut g, diverge, arm0, arm1, _reconverge) = diamond_2arm();
16372 // A sibling node that does NOT descend from `diverge`.
16373 let unrelated = g.push(Node {
16374 op: Op::Const,
16375 inputs: vec![],
16376 shape: Shape::from_dims(&[2]),
16377 dtype: DType::F32,
16378 });
16379
16380 let mut b = g.open_branch(diverge);
16381 b.add_arm(arm0);
16382 b.add_arm(arm1);
16383 let err = b
16384 .finalize_branches(&mut g, unrelated)
16385 .expect_err("reconverge that doesn't descend from diverge must be rejected");
16386 assert!(
16387 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16388 "expected InvalidBranch, got {err:?}",
16389 );
16390 }
16391
16392 /// (c) A non-disjoint arm — an arm interior node reachable from
16393 /// outside that arm (shared with the rest of the graph) — returns
16394 /// `Error::InvalidBranch`.
16395 #[test]
16396 fn non_disjoint_arm_is_typed_err() {
16397 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16398 // Add a reader OUTSIDE the branch that consumes arm0's interior.
16399 // arm0 is now reachable from a node that isn't part of the merge,
16400 // so the arm is not internally disjoint.
16401 let _external_reader = g.push(Node {
16402 op: Op::Relu,
16403 inputs: vec![arm0],
16404 shape: Shape::from_dims(&[2]),
16405 dtype: DType::F32,
16406 });
16407
16408 let mut b = g.open_branch(diverge);
16409 b.add_arm(arm0);
16410 b.add_arm(arm1);
16411 let err = b
16412 .finalize_branches(&mut g, reconverge)
16413 .expect_err("an arm interior read from outside the branch must be rejected");
16414 assert!(
16415 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16416 "expected InvalidBranch, got {err:?}",
16417 );
16418 }
16419
16420 /// (c') Arms that disagree on shape/dtype at their exits violate
16421 /// cast-to-uniform and return `Error::InvalidBranch` (validate-and-Err
16422 /// — no implicit Cast insertion in PR-A1).
16423 #[test]
16424 fn arms_disagreeing_on_dtype_is_typed_err() {
16425 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16426 // A second arm with a DIFFERENT dtype than arm0.
16427 let arm1_f16 = g.push(Node {
16428 op: Op::Silu,
16429 inputs: vec![diverge],
16430 shape: Shape::from_dims(&[2]),
16431 dtype: DType::F16,
16432 });
16433
16434 let mut b = g.open_branch(diverge);
16435 b.add_arm(arm0);
16436 b.add_arm(arm1_f16);
16437 let err = b
16438 .finalize_branches(&mut g, reconverge)
16439 .expect_err("arms with mismatched dtype must be rejected (cast-to-uniform)");
16440 assert!(
16441 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16442 "expected InvalidBranch, got {err:?}",
16443 );
16444 }
16445
16446 /// (d) `finalize_branches` drops a single-arm branch: with only one
16447 /// surviving arm there is no real decision point, so no `Op::Branch`
16448 /// node is emitted (`Ok(None)`), the arena is left untouched, and the
16449 /// graph collapses back to that arm.
16450 #[test]
16451 fn single_arm_branch_is_dropped() {
16452 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16453 let before = g.len();
16454
16455 let mut b = g.open_branch(diverge);
16456 b.add_arm(arm0);
16457 let result = b
16458 .finalize_branches(&mut g, reconverge)
16459 .expect("a single-arm branch is valid — it just collapses");
16460 assert!(
16461 result.is_none(),
16462 "single-arm branch must NOT emit an Op::Branch"
16463 );
16464 // No node appended: the lone arm is the graph, unchanged.
16465 assert_eq!(
16466 g.len(),
16467 before,
16468 "dropping a single-arm branch leaves the arena untouched"
16469 );
16470 let branch_count = (0..g.len())
16471 .filter(|&i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }))
16472 .count();
16473 assert_eq!(branch_count, 0);
16474 }
16475
16476 /// (e) The runnability invariant: the emitted `Op::Branch`'s inputs
16477 /// always include arm-0's exit as input 0, so a finalized-but-not-yet-
16478 /// route-picked graph still realizes on arm 0 (a graph with a
16479 /// finalized branch must still be executable). The named reconverge
16480 /// node reads arm-0's exit, so realizing on arm 0 alone produces a
16481 /// defined value at the merge.
16482 #[test]
16483 fn finalized_branch_preserves_arm0_runnability() {
16484 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16485
16486 let mut b = g.open_branch(diverge);
16487 b.add_arm(arm0);
16488 b.add_arm(arm1);
16489 let branch = b
16490 .finalize_branches(&mut g, reconverge)
16491 .expect("well-formed branch finalizes")
16492 .expect("2 arms survive");
16493
16494 // arm 0 is input 0 of the Branch — the always-realizable route.
16495 assert_eq!(g.node(branch).inputs.first().copied(), Some(arm0));
16496 // And the named reconverge node reads arm0, so realizing on
16497 // arm 0 alone produces a defined value at the merge.
16498 assert!(
16499 g.node(reconverge).inputs.contains(&arm0),
16500 "reconverge must read arm-0's exit so the unpicked graph runs on arm 0",
16501 );
16502 }
16503
16504 // ===================================================================
16505 // PR-B4: required compaction of the append-only arena.
16506 // ===================================================================
16507
16508 use crate::run::{extract_runs, lower_runs_arm0};
16509
16510 /// Build the same 2-arm diamond the run.rs tests use, finalized into a
16511 /// real `Op::Branch`. Returns `(g, diverge, arm0, arm1, reconverge,
16512 /// branch, post)`. `post` reads `reconverge`, so the post-merge region
16513 /// is a non-empty run and `post` is a stable root.
16514 fn diamond_with_branch_b4() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
16515 let mk = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
16516 g.push(Node {
16517 op,
16518 inputs,
16519 shape: Shape::from_dims(&[2]),
16520 dtype: DType::F32,
16521 })
16522 };
16523 let mut g = Graph::new();
16524 let pre = mk(&mut g, Op::Const, vec![]);
16525 let diverge = mk(&mut g, Op::Relu, vec![pre]);
16526 let arm0 = mk(&mut g, Op::Silu, vec![diverge]);
16527 let arm1 = mk(&mut g, Op::GeluTanh, vec![diverge]);
16528 let reconverge = mk(&mut g, Op::Relu, vec![arm0]);
16529 let mut b = g.open_branch(diverge);
16530 b.add_arm(arm0);
16531 b.add_arm(arm1);
16532 let branch = b
16533 .finalize_branches(&mut g, reconverge)
16534 .expect("well-formed 2-arm branch finalizes")
16535 .expect("2 arms survive");
16536 let post = mk(&mut g, Op::Tanh, vec![reconverge]);
16537 (g, diverge, arm0, arm1, reconverge, branch, post)
16538 }
16539
16540 /// PR-D1 storage-class substrate: the op-inferred class is correct
16541 /// (`Op::Const` → Shared, `Op::WriteSlice` → SessionState, other →
16542 /// Transient), an explicit override beats the inferred default (a
16543 /// KV-cache placeholder `Op::Const` marked SessionState), and `compact`
16544 /// carries the override to the node's new id while inferred defaults
16545 /// still hold. Born-red: fails if classification, override precedence,
16546 /// or the compaction remap is wrong.
16547 #[test]
16548 fn storage_class_inference_override_and_compaction() {
16549 let mut g = Graph::new();
16550 // A shared weight Const, a session-state KV placeholder Const, a
16551 // transient activation, and an in-place cache-write target.
16552 let weight = g.push(Node {
16553 op: Op::Const,
16554 inputs: vec![],
16555 shape: Shape::from_dims(&[2]),
16556 dtype: DType::F32,
16557 });
16558 let kv = g.push(Node {
16559 op: Op::Const,
16560 inputs: vec![],
16561 shape: Shape::from_dims(&[2]),
16562 dtype: DType::F32,
16563 });
16564 let act = g.push(Node {
16565 op: Op::Relu,
16566 inputs: vec![weight],
16567 shape: Shape::from_dims(&[2]),
16568 dtype: DType::F32,
16569 });
16570 let write = g.push(Node {
16571 op: Op::WriteSlice {
16572 ranges: vec![(0, 2)],
16573 dyn_offset: None,
16574 },
16575 inputs: vec![kv, act],
16576 shape: Shape::from_dims(&[2]),
16577 dtype: DType::F32,
16578 });
16579
16580 // Op-inferred defaults.
16581 assert_eq!(
16582 g.storage_class(weight),
16583 StorageClass::Shared,
16584 "Const → Shared"
16585 );
16586 assert_eq!(
16587 g.storage_class(act),
16588 StorageClass::Transient,
16589 "activation → Transient"
16590 );
16591 assert_eq!(
16592 g.storage_class(write),
16593 StorageClass::SessionState,
16594 "WriteSlice → SessionState"
16595 );
16596 // No overrides set yet.
16597 assert_eq!(
16598 g.storage_class(kv),
16599 StorageClass::Shared,
16600 "KV placeholder Const infers Shared before override"
16601 );
16602 assert!(!g.has_storage_class_override(kv));
16603 assert_eq!(g.storage_class_override_count(), 0);
16604
16605 // Explicit override: the KV placeholder is session state, not a
16606 // shared weight.
16607 g.set_storage_class(kv, StorageClass::SessionState);
16608 assert_eq!(
16609 g.storage_class(kv),
16610 StorageClass::SessionState,
16611 "override beats inferred default"
16612 );
16613 assert!(g.has_storage_class_override(kv));
16614 assert_eq!(g.storage_class_override_count(), 1);
16615
16616 // Compaction carries the override to the new id; inferred defaults
16617 // (no side-table entry) still resolve from the op.
16618 let remap = compact(&mut g, &[write]);
16619 let n_kv = remap.get(kv).expect("kv survives (input of write)");
16620 let n_weight = remap
16621 .get(weight)
16622 .expect("weight survives (transitively under act)");
16623 let n_write = remap.get(write).expect("write is the root");
16624 assert_eq!(
16625 g.storage_class(n_kv),
16626 StorageClass::SessionState,
16627 "override remapped by compact"
16628 );
16629 assert!(g.has_storage_class_override(n_kv));
16630 assert_eq!(
16631 g.storage_class_override_count(),
16632 1,
16633 "exactly the one override survives"
16634 );
16635 assert_eq!(
16636 g.storage_class(n_weight),
16637 StorageClass::Shared,
16638 "inferred Shared still holds post-compact"
16639 );
16640 assert_eq!(
16641 g.storage_class(n_write),
16642 StorageClass::SessionState,
16643 "inferred SessionState still holds post-compact"
16644 );
16645 assert!(g.verify_no_dangling().is_ok());
16646 }
16647
16648 /// (a) A deliberately-orphaned node (pushed, referenced by nothing) is
16649 /// dropped by `compact`; the node count shrinks by exactly the orphan
16650 /// count, and every still-reachable node survives.
16651 #[test]
16652 fn compact_drops_orphan_debris() {
16653 let mut g = Graph::new();
16654 let a = g.push(Node {
16655 op: Op::Const,
16656 inputs: vec![],
16657 shape: Shape::from_dims(&[2]),
16658 dtype: DType::F32,
16659 });
16660 let b = g.push(Node {
16661 op: Op::Relu,
16662 inputs: vec![a],
16663 shape: Shape::from_dims(&[2]),
16664 dtype: DType::F32,
16665 });
16666 let c = g.push(Node {
16667 op: Op::Silu,
16668 inputs: vec![b],
16669 shape: Shape::from_dims(&[2]),
16670 dtype: DType::F32,
16671 });
16672 // Two pieces of exploration debris: reachable from nothing in the
16673 // live structure (no root, no side-effect, no branch references them).
16674 let _orphan0 = g.push(Node {
16675 op: Op::Const,
16676 inputs: vec![],
16677 shape: Shape::from_dims(&[2]),
16678 dtype: DType::F32,
16679 });
16680 let _orphan1 = g.push(Node {
16681 op: Op::Tanh,
16682 inputs: vec![_orphan0],
16683 shape: Shape::from_dims(&[2]),
16684 dtype: DType::F32,
16685 });
16686
16687 let before = g.len();
16688 let remap = compact(&mut g, &[c]);
16689
16690 assert_eq!(
16691 g.len(),
16692 before - 2,
16693 "compaction drops exactly the two orphan-debris nodes",
16694 );
16695 // The three reachable nodes all survived (have new ids).
16696 assert!(remap.get(a).is_some());
16697 assert!(remap.get(b).is_some());
16698 assert!(remap.get(c).is_some());
16699 // The orphans are gone.
16700 assert!(remap.get(_orphan0).is_none());
16701 assert!(remap.get(_orphan1).is_none());
16702 // The surviving chain still resolves: c' reads b' reads a'.
16703 let (na, nb, nc) = (
16704 remap.get(a).unwrap(),
16705 remap.get(b).unwrap(),
16706 remap.get(c).unwrap(),
16707 );
16708 assert_eq!(g.node(nc).inputs, vec![nb]);
16709 assert_eq!(g.node(nb).inputs, vec![na]);
16710 assert_eq!(g.node(na).inputs, Vec::<NodeId>::new());
16711 assert_no_dangling(&g);
16712 }
16713
16714 /// (b) Branches preserved: a graph with a finalized `Op::Branch` keeps
16715 /// every arm + `reconverge_at` after compaction (remapped), and the
16716 /// arm-0 lowering yields the same logical route.
16717 #[test]
16718 fn compact_preserves_branch_arms_and_reconverge() {
16719 let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch_b4();
16720
16721 // Inject orphan debris so compaction has something to drop and the
16722 // surviving-branch claim is non-trivial.
16723 let _debris = g.push(Node {
16724 op: Op::Const,
16725 inputs: vec![],
16726 shape: Shape::from_dims(&[2]),
16727 dtype: DType::F32,
16728 });
16729
16730 // Baseline arm-0 route over old ids, mapped to the op sequence.
16731 let before_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16732 .iter()
16733 .map(|&id| g.node(id).op.short_name())
16734 .collect();
16735
16736 let remap = compact(&mut g, &[post]);
16737
16738 // Every branch participant survived.
16739 let narm0 = remap.get(arm0).expect("arm0 survives");
16740 let narm1 = remap
16741 .get(arm1)
16742 .expect("arm1 (the non-fallback arm) survives");
16743 let nrecon = remap.get(reconverge).expect("reconverge survives");
16744 let nbranch = remap.get(branch).expect("the Branch node itself survives");
16745 let npost = remap.get(post).expect("post survives");
16746
16747 // The Branch's inputs are the remapped arm exits (arm0 first), and
16748 // its reconverge_at is the remapped reconverge — it still resolves.
16749 let bn = g.node(nbranch);
16750 assert!(matches!(bn.op, Op::Branch { .. }));
16751 assert_eq!(
16752 bn.inputs,
16753 vec![narm0, narm1],
16754 "arm exits remapped, arm0 first"
16755 );
16756 match bn.op {
16757 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, nrecon),
16758 ref other => panic!("expected Op::Branch, got {other:?}"),
16759 }
16760 // reconverge still reads arm0 (runnability preserved through remap).
16761 assert!(g.node(nrecon).inputs.contains(&narm0));
16762 // The arm-0 route is logically identical (same op sequence).
16763 let after_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16764 .iter()
16765 .map(|&id| g.node(id).op.short_name())
16766 .collect();
16767 assert_eq!(before_ops, after_ops, "arm-0 route is logically unchanged");
16768 assert_no_dangling(&g);
16769 }
16770
16771 /// (c) Base map preserved: a branchless, fully-reachable graph compacts
16772 /// to itself — no node dropped; ids may renumber but the structure is
16773 /// identical.
16774 #[test]
16775 fn compact_branchless_reachable_is_identity_in_structure() {
16776 let mut g = Graph::new();
16777 let a = g.push(Node {
16778 op: Op::Const,
16779 inputs: vec![],
16780 shape: Shape::from_dims(&[2]),
16781 dtype: DType::F32,
16782 });
16783 let b = g.push(Node {
16784 op: Op::Relu,
16785 inputs: vec![a],
16786 shape: Shape::from_dims(&[2]),
16787 dtype: DType::F32,
16788 });
16789 let c = g.push(Node {
16790 op: Op::Silu,
16791 inputs: vec![b],
16792 shape: Shape::from_dims(&[2]),
16793 dtype: DType::F32,
16794 });
16795 let d = g.push(Node {
16796 op: Op::Tanh,
16797 inputs: vec![c],
16798 shape: Shape::from_dims(&[2]),
16799 dtype: DType::F32,
16800 });
16801
16802 let before_ops: Vec<&'static str> = extract_runs(&g, d)
16803 .iter()
16804 .flat_map(|r| {
16805 r.members
16806 .iter()
16807 .map(|&id| g.node(id).op.short_name())
16808 .collect::<Vec<_>>()
16809 })
16810 .collect();
16811 let before_len = g.len();
16812
16813 let remap = compact(&mut g, &[d]);
16814
16815 assert_eq!(g.len(), before_len, "a fully-reachable graph drops nothing");
16816 for n in [a, b, c, d] {
16817 assert!(remap.get(n).is_some(), "every node survives");
16818 }
16819 // Structure identical: same op sequence over the compacted graph.
16820 let nd = remap.get(d).unwrap();
16821 let after_ops: Vec<&'static str> = extract_runs(&g, nd)
16822 .iter()
16823 .flat_map(|r| {
16824 r.members
16825 .iter()
16826 .map(|&id| g.node(id).op.short_name())
16827 .collect::<Vec<_>>()
16828 })
16829 .collect();
16830 assert_eq!(before_ops, after_ops);
16831 assert_no_dangling(&g);
16832 }
16833
16834 /// (d) No dangling + round-trip: after `compact`, NO NodeId reference
16835 /// (node inputs, op-carried `reconverge_at`, or any side-table) points
16836 /// outside the new arena, AND `extract_runs` / arm-0 lowering on the
16837 /// compacted graph yields the identical logical result, including for
16838 /// graphs carrying every side-table (placements, target_backends,
16839 /// layouts, storage_map, node_output_views, side_effect_roots).
16840 #[test]
16841 fn compact_no_dangling_and_round_trip_with_side_tables() {
16842 let (mut g, diverge, arm0, _arm1, reconverge, _branch, post) = diamond_with_branch_b4();
16843
16844 // Populate side-tables on surviving nodes so the remap must carry
16845 // them. (target_backend on a couple nodes; placement on one.)
16846 g.set_target_backend(arm0, BackendId::Cpu);
16847 g.set_target_backend(reconverge, BackendId::Cpu);
16848 g.set_placement(diverge, DeviceLocation::Cpu);
16849 // A side-effect root that is itself orphan-from-roots: a Release-like
16850 // op the executor must keep even though no output reads it.
16851 let se = g.push(Node {
16852 op: Op::Const,
16853 inputs: vec![post],
16854 shape: Shape::from_dims(&[2]),
16855 dtype: DType::F32,
16856 });
16857 g.add_side_effect_root(se);
16858
16859 // Orphan debris (referenced by nothing live) to force a real drop.
16860 let _debris = g.push(Node {
16861 op: Op::Const,
16862 inputs: vec![],
16863 shape: Shape::from_dims(&[2]),
16864 dtype: DType::F32,
16865 });
16866
16867 let before_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16868 .iter()
16869 .map(|&id| g.node(id).op.short_name())
16870 .collect();
16871
16872 let remap = compact(&mut g, &[post]);
16873
16874 // No dangling references anywhere.
16875 assert_no_dangling(&g);
16876
16877 // The side-effect root survived (a side-effect-only node is a
16878 // reachability seed) and its side-table entry was remapped.
16879 let nse = remap.get(se).expect("side-effect root survives compaction");
16880 assert!(
16881 g.side_effect_roots().contains(&nse),
16882 "the remapped side-effect root is registered post-compaction",
16883 );
16884 // The surviving target_backend side-table is keyed by the new ids.
16885 assert_eq!(
16886 g.target_backend(remap.get(arm0).unwrap()),
16887 Some(BackendId::Cpu)
16888 );
16889 assert_eq!(
16890 g.target_backend(remap.get(reconverge).unwrap()),
16891 Some(BackendId::Cpu)
16892 );
16893 assert_eq!(
16894 g.placement(remap.get(diverge).unwrap()),
16895 Some(DeviceLocation::Cpu)
16896 );
16897
16898 // Round-trip: the arm-0 route is logically identical.
16899 let npost = remap.get(post).unwrap();
16900 let after_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16901 .iter()
16902 .map(|&id| g.node(id).op.short_name())
16903 .collect();
16904 assert_eq!(
16905 before_run_ops, after_run_ops,
16906 "compaction preserves the realized arm-0 route exactly",
16907 );
16908 }
16909
16910 /// Helper: assert NO NodeId reference in the graph points outside the
16911 /// arena. Covers node `inputs`, the op-carried `Op::Branch.reconverge_at`,
16912 /// every NodeId-keyed side-table, and the `side_effect_roots` vec — the
16913 /// exhaustive no-dangling safety net for a missed remap.
16914 fn assert_no_dangling(g: &Graph) {
16915 let n = g.len();
16916 let ok = |id: NodeId| id.0 < n;
16917 for i in 0..n {
16918 let node = g.node(NodeId(i));
16919 for &inp in &node.inputs {
16920 assert!(ok(inp), "Node#{i} input {:?} dangles (len={n})", inp);
16921 }
16922 if let Op::Branch { reconverge_at } = node.op {
16923 assert!(
16924 ok(reconverge_at),
16925 "Node#{i} Branch.reconverge_at {:?} dangles (len={n})",
16926 reconverge_at
16927 );
16928 }
16929 }
16930 for &r in g.side_effect_roots() {
16931 assert!(ok(r), "side_effect_root {:?} dangles (len={n})", r);
16932 }
16933 // Use the graph's own verification entry point as the load-bearing
16934 // assert (it covers every side-table by reading the private fields).
16935 assert!(
16936 g.verify_no_dangling().is_ok(),
16937 "Graph::verify_no_dangling found a dangling reference: {:?}",
16938 g.verify_no_dangling().err(),
16939 );
16940 }
16941
16942 #[test]
16943 fn scan_variants_construct_and_name() {
16944 use crate::{Graph, Node, Op, ScanEmit, ScanPredicate, ScanRole};
16945 use fuel_ir::{DType, Shape};
16946 let mut g = Graph::new();
16947 let s = Shape::from_dims(&[1, 1, 1]);
16948 let carry = g.push(Node {
16949 op: Op::Const,
16950 inputs: vec![],
16951 shape: s.clone(),
16952 dtype: DType::F32,
16953 });
16954 // A ScanPlaceholder leaf (the per-step carry hole).
16955 let hole = g.push(Node {
16956 op: Op::ScanPlaceholder {
16957 role: ScanRole::Carry,
16958 index: 0,
16959 },
16960 inputs: vec![],
16961 shape: s.clone(),
16962 dtype: DType::F32,
16963 });
16964 // A trivial body: new_carry = hole (identity); body_y = hole.
16965 // Op::Scan node: inputs = [init_carry, <no xs>, <no consts>, body_new_carry, body_y].
16966 let scan = g.push(Node {
16967 op: Op::Scan {
16968 n_carries: 1,
16969 n_xs: 0,
16970 bound: 1,
16971 emit: ScanEmit::All,
16972 early_exit: None,
16973 },
16974 inputs: vec![carry, hole, hole],
16975 shape: s.clone(),
16976 dtype: DType::F32,
16977 });
16978 assert_eq!(g.node(scan).op.short_name(), "Scan");
16979 assert_eq!(g.node(hole).op.short_name(), "ScanPlaceholder");
16980 // early_exit is constructible (guarded elsewhere) but never Some on a live path.
16981 let _guarded = Op::Scan {
16982 n_carries: 1,
16983 n_xs: 0,
16984 bound: 1,
16985 emit: ScanEmit::Final,
16986 early_exit: Some(ScanPredicate),
16987 };
16988 // derive_view_output_layout: Scan is NOT a view op -> Err (handled by the catch-all).
16989 let lay = fuel_ir::Layout::contiguous(s.clone());
16990 let derived = crate::derive_view_output_layout(
16991 &Op::Scan {
16992 n_carries: 1,
16993 n_xs: 0,
16994 bound: 1,
16995 emit: ScanEmit::All,
16996 early_exit: None,
16997 },
16998 &lay,
16999 );
17000 assert!(
17001 derived.is_err(),
17002 "Op::Scan must not be treated as a view op"
17003 );
17004 let _ = scan;
17005 }
17006
17007 #[test]
17008 fn scan_builder_all_and_final_shapes() {
17009 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17010 use fuel_ir::{DType, Shape};
17011 use std::sync::{Arc, RwLock};
17012 let graph = Arc::new(RwLock::new(Graph::new()));
17013 let cs = Shape::from_dims(&[2]); // carry shape
17014 let ys = Shape::from_dims(&[2]); // per-step y shape
17015 let (carry, hole, new_carry, body_y) = {
17016 let mut g = graph.write().unwrap();
17017 let carry = g.push(Node {
17018 op: Op::Const,
17019 inputs: vec![],
17020 shape: cs.clone(),
17021 dtype: DType::F32,
17022 });
17023 let hole = g.push(Node {
17024 op: Op::ScanPlaceholder {
17025 role: ScanRole::Carry,
17026 index: 0,
17027 },
17028 inputs: vec![],
17029 shape: cs.clone(),
17030 dtype: DType::F32,
17031 });
17032 let new_carry = g.push(Node {
17033 op: Op::MulScalar(2.0),
17034 inputs: vec![hole],
17035 shape: cs.clone(),
17036 dtype: DType::F32,
17037 });
17038 let body_y = g.push(Node {
17039 op: Op::AddScalar(1.0),
17040 inputs: vec![new_carry],
17041 shape: ys.clone(),
17042 dtype: DType::F32,
17043 });
17044 (carry, hole, new_carry, body_y)
17045 };
17046 let t = |id| NodeHandle {
17047 graph: graph.clone(),
17048 id,
17049 }; // same-crate access to private fields
17050 let init = t(carry);
17051 let (nc, by) = (t(new_carry), t(body_y));
17052 let bound = 4usize;
17053
17054 let all = init
17055 .scan(&[], &[], &nc, &by, bound, ScanEmit::All)
17056 .expect("scan All");
17057 assert_eq!(
17058 all.shape().dims(),
17059 &[bound, 2],
17060 "emit=All -> [bound] ++ body_y"
17061 );
17062
17063 // Structural guard (Task-2 review finding): the Op::Scan node's
17064 // inputs MUST end with [.., body_new_carry, body_y] in that
17065 // order — base_map_hash recurses into the last two inputs to
17066 // hash the body, so a reordering would silently hash the wrong
17067 // subgraph. `all` is a View(0) over the producer; its own
17068 // single input is the producer NodeId.
17069 {
17070 let g = graph.read().unwrap();
17071 let producer_id = g.node(all.id()).inputs[0];
17072 let producer_inputs = &g.node(producer_id).inputs;
17073 assert_eq!(
17074 producer_inputs[producer_inputs.len() - 2],
17075 nc.id(),
17076 "Op::Scan inputs[len-2] must be body_new_carry",
17077 );
17078 assert_eq!(
17079 producer_inputs[producer_inputs.len() - 1],
17080 by.id(),
17081 "Op::Scan inputs[len-1] must be body_y",
17082 );
17083 }
17084
17085 let fin = init
17086 .scan(&[], &[], &nc, &by, bound, ScanEmit::Final)
17087 .expect("scan Final");
17088 assert_eq!(fin.shape().dims(), &[2], "emit=Final -> carry shape");
17089 let _ = hole;
17090 }
17091
17092 #[test]
17093 fn scan_builder_rejects_zero_bound() {
17094 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17095 use fuel_ir::{DType, Shape};
17096 use std::sync::{Arc, RwLock};
17097 let graph = Arc::new(RwLock::new(Graph::new()));
17098 let cs = Shape::from_dims(&[1]);
17099 let (carry, new_carry, body_y) = {
17100 let mut g = graph.write().unwrap();
17101 let carry = g.push(Node {
17102 op: Op::Const,
17103 inputs: vec![],
17104 shape: cs.clone(),
17105 dtype: DType::F32,
17106 });
17107 let hole = g.push(Node {
17108 op: Op::ScanPlaceholder {
17109 role: ScanRole::Carry,
17110 index: 0,
17111 },
17112 inputs: vec![],
17113 shape: cs.clone(),
17114 dtype: DType::F32,
17115 });
17116 let nc = g.push(Node {
17117 op: Op::MulScalar(2.0),
17118 inputs: vec![hole],
17119 shape: cs.clone(),
17120 dtype: DType::F32,
17121 });
17122 (carry, nc, nc)
17123 };
17124 let t = |id| NodeHandle {
17125 graph: graph.clone(),
17126 id,
17127 };
17128 let r = t(carry).scan(&[], &[], &t(new_carry), &t(body_y), 0, ScanEmit::All);
17129 assert!(r.is_err(), "bound == 0 must be a typed Err, not a panic");
17130 }
17131
17132 /// Task 5 (C6): every "opt-in" classifier/dispatch site over `Op` must
17133 /// treat the new `Op::Scan` / `Op::ScanPlaceholder` variants via its
17134 /// existing safe-conservative wildcard/allow-list — no site should need
17135 /// a bespoke Scan arm in Phase 1. This is a regression LOCK, not a
17136 /// born-red test: every assertion here is expected to pass immediately
17137 /// because the wildcards already exist; a red assertion means that site
17138 /// silently mishandles Scan and needs a conservative arm added.
17139 ///
17140 /// Also confirms reachability: `Op::Scan`'s body lives in its own
17141 /// `inputs` (like `Op::Branch`'s arms), so the ordinary input-closure
17142 /// walk (`topo_order_multi`) sees body nodes for free — no
17143 /// `effective_roots` / `live_set` edit is needed.
17144 #[test]
17145 fn scan_opt_in_sites_are_safe_defaults() {
17146 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
17147 use fuel_ir::{DType, Shape};
17148 let scan = Op::Scan {
17149 n_carries: 1,
17150 n_xs: 0,
17151 bound: 2,
17152 emit: ScanEmit::All,
17153 early_exit: None,
17154 };
17155 let hole = Op::ScanPlaceholder {
17156 role: ScanRole::Carry,
17157 index: 0,
17158 };
17159 // Classifier defaults.
17160 assert_eq!(scan.destructive_input(), None);
17161 assert_eq!(hole.destructive_input(), None);
17162 assert!(!scan.is_view_op());
17163 assert!(!hole.is_view_op());
17164 assert_eq!(
17165 crate::infer_storage_class(&scan),
17166 crate::StorageClass::Transient
17167 );
17168 assert_eq!(crate::jit::op_to_tag(&scan), None);
17169 // Reachability: build a graph with an Op::Scan whose body references a hole;
17170 // the hole (a body node) is reachable from the Scan via inputs, no seeding.
17171 let mut g = Graph::new();
17172 let s = Shape::from_dims(&[1]);
17173 let carry = g.push(Node {
17174 op: Op::Const,
17175 inputs: vec![],
17176 shape: s.clone(),
17177 dtype: DType::F32,
17178 });
17179 let h = g.push(Node {
17180 op: hole.clone(),
17181 inputs: vec![],
17182 shape: s.clone(),
17183 dtype: DType::F32,
17184 });
17185 let nc = g.push(Node {
17186 op: Op::MulScalar(2.0),
17187 inputs: vec![h],
17188 shape: s.clone(),
17189 dtype: DType::F32,
17190 });
17191 let sc = g.push(Node {
17192 op: scan.clone(),
17193 inputs: vec![carry, nc, nc],
17194 shape: Shape::from_dims(&[2, 1]),
17195 dtype: DType::F32,
17196 });
17197 let reachable = crate::topo_order_multi(&g, &[sc]);
17198 assert!(
17199 reachable.contains(&nc) && reachable.contains(&h),
17200 "body nodes must be reachable from Op::Scan via inputs (no effective_roots edit needed)"
17201 );
17202 }
17203}