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 takes the
1019 /// per-backend handle (e.g. `&CudaDevice`, `&Arc<VulkanBackend>`)
1020 /// from the `DeviceRegistry` the caller hands the realize (a
1021 /// `*_with_devices` entry point of `fuel-dispatch`'s
1022 /// `PipelinedExecutor`). A non-CPU place nobody registered is a
1023 /// typed error at the Alloc.
1024 Alloc { target: DeviceLocation },
1025
1026 /// Fill the input tensor's bytes with zero, in place. Aliases
1027 /// `inputs[0]`'s Storage Arc as the output (same Storage; the
1028 /// bytes are mutated). Destructive on `inputs[0]` — readers of
1029 /// the input's NodeId after this op see post-fill bytes; new
1030 /// readers should use this op's NodeId.
1031 ///
1032 /// Bridge-retirement Phase 3a follow-up. Paired with
1033 /// [`Op::Alloc`] to give the architecturally clean "alloc uninit +
1034 /// explicit zero" pipeline. Backends with native device-side
1035 /// fills (CUDA `cuMemsetD8Async`, Vulkan `vkCmdFillBuffer`)
1036 /// dispatch through their kernels; CPU does an
1037 /// `Arc::make_mut`-style in-place memset.
1038 ///
1039 /// Future extension: an `Op::Fill { value: u8 }` (or `Scalar`)
1040 /// for non-zero patterns. ZeroFill is the only variant today
1041 /// because zero is the only init pattern any current caller
1042 /// needs.
1043 ZeroFill,
1044
1045 /// Phase 7.6 single-arm delegate to the open
1046 /// [`crate::registry::FusedOpRegistry`]. The id selects which
1047 /// fused op (SoftmaxLastDim, RmsNormLastDim, FlashAttn, ...) and
1048 /// the params carry per-instance data. The registry's metadata
1049 /// side (decompose, backward identity, shape/dtype rules) lives in
1050 /// `fuel-graph::registry`; the kernel side (per-backend `KernelRef`
1051 /// + cost + precision) lives in `fuel-storage::fused`.
1052 ///
1053 /// Adding a new fused op is one registry entry plus one kernel
1054 /// function per backend that supports it — no new `Op` variant.
1055 /// Step 3 of Phase 7.6 migrates SoftmaxLastDim through this arm
1056 /// as the proof of concept.
1057 Fused(FusedOpId, FusedOpParams),
1058
1059 /// Project one logical output out of a multi-output producer node.
1060 /// The producer's realized [`Storage`] carries a
1061 /// [`fuel_ir::storage::OutputView`] side-table; this op
1062 /// reads slot `slot` of that side-table and exposes its
1063 /// dtype/shape/layout as the View node's output.
1064 ///
1065 /// Single input (the multi-output producer). Output shares the
1066 /// producer's `Arc<RwLock<Storage>>` — zero bytes copied. The
1067 /// bundle stays alive as long as any View consumer (or the
1068 /// original producer handle) holds a clone.
1069 ///
1070 /// At graph-build time, the View's shape + dtype + layout come
1071 /// from the producer's slot specs recorded via
1072 /// [`Graph::set_output_views`]; building a `View { slot }` over a
1073 /// producer that hasn't declared slot specs is a typed error
1074 /// surfaced by the View-emitting builder helper. The bundle's
1075 /// per-slot dtype is independent of the producer node's own
1076 /// `Node::dtype` (which is the bundle's primary/slot-0 dtype).
1077 ///
1078 /// Backward (see `fuel-graph::grad`): the per-slot upstream
1079 /// gradient is scattered into a zero-filled bundle of the
1080 /// producer's overall byte shape; the producer's own backward
1081 /// rule then sees a "bundle gradient" as its upstream. Until a
1082 /// real multi-output op author exists (Session 2), the backward
1083 /// rule emits an [`Op::Const`] zero of the producer's primary
1084 /// shape — the scatter-into-slot primitive lands alongside the
1085 /// first differentiable multi-output op.
1086 View { slot: u32 },
1087
1088 /// Like [`Op::View`], but copies the slot's bytes into a fresh
1089 /// standalone Storage. Costs one allocation + one slot-sized
1090 /// memcpy; the producer's bundle Arc can drop as soon as every
1091 /// outstanding `Op::View` over the same producer also drops.
1092 ///
1093 /// The planner promotes a `View` to `ViewOwned` when a slot's
1094 /// liveness substantially outlasts the rest of the bundle (the
1095 /// classic case: Mamba's `last_state` slot retained across an
1096 /// autoregressive step while `y` is consumed immediately). v1
1097 /// emits the same dispatch shape as `Op::Copy` — backend-side it's
1098 /// `Copy` with byte offset + length pulled from the slot spec.
1099 ///
1100 /// Same shape/dtype/layout inference path as `View`; same backward
1101 /// shape too (the forward already paid the copy).
1102 ViewOwned { slot: u32 },
1103
1104 /// Multi-output autograd primitive (Option C, item 4). Takes two
1105 /// inputs:
1106 /// - `inputs[0]`: a bundled tensor (typically a zero-bundle)
1107 /// - `inputs[1]`: the slot's gradient
1108 ///
1109 /// Produces a new bundled tensor identical to `inputs[0]` except
1110 /// that slot `slot`'s byte range is overlaid by `inputs[1]`'s
1111 /// bytes. The output is alias-free with respect to `inputs[0]`
1112 /// (a fresh Storage with the new bytes) so multiple
1113 /// `ScatterIntoSlot` operations on the same `bundle_zero` chain
1114 /// sequentially without aliasing pitfalls.
1115 ///
1116 /// Emitted by `Op::View` / `Op::ViewOwned` backward rules: each
1117 /// View consumer scatters its upstream gradient into a fresh
1118 /// zero-bundle, then the producer's backward receives the
1119 /// composed bundle gradient as its upstream.
1120 ///
1121 /// **Status**: IR-level primitive only in this session. No CPU
1122 /// kernel registration yet. The production multi-output SSM ops
1123 /// (SelectiveScan, SsdChunkScan) are now differentiable via the
1124 /// Op::Scan Phase-2 `lower_scans_for_backward` pre-pass (decompose →
1125 /// `Op::Scan` → `unroll_scan` → node-general autograd), which lowers
1126 /// them to primitives BEFORE the reverse walk — so the autograd
1127 /// differentiates the unrolled `View` projections directly and never
1128 /// reaches a `ScatterIntoSlot` realization on the SSM path.
1129 ScatterIntoSlot { slot: u32 },
1130
1131 /// In-place multi-path (phi/merge) node — the arena representation
1132 /// of the optimized form's divergent-then-reconvergent routes.
1133 ///
1134 /// A `Branch` node's divergent "arms" are encoded in the node's
1135 /// existing `inputs: Vec<NodeId>`: each input is the *exit* of one
1136 /// candidate route, and `reconverge_at` names the explicit node at
1137 /// which those routes merge back into a single value. Because the
1138 /// multi-path structure is an arena fact rather than an overlay, it
1139 /// persists, compacts, graph-walks, and path-filters exactly like
1140 /// any other node; a graph with **zero** `Op::Branch` nodes is
1141 /// exactly today's single-route graph (back-compatible by
1142 /// construction).
1143 ///
1144 /// **Inert until PR-A1.** This variant is the PR-A0 scaffold: the
1145 /// closed `Op` enum carries it and every exhaustive match handles
1146 /// it, but nothing constructs it yet. The `open_branch` /
1147 /// `add_arm` / `finalize_branches` builders (with build-time
1148 /// validation: reconverge must descend from the diverge point, arms
1149 /// internally disjoint, cast-to-uniform at reconverge) land in
1150 /// PR-A1. Until then, accessors return a constant ("branch") and
1151 /// fallible paths (shape inference, autograd, lowering) return a
1152 /// descriptive `Err` rather than panicking.
1153 Branch { reconverge_at: NodeId },
1154
1155 /// Fuel's first sub-graph-carrying primitive: a bounded `lax.scan`-shaped
1156 /// recurrence `scan(body, init_carry, xs, consts) -> (final_carry, ys)`.
1157 ///
1158 /// The body is encoded in this node's own `inputs`, exactly like
1159 /// [`Op::Branch`]'s arms. Node layout:
1160 /// `inputs = [ init_carry_0..init_carry_{n_carries-1}, xs_0..xs_{n_xs-1},
1161 /// consts..., body_new_carry_0..body_new_carry_{n_carries-1}, body_y ]`
1162 /// — the two body-exit NodeIds are the LAST two inputs, so `base_map_hash`,
1163 /// `topo_order_multi`, and reachability see the body for free. The body
1164 /// references `Op::ScanPlaceholder{Carry,0}` for the per-step carry and
1165 /// `Op::ScanPlaceholder{Elem,i}` for the per-step slice of `xs[i]`; consts
1166 /// are referenced by real NodeId. `n_carries` carries are threaded; the
1167 /// body references `ScanPlaceholder{Carry,k}` for carry `k` (GAP-303 —
1168 /// `n_carries = 1` is the v1 single-carry model).
1169 ///
1170 /// An optimization/verification-time node: it never reaches the executor
1171 /// un-lowered (the SSM decompose emits it, but the executor dispatches the
1172 /// fused op to its kernel; `unroll_scan` materializes primitives on demand
1173 /// for the verify oracle / kernel-absent fallback). No `LoweringRule`
1174 /// matches it — it is a terminal in the base map, which is correct: it IS
1175 /// the primitive. Always a 2-slot bundle (slot 0 = stacked `ys`, slot 1 =
1176 /// final carry). `early_exit` is Phase-2 (see [`ScanPredicate`]).
1177 Scan {
1178 /// How many recurrent carries this scan threads. Symmetric with
1179 /// `n_xs`: the carry NODES live in `inputs` (a positional block, see
1180 /// the layout above); this field is only their COUNT, exactly as
1181 /// `n_xs` is only the count of the `xs` block.
1182 ///
1183 /// GAP-303: `1` reproduces the v1 single-carry model exactly.
1184 n_carries: usize,
1185 n_xs: usize,
1186 bound: usize,
1187 emit: ScanEmit,
1188 early_exit: Option<ScanPredicate>,
1189 },
1190
1191 /// Inert body-hole leaf for [`Op::Scan`] (no inputs). Substituted by
1192 /// `unroll_scan` per step. Never directly realized.
1193 ScanPlaceholder { role: ScanRole, index: usize },
1194}
1195
1196/// What a [`Op::Scan`] emits. `All` stacks the per-step `body_y` over the
1197/// bound (slot 0); `Final` returns only the final carry (slot 1). The op
1198/// always produces the 2-slot bundle; `emit` selects the builder's default
1199/// projection. (`Op::Reduce` is `Op::Scan { emit: Final }` conceptually —
1200/// no separate variant.)
1201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1202pub enum ScanEmit {
1203 All,
1204 Final,
1205}
1206
1207/// Which body hole a [`Op::ScanPlaceholder`] stands in for. `Carry` is the
1208/// per-step recurrent carry (always index 0 in v1's single-carry model);
1209/// `Elem` is the per-step slice of `xs[index]`.
1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1211pub enum ScanRole {
1212 Carry,
1213 Elem,
1214}
1215
1216/// Phase-1 placeholder for [`Op::Scan`]'s `early_exit` field. The FIELD is
1217/// defined now so the enum shape is final (one `03-ir` MAJOR bump); the
1218/// data-dependent early-exit MECHANISM is Phase 2. It is never `Some` on any
1219/// live Phase-1 path; if a realize/lowering path sees `Some`, that path
1220/// returns a clear `Err` (a surfaced Phase-2 gap), never a panic.
1221#[derive(Debug, Clone, PartialEq)]
1222pub struct ScanPredicate;
1223
1224impl Op {
1225 /// Index into `inputs` that this op destroys on execution. `None`
1226 /// means the op is non-destructive — every input remains readable
1227 /// after the op completes. Destructive ops need the scheduler to
1228 /// pin them to run after all other readers of the destroyed input,
1229 /// via ordering edges derived by [`opt::derive_ordering`].
1230 pub fn destructive_input(&self) -> Option<usize> {
1231 match self {
1232 // --- Destructive: the op writes through input 0 in place, so every
1233 // reader of input 0 (and its view-aliases) must be scheduled BEFORE
1234 // it (`opt::derive_ordering`). ---
1235 Op::Release
1236 | Op::Move { .. }
1237 | Op::WriteSlice { .. }
1238 | Op::WriteSliceRotating { .. }
1239 | Op::WriteSliceDoff { .. }
1240 | Op::ZeroFill
1241 | Op::ReluInplace
1242 | Op::SiluInplace
1243 | Op::GeluTanhInplace
1244 | Op::TanhInplace
1245 | Op::SigmoidInplace
1246 | Op::NegInplace
1247 | Op::AbsInplace
1248 | Op::SqrInplace
1249 | Op::SqrtInplace
1250 | Op::RsqrtInplace
1251 | Op::RecipInplace
1252 | Op::ExpInplace
1253 | Op::LogInplace
1254 | Op::SinInplace
1255 | Op::CosInplace
1256 | Op::SignInplace
1257 | Op::FloorInplace
1258 | Op::CeilInplace
1259 | Op::RoundInplace
1260 | Op::ErfInplace
1261 | Op::GeluInplace
1262 | Op::ClampInplace { .. }
1263 | Op::PowIInplace(_) => Some(0),
1264
1265 // --- Fused ops declare destructiveness as a MANDATORY
1266 // `FusedOpEntry::destructive_input` field (registry-declared, not
1267 // hardcoded here), so the fact lives with the thing and cannot drift.
1268 // Total by construction: a compile-time fused op cannot be registered
1269 // without the field; a runtime-registered fused id is not in the
1270 // compile-time registry and its region is a functional recipe (the
1271 // PatternNode grammar cannot express a destructive op), so `entry` is
1272 // `None` there and the op is non-destructive. GAP-076. ---
1273 Op::Fused(id, _) => crate::registry::default_registry()
1274 .entry(*id)
1275 .and_then(|e| e.destructive_input),
1276
1277 // --- Non-destructive primitives, listed EXHAUSTIVELY (no wildcard)
1278 // so adding an `Op` variant fails to compile here until it is
1279 // classified (`Op` is EXHAUSTIVE-BY-DESIGN — see the marker on
1280 // `enum Op`). A silent `_ => None` was the GAP-076 hazard: a future
1281 // destructive op would read as non-destructive and the scheduler
1282 // would drop its ordering edges — an intermittent data race that
1283 // points nowhere near this function. ---
1284 Op::Const
1285 | Op::Iota { .. }
1286 | Op::Add
1287 | Op::Sub
1288 | Op::Mul
1289 | Op::Div
1290 | Op::Neg
1291 | Op::Sqr
1292 | Op::Sqrt
1293 | Op::Exp
1294 | Op::Log
1295 | Op::Sin
1296 | Op::Cos
1297 | Op::Tanh
1298 | Op::Sigmoid
1299 | Op::Silu
1300 | Op::GeluTanh
1301 | Op::Relu
1302 | Op::Step
1303 | Op::Recip
1304 | Op::Abs
1305 | Op::Equal
1306 | Op::Ne
1307 | Op::Lt
1308 | Op::Le
1309 | Op::Gt
1310 | Op::Ge
1311 | Op::Where
1312 | Op::Floor
1313 | Op::Ceil
1314 | Op::Round
1315 | Op::Sign
1316 | Op::Erf
1317 | Op::Gelu
1318 | Op::Pow
1319 | Op::Rsqrt
1320 | Op::Rem
1321 | Op::Flip { .. }
1322 | Op::Roll { .. }
1323 | Op::CumSum { .. }
1324 | Op::Triu { .. }
1325 | Op::Tril { .. }
1326 | Op::LogSoftmaxLastDim
1327 | Op::MaskedFill { .. }
1328 | Op::Pad { .. }
1329 | Op::PadBackward { .. }
1330 | Op::MatMul
1331 | Op::Transpose
1332 | Op::Permute(_)
1333 | Op::Cast(_)
1334 | Op::BroadcastTo(_)
1335 | Op::Reshape(_)
1336 | Op::Contiguize
1337 | Op::Unsqueeze { .. }
1338 | Op::Squeeze { .. }
1339 | Op::ReduceSumTo(_)
1340 | Op::ReduceMaxTo(_)
1341 | Op::SumAll
1342 | Op::MaxAll
1343 | Op::MinAll
1344 | Op::MeanAll
1345 | Op::SumDim(_)
1346 | Op::MaxDim(_)
1347 | Op::MinDim(_)
1348 | Op::MeanDim(_)
1349 | Op::LogSoftmaxLastDimBackward
1350 | Op::ArgMaxDim(_)
1351 | Op::ArgMinDim(_)
1352 | Op::Concat { .. }
1353 | Op::Slice { .. }
1354 | Op::AddScalar(_)
1355 | Op::MulScalar(_)
1356 | Op::PowI(_)
1357 | Op::Clamp { .. }
1358 | Op::Maximum
1359 | Op::Minimum
1360 | Op::IndexSelect { .. }
1361 | Op::Gather { .. }
1362 | Op::IndexAdd { .. }
1363 | Op::ScatterAdd { .. }
1364 | Op::NonZeroIndices { .. }
1365 | Op::Copy { .. }
1366 | Op::Alloc { .. }
1367 | Op::View { .. }
1368 | Op::ViewOwned { .. }
1369 | Op::ScatterIntoSlot { .. }
1370 | Op::Branch { .. }
1371 | Op::Scan { .. }
1372 | Op::ScanPlaceholder { .. } => None,
1373 }
1374 }
1375
1376 /// Short human-readable name for this op — used by executor error
1377 /// messages to identify the offending graph node without spilling
1378 /// all of `Debug`'s field contents. Keeps panic messages one-liner-
1379 /// friendly while still telling you which kind of op blew up.
1380 pub fn short_name(&self) -> &'static str {
1381 op_short_name(self)
1382 }
1383
1384 /// Whether this op is a metadata-only view: its output shares bytes
1385 /// with its single input, reinterpreting them through new strides
1386 /// and/or offset. Executors realize these without allocating new
1387 /// storage — they wrap the input's Storage in a fresh Layout.
1388 ///
1389 /// Note that `Op::Reshape` is *not* a view op. Reshape produces
1390 /// contiguous output: zero-copy when its input is contiguous, but
1391 /// it materializes via auto-Contiguize when the input is strided.
1392 /// The other shape-altering ops in this set are always view-shaped
1393 /// regardless of the input layout.
1394 pub fn is_view_op(&self) -> bool {
1395 matches!(
1396 self,
1397 Op::Transpose
1398 | Op::Permute(_)
1399 | Op::BroadcastTo(_)
1400 | Op::Slice { .. }
1401 | Op::Unsqueeze { .. }
1402 | Op::Squeeze { .. }
1403 | Op::Flip { .. }
1404 )
1405 }
1406}
1407
1408/// Compute the output [`Layout`] of a metadata-only view op from its
1409/// input layout + the op variant. Returns `Err` if the op variant
1410/// isn't a view op (caller's contract — typically guarded by
1411/// [`Op::is_view_op`]).
1412///
1413/// Used by [`Graph::push`] to auto-populate the layout side-table for
1414/// view-op nodes at construction time, and by lowering rules in
1415/// [`opt`] that emit view-op nodes and need to populate the side-table
1416/// for them. The compiler reads the resulting layouts via
1417/// [`Graph::layout`] without re-deriving.
1418pub fn derive_view_output_layout(op: &Op, input_layout: &Layout) -> Result<Layout, fuel_ir::Error> {
1419 match op {
1420 Op::Transpose => {
1421 let rank = input_layout.shape().rank();
1422 if rank < 2 {
1423 return Err(fuel_ir::Error::Msg(format!(
1424 "Op::Transpose requires rank >= 2, input rank is {rank}",
1425 ))
1426 .bt());
1427 }
1428 input_layout.transpose(rank - 2, rank - 1)
1429 }
1430 Op::Permute(axes) => input_layout.permute(axes),
1431 Op::BroadcastTo(target_shape) => input_layout.broadcast_as(target_shape.clone()),
1432 Op::Slice { dim, start, len } => input_layout.narrow(*dim, *start, *len),
1433 Op::Unsqueeze { dim } => input_layout.unsqueeze(*dim),
1434 Op::Squeeze { dim } => input_layout.squeeze(*dim),
1435 Op::Flip { dim } => input_layout.flip(*dim),
1436 other => Err(fuel_ir::Error::Msg(format!(
1437 "derive_view_output_layout called with non-view op {other:?}",
1438 ))
1439 .bt()),
1440 }
1441}
1442
1443fn op_short_name(op: &Op) -> &'static str {
1444 match op {
1445 Op::Const => "Const",
1446 Op::Iota { .. } => "Iota",
1447 Op::Add => "Add",
1448 Op::Sub => "Sub",
1449 Op::Mul => "Mul",
1450 Op::Div => "Div",
1451 Op::Neg => "Neg",
1452 Op::Sqr => "Sqr",
1453 Op::Sqrt => "Sqrt",
1454 Op::Exp => "Exp",
1455 Op::Log => "Log",
1456 Op::Sin => "Sin",
1457 Op::Cos => "Cos",
1458 Op::Tanh => "Tanh",
1459 Op::Sigmoid => "Sigmoid",
1460 Op::Silu => "Silu",
1461 Op::GeluTanh => "GeluTanh",
1462 Op::Relu => "Relu",
1463 Op::Step => "Step",
1464 Op::Recip => "Recip",
1465 Op::Abs => "Abs",
1466 Op::ReluInplace => "ReluInplace",
1467 Op::SiluInplace => "SiluInplace",
1468 Op::GeluTanhInplace => "GeluTanhInplace",
1469 Op::TanhInplace => "TanhInplace",
1470 Op::SigmoidInplace => "SigmoidInplace",
1471 Op::NegInplace => "NegInplace",
1472 Op::AbsInplace => "AbsInplace",
1473 Op::SqrInplace => "SqrInplace",
1474 Op::SqrtInplace => "SqrtInplace",
1475 Op::RsqrtInplace => "RsqrtInplace",
1476 Op::RecipInplace => "RecipInplace",
1477 Op::ExpInplace => "ExpInplace",
1478 Op::LogInplace => "LogInplace",
1479 Op::SinInplace => "SinInplace",
1480 Op::CosInplace => "CosInplace",
1481 Op::SignInplace => "SignInplace",
1482 Op::FloorInplace => "FloorInplace",
1483 Op::CeilInplace => "CeilInplace",
1484 Op::RoundInplace => "RoundInplace",
1485 Op::ErfInplace => "ErfInplace",
1486 Op::GeluInplace => "GeluInplace",
1487 Op::ClampInplace { .. } => "ClampInplace",
1488 Op::PowIInplace(_) => "PowIInplace",
1489 Op::Equal => "Equal",
1490 Op::Ne => "Ne",
1491 Op::Lt => "Lt",
1492 Op::Le => "Le",
1493 Op::Gt => "Gt",
1494 Op::Ge => "Ge",
1495 Op::Where => "Where",
1496 Op::Floor => "Floor",
1497 Op::Ceil => "Ceil",
1498 Op::Round => "Round",
1499 Op::Sign => "Sign",
1500 Op::Erf => "Erf",
1501 Op::Gelu => "Gelu",
1502 Op::Pow => "Pow",
1503 Op::Rsqrt => "Rsqrt",
1504 Op::Rem => "Rem",
1505 Op::Flip { .. } => "Flip",
1506 Op::Roll { .. } => "Roll",
1507 Op::CumSum { .. } => "CumSum",
1508 Op::Triu { .. } => "Triu",
1509 Op::Tril { .. } => "Tril",
1510 Op::LogSoftmaxLastDim => "LogSoftmaxLastDim",
1511 Op::MaskedFill { .. } => "MaskedFill",
1512 Op::Pad { .. } => "Pad",
1513 Op::PadBackward { .. } => "PadBackward",
1514 Op::MatMul => "MatMul",
1515 Op::Transpose => "Transpose",
1516 Op::Permute(_) => "Permute",
1517 Op::Cast(_) => "Cast",
1518 Op::BroadcastTo(_) => "BroadcastTo",
1519 Op::Reshape(_) => "Reshape",
1520 Op::Contiguize => "Contiguize",
1521 Op::Unsqueeze { .. } => "Unsqueeze",
1522 Op::Squeeze { .. } => "Squeeze",
1523 Op::ReduceSumTo(_) => "ReduceSumTo",
1524 Op::ReduceMaxTo(_) => "ReduceMaxTo",
1525 Op::SumAll => "SumAll",
1526 Op::MaxAll => "MaxAll",
1527 Op::MinAll => "MinAll",
1528 Op::MeanAll => "MeanAll",
1529 Op::SumDim(_) => "SumDim",
1530 Op::MaxDim(_) => "MaxDim",
1531 Op::MinDim(_) => "MinDim",
1532 Op::MeanDim(_) => "MeanDim",
1533 Op::LogSoftmaxLastDimBackward => "LogSoftmaxLastDimBackward",
1534 Op::ArgMaxDim(_) => "ArgMaxDim",
1535 Op::ArgMinDim(_) => "ArgMinDim",
1536 Op::Concat { .. } => "Concat",
1537 Op::Slice { .. } => "Slice",
1538 Op::AddScalar(_) => "AddScalar",
1539 Op::MulScalar(_) => "MulScalar",
1540 Op::PowI(_) => "PowI",
1541 Op::Clamp { .. } => "Clamp",
1542 Op::Maximum => "Maximum",
1543 Op::Minimum => "Minimum",
1544 Op::IndexSelect { .. } => "IndexSelect",
1545 Op::Gather { .. } => "Gather",
1546 Op::IndexAdd { .. } => "IndexAdd",
1547 Op::ScatterAdd { .. } => "ScatterAdd",
1548 Op::NonZeroIndices { .. } => "NonZeroIndices",
1549 Op::Copy { .. } => "Copy",
1550 Op::Release => "Release",
1551 Op::Move { .. } => "Move",
1552 Op::WriteSlice { .. } => "WriteSlice",
1553 Op::WriteSliceRotating { .. } => "WriteSliceRotating",
1554 Op::WriteSliceDoff { .. } => "WriteSliceDoff",
1555 Op::Alloc { .. } => "Alloc",
1556 Op::ZeroFill => "ZeroFill",
1557 // Phase 7.6: registry-extended fused ops. Step 3 wires per-id
1558 // names through a static lookup; until then, all fused ops
1559 // share one short name. Distinguishing in error messages is
1560 // future work — `id` is in the Debug repr.
1561 Op::Fused(_, _) => "Fused",
1562 Op::View { .. } => "View",
1563 Op::ViewOwned { .. } => "ViewOwned",
1564 Op::ScatterIntoSlot { .. } => "ScatterIntoSlot",
1565 // PR-A0 inert scaffold (the multi-path phi/merge node).
1566 Op::Branch { .. } => "Branch",
1567 Op::Scan { .. } => "Scan",
1568 Op::ScanPlaceholder { .. } => "ScanPlaceholder",
1569 }
1570}
1571
1572/// G2 helper: element count of a `HostBuffer`. Used by NodeHandle's
1573/// constructors to validate that the supplied data matches the
1574/// declared shape's `elem_count` before allocating Storage.
1575fn host_buffer_elem_count(buf: &fuel_ir::HostBuffer) -> usize {
1576 use fuel_ir::HostBuffer;
1577 match buf {
1578 HostBuffer::F32(v) => v.len(),
1579 HostBuffer::F64(v) => v.len(),
1580 HostBuffer::BF16(v) => v.len(),
1581 HostBuffer::F16(v) => v.len(),
1582 HostBuffer::U8(v) => v.len(),
1583 HostBuffer::U32(v) => v.len(),
1584 HostBuffer::I64(v) => v.len(),
1585 other => panic!(
1586 "NodeHandle::from_*: unsupported host-buffer dtype {:?}",
1587 other.dtype(),
1588 ),
1589 }
1590}
1591
1592/// A single node in the graph: an operation and the IDs of its inputs.
1593/// The node also caches its output shape and dtype so downstream builders
1594/// can validate without walking back through the graph.
1595#[derive(Debug, Clone)]
1596pub struct Node {
1597 pub op: Op,
1598 pub inputs: Vec<NodeId>,
1599 pub shape: Shape,
1600 pub dtype: DType,
1601}
1602
1603/// How a node's storage is shared and how long it lives — its **storage
1604/// class** ([03-ir §"Storage classes and sessions"]). A node is a
1605/// structural fact and does not need storage to exist; when storage *is*
1606/// attached, its class governs sharing and lifetime so one optimized graph
1607/// can serve many concurrent sessions (weights shared, session state
1608/// `SessionId`-keyed, activations per-realize scratch).
1609///
1610/// The class is **inferred from the op** ([`infer_storage_class`]) with an
1611/// **explicit override** recorded in the graph's `storage_class` side-table
1612/// — e.g. KV-cache placeholder `Op::Const`s, which are session state, not
1613/// shared weights.
1614///
1615/// Phase D substrate (PR-D1): the classification is recorded but not yet
1616/// consumed by realize. Session keying (D2) and the persistent decode graph
1617/// (D3–D5) build on it.
1618#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1619pub enum StorageClass {
1620 /// Weights / constants: one storage for the whole model, identical
1621 /// across all sessions; keyed by `NodeId`. The op-inferred default for
1622 /// `Op::Const`.
1623 Shared,
1624 /// Per-session durable buffers (KV-caches + explicit cache-write
1625 /// targets): one storage per session, keyed by `(NodeId, SessionId)`.
1626 /// The op-inferred default for the in-place cache-write ops
1627 /// (`Op::WriteSlice` / `Op::WriteSliceRotating`); KV-cache placeholder
1628 /// `Op::Const`s take it via an explicit override.
1629 SessionState,
1630 /// Activations / scratch: ephemeral, allocated per realize and freed
1631 /// after use; never persisted. The op-inferred default for everything
1632 /// else. A transient value may cross devices mid-realize (a D2D
1633 /// `Op::Copy`) but never crosses to disk.
1634 Transient,
1635}
1636
1637/// The op-inferred storage class for a node, **before** any explicit
1638/// override (see [`StorageClass`] and [`Graph::storage_class`]):
1639/// - `Op::Const` → [`StorageClass::Shared`] (weights);
1640/// - `Op::WriteSlice` / `Op::WriteSliceRotating` → [`StorageClass::SessionState`]
1641/// (they write into a per-session durable buffer);
1642/// - everything else → [`StorageClass::Transient`].
1643pub fn infer_storage_class(op: &Op) -> StorageClass {
1644 match op {
1645 Op::Const => StorageClass::Shared,
1646 Op::WriteSlice { .. } | Op::WriteSliceRotating { .. } | Op::WriteSliceDoff { .. } => {
1647 StorageClass::SessionState
1648 }
1649 _ => StorageClass::Transient,
1650 }
1651}
1652
1653/// The graph arena. Stores every node added during a computation-building
1654/// session. Nodes are append-only and indexed by [`NodeId`].
1655///
1656/// Placement metadata (`DeviceLocation` per node) lives in a side-table
1657/// so existing `Node { ... }` construction sites don't need to be
1658/// modified. This is the Phase-1 shape: placements are opt-in, inert
1659/// hints that the executor may validate but does not yet act on.
1660/// `Default` is implemented **manually** (not derived) so that every graph —
1661/// however it is created — mints a fresh [`GraphId`] from the monotonic
1662/// counter. A derived `Default` would hand out a zeroed id, so two
1663/// `Graph::default()` graphs would claim the same identity and affinity
1664/// diagnostics would report nonsense.
1665#[derive(Debug)]
1666pub struct Graph {
1667 nodes: Vec<Node>,
1668 /// Sparse map of per-node placement hints. Entries are only present
1669 /// when explicitly set via [`Graph::set_placement`]. Absent entries
1670 /// mean "inherit from the executor's default device."
1671 placements: HashMap<NodeId, DeviceLocation>,
1672 /// NodeIds the executor must schedule even when their outputs are
1673 /// unreachable from the user's roots. Populated by graph-mutating
1674 /// rules that emit side-effecting ops (e.g. `Op::Release` for
1675 /// residency eviction). See [`Graph::add_side_effect_root`].
1676 side_effect_roots: Vec<NodeId>,
1677 /// Phase 7.5 work item G: graph-owned realized-storage map.
1678 /// Slots are populated for `Op::Const` leaves at construction
1679 /// time and for non-leaf nodes at realize time. Values are
1680 /// `Arc<RwLock<Storage>>` so consumers (NodeHandle handles, executor
1681 /// caches, residency machinery) share Storage cheaply via Arc
1682 /// clones. Lifetime is tied to the Graph; when the graph drops,
1683 /// any slots not held by external Arc clones are freed.
1684 storage_map: HashMap<NodeId, Arc<RwLock<Storage>>>,
1685 /// Phase 7.5 storage-unification B2: per-node dispatch
1686 /// resolution result. Set by the dispatch resolver (Phase B3+)
1687 /// when DAG construction picks which backend will execute the
1688 /// node's op given its inputs' dtype + residency. Sparse like
1689 /// `placements`: absent entries mean "not yet resolved" and the
1690 /// executor falls back to per-op-eval dispatch (today's
1691 /// behavior). After full migration, every Node has an entry.
1692 ///
1693 /// Note: this is a *side-table*, not a `Node` field, so that
1694 /// existing `Node { ... }` constructors don't need to change
1695 /// during the migration. Mirrors the `placements` pattern.
1696 target_backends: HashMap<NodeId, BackendId>,
1697 /// Phase 7.5 storage-unification — Layout-on-Node side-table.
1698 /// Sparse: every Node has a logical [`Layout`], but for the
1699 /// common case (contiguous result of a kernel) we don't store
1700 /// it explicitly — [`Graph::layout`] returns
1701 /// `Layout::contiguous(node.shape)` as the fallback. Entries
1702 /// are written here exclusively by metadata-only view ops
1703 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1704 /// 0-copy `Op::Reshape`) where the output is a strided view
1705 /// over an upstream node's Storage.
1706 ///
1707 /// Coherence rule: if `layouts[id]` is present, its
1708 /// `shape()` must equal `nodes[id].shape` — Layout adds
1709 /// strides + offset; the visible shape is identical.
1710 layouts: HashMap<NodeId, Layout>,
1711 /// Per-node multi-output side-table. Populated only for nodes
1712 /// whose op produces a bundled [`Storage`] with N>1 logical
1713 /// outputs (Session 1 of the multi-output-nodes design — see
1714 /// [`OutputView`](fuel_ir::storage::OutputView)). `Op::View`
1715 /// and `Op::ViewOwned` builders read this side-table to derive
1716 /// their own output shape/dtype/layout from the producer's
1717 /// declared slot specs.
1718 ///
1719 /// Coherence rule: when present, slot 0's `dtype` must equal the
1720 /// producer node's `Node::dtype` (which the multi-output op's
1721 /// allocator also uses as the inner backend storage's dtype).
1722 /// The producer's `Node::shape` reflects slot 0's logical shape
1723 /// for back-compat with single-output infrastructure; non-primary
1724 /// slots may have unrelated shapes and dtypes.
1725 node_output_views: HashMap<NodeId, Arc<[fuel_ir::storage::OutputView]>>,
1726 /// Per-node **storage-class override** ([`StorageClass`]). Sparse:
1727 /// entries are present only where the class differs from the op-inferred
1728 /// default ([`infer_storage_class`]) — chiefly KV-cache placeholder
1729 /// `Op::Const`s, which are session state, not shared weights.
1730 /// [`Graph::storage_class`] returns the override if present, else the
1731 /// inferred default, so every node has a well-defined class.
1732 /// Phase D substrate (PR-D1); not yet consumed by realize.
1733 storage_class: HashMap<NodeId, StorageClass>,
1734 /// Per-node **data-determined matmul row count** — the sparse-MoE
1735 /// capacity-buffer support. Present only on `Op::MatMul` nodes whose
1736 /// M (row count) is a runtime value: the node's `Node::shape` carries
1737 /// the row **capacity**, and this side-table carries the [`DynScalar`]
1738 /// that resolves (at compile if input-determined, else at execute from
1739 /// the producer-bound `SymEnv`) to how many rows to actually compute.
1740 /// Absent ⇒ a normal, static-M matmul. A side-table (not an `Op::MatMul`
1741 /// field) so the dense-matmul enum + its every match arm stay untouched.
1742 node_matmul_row_count: HashMap<NodeId, DynScalar>,
1743 /// Process-unique identity for this graph, minted at construction.
1744 ///
1745 /// Tensors are **graph-affine**: every binary op requires both operands to
1746 /// live on the same `Graph`, checked by `Arc::ptr_eq`. Pointer identity is
1747 /// the right *check* but a useless thing to *report* — so each graph also
1748 /// carries a small monotonic id, letting an affinity failure say "lhs is on
1749 /// graph #1, rhs on graph #2" instead of only that the two differ. That
1750 /// turns an abstract invariant into an observation the caller can act on:
1751 /// *you made two graphs.*
1752 id: GraphId,
1753}
1754
1755/// Process-unique identifier for a [`Graph`], minted monotonically by
1756/// [`Graph::new`]. Exists so affinity diagnostics can name *which* graphs
1757/// disagree; it is not a stable address, an index, or anything to persist.
1758#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1759pub struct GraphId(u64);
1760
1761impl std::fmt::Display for GraphId {
1762 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1763 write!(f, "{}", self.0)
1764 }
1765}
1766
1767/// Monotonic source for [`GraphId`]. Starts at 1 so `#0` never appears and a
1768/// zeroed/defaulted id is visibly wrong.
1769static NEXT_GRAPH_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1770
1771impl Default for Graph {
1772 fn default() -> Self {
1773 Self::new()
1774 }
1775}
1776
1777impl Graph {
1778 /// Create an empty graph.
1779 pub fn new() -> Self {
1780 Self {
1781 id: GraphId(NEXT_GRAPH_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)),
1782 nodes: Vec::new(),
1783 placements: HashMap::new(),
1784 side_effect_roots: Vec::new(),
1785 storage_map: HashMap::new(),
1786 target_backends: HashMap::new(),
1787 layouts: HashMap::new(),
1788 node_output_views: HashMap::new(),
1789 storage_class: HashMap::new(),
1790 node_matmul_row_count: HashMap::new(),
1791 }
1792 }
1793
1794 /// This graph's process-unique [`GraphId`]. Used by affinity diagnostics to
1795 /// name *which* graphs disagree; see [`NodeHandle::graph_id`].
1796 pub fn id(&self) -> GraphId {
1797 self.id
1798 }
1799
1800 /// Look up the resolved target backend for a node, if any has
1801 /// been set. Returns `None` if dispatch resolution hasn't
1802 /// happened yet for this node — common during the migration
1803 /// because old op-builder paths don't call the resolver.
1804 ///
1805 /// Phase 7.5 B2.
1806 pub fn target_backend(&self, id: NodeId) -> Option<BackendId> {
1807 self.target_backends.get(&id).copied()
1808 }
1809
1810 /// Record the resolved target backend for `id`. Set once at DAG
1811 /// construction time (or first-realize time, depending on the
1812 /// dispatch policy chosen in Phase B3). Idempotent: calling
1813 /// twice with the same value is fine; calling twice with
1814 /// different values overwrites.
1815 ///
1816 /// Phase 7.5 B2.
1817 pub fn set_target_backend(&mut self, id: NodeId, backend: BackendId) {
1818 assert!(
1819 id.0 < self.nodes.len(),
1820 "set_target_backend: id out of bounds",
1821 );
1822 self.target_backends.insert(id, backend);
1823 }
1824
1825 /// Number of nodes with a resolved target backend. Mostly for
1826 /// tests and diagnostics.
1827 pub fn target_backend_count(&self) -> usize {
1828 self.target_backends.len()
1829 }
1830
1831 /// The storage class of `id`: the explicit override if one was set via
1832 /// [`Graph::set_storage_class`], else the op-inferred default
1833 /// ([`infer_storage_class`]). Every node has a well-defined class.
1834 ///
1835 /// Phase D substrate (PR-D1).
1836 pub fn storage_class(&self, id: NodeId) -> StorageClass {
1837 if let Some(c) = self.storage_class.get(&id).copied() {
1838 return c;
1839 }
1840 infer_storage_class(&self.nodes[id.0].op)
1841 }
1842
1843 /// Record an explicit storage-class override for `id`, replacing the
1844 /// op-inferred default. Used for nodes whose op does not determine the
1845 /// class — chiefly KV-cache placeholder `Op::Const`s, which are session
1846 /// state rather than shared weights.
1847 ///
1848 /// Phase D substrate (PR-D1).
1849 pub fn set_storage_class(&mut self, id: NodeId, class: StorageClass) {
1850 assert!(
1851 id.0 < self.nodes.len(),
1852 "set_storage_class: id out of bounds",
1853 );
1854 self.storage_class.insert(id, class);
1855 }
1856
1857 /// Whether `id` carries an explicit storage-class override (as opposed
1858 /// to relying on the op-inferred default).
1859 pub fn has_storage_class_override(&self, id: NodeId) -> bool {
1860 self.storage_class.contains_key(&id)
1861 }
1862
1863 /// Number of explicit storage-class overrides. Mostly for tests and
1864 /// diagnostics.
1865 pub fn storage_class_override_count(&self) -> usize {
1866 self.storage_class.len()
1867 }
1868
1869 /// The [`Layout`] associated with `id`. If the side-table has
1870 /// no explicit entry, returns `Layout::contiguous(shape)` —
1871 /// every Node logically has a Layout; the side-table is just
1872 /// the sparse storage for the strided / offset cases.
1873 ///
1874 /// Phase 7.5 storage-unification: metadata-only view ops
1875 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1876 /// 0-copy `Op::Reshape`) populate this side-table during
1877 /// graph construction. Kernel ops produce contiguous results
1878 /// and rely on the fallback.
1879 pub fn layout(&self, id: NodeId) -> Layout {
1880 if let Some(l) = self.layouts.get(&id) {
1881 return l.clone();
1882 }
1883 Layout::contiguous(self.node(id).shape.clone())
1884 }
1885
1886 /// Record an explicit [`Layout`] for `id`. The Layout's
1887 /// `shape()` must equal `nodes[id].shape` — otherwise the
1888 /// graph becomes incoherent (downstream ops were validated
1889 /// against `node.shape`). Panics in `debug_assertions` mode
1890 /// on mismatch; in release the mismatch is silently kept
1891 /// because the alternative would require this method to
1892 /// return `Result`, which would break call ergonomics in
1893 /// graph-construction code.
1894 ///
1895 /// Set this exactly when an op produces a strided / offset
1896 /// view over upstream Storage. For the common case
1897 /// (contiguous kernel output), don't call this at all —
1898 /// [`Graph::layout`] returns `Layout::contiguous(shape)`
1899 /// as the implicit fallback.
1900 pub fn set_layout(&mut self, id: NodeId, layout: Layout) {
1901 assert!(id.0 < self.nodes.len(), "set_layout: id out of bounds");
1902 debug_assert_eq!(
1903 layout.shape(),
1904 &self.nodes[id.0].shape,
1905 "set_layout: Layout shape disagrees with Node shape \
1906 (Layout sets strides/offset, not the visible shape)",
1907 );
1908 self.layouts.insert(id, layout);
1909 }
1910
1911 /// Whether `id` has an explicit Layout entry in the side-table
1912 /// (i.e. it's a strided / offset view; not the default
1913 /// contiguous case).
1914 pub fn has_explicit_layout(&self, id: NodeId) -> bool {
1915 self.layouts.contains_key(&id)
1916 }
1917
1918 /// Number of nodes with an explicit (non-contiguous) Layout.
1919 /// Mostly for tests and diagnostics.
1920 pub fn explicit_layout_count(&self) -> usize {
1921 self.layouts.len()
1922 }
1923
1924 // -------------------------------------------------------------------
1925 // Multi-output side-table (Op::View / Op::ViewOwned)
1926 // -------------------------------------------------------------------
1927
1928 /// Borrow the per-slot output-view specs for `id`, if it's been
1929 /// declared as a multi-output producer. Returns `None` for
1930 /// single-output nodes (the common case).
1931 ///
1932 /// `Op::View` and `Op::ViewOwned` builders read this to derive
1933 /// the slot's shape/dtype/layout at graph-build time.
1934 pub fn output_views(&self, id: NodeId) -> Option<&[fuel_ir::storage::OutputView]> {
1935 self.node_output_views.get(&id).map(|a| a.as_ref())
1936 }
1937
1938 /// Clone the `Arc` handle to `id`'s per-slot output-view specs.
1939 /// Used by the realization path to attach the same bundle metadata
1940 /// to the realized [`Storage`] without copying the slice.
1941 pub fn output_views_arc(&self, id: NodeId) -> Option<Arc<[fuel_ir::storage::OutputView]>> {
1942 self.node_output_views.get(&id).cloned()
1943 }
1944
1945 /// Declare `id` as a multi-output producer with the given per-slot
1946 /// specs. Validates at graph-build time:
1947 /// 1. `id` is in bounds.
1948 /// 2. `views` is non-empty (a "multi-output" node with zero slots
1949 /// is a contract bug — use single-output if there's nothing to
1950 /// project).
1951 /// 3. Slot 0's dtype equals `nodes[id].dtype` (the bundle's
1952 /// primary dtype convention).
1953 /// 4. Slot 0's shape equals `nodes[id].shape` (slot 0 is the
1954 /// "primary" slot whose shape the single-output infrastructure
1955 /// already sees).
1956 /// 5. Each slot's `layout.shape()` equals the slot's `shape`
1957 /// (Layout adds strides/offset; the visible shape is identical).
1958 ///
1959 /// Idempotent on (id, views). Replacing an existing declaration
1960 /// asserts the new specs are byte-identical to the old in debug
1961 /// builds; in release the last write wins (matches the layouts
1962 /// side-table pattern).
1963 pub fn set_output_views(
1964 &mut self,
1965 id: NodeId,
1966 views: Arc<[fuel_ir::storage::OutputView]>,
1967 ) -> Result<(), fuel_ir::Error> {
1968 if id.0 >= self.nodes.len() {
1969 return Err(fuel_ir::Error::Msg(format!(
1970 "set_output_views: NodeId({}) out of bounds (len={})",
1971 id.0,
1972 self.nodes.len(),
1973 ))
1974 .bt());
1975 }
1976 if views.is_empty() {
1977 return Err(fuel_ir::Error::Msg(
1978 "set_output_views: slot list must be non-empty".into(),
1979 )
1980 .bt());
1981 }
1982 let node = &self.nodes[id.0];
1983 let slot0 = &views[0];
1984 if slot0.dtype != node.dtype {
1985 return Err(fuel_ir::Error::Msg(format!(
1986 "set_output_views: slot 0 dtype {:?} disagrees with \
1987 Node::dtype {:?} on Node#{} (slot 0 is the primary; \
1988 dtypes must match)",
1989 slot0.dtype, node.dtype, id.0,
1990 ))
1991 .bt());
1992 }
1993 if slot0.shape != node.shape {
1994 return Err(fuel_ir::Error::Msg(format!(
1995 "set_output_views: slot 0 shape {:?} disagrees with \
1996 Node::shape {:?} on Node#{} (slot 0 is the primary)",
1997 slot0.shape, node.shape, id.0,
1998 ))
1999 .bt());
2000 }
2001 for (i, v) in views.iter().enumerate() {
2002 if v.layout.shape() != &v.shape {
2003 return Err(fuel_ir::Error::Msg(format!(
2004 "set_output_views: slot {i} layout.shape() = {:?} \
2005 disagrees with declared slot shape {:?}",
2006 v.layout.shape(),
2007 v.shape,
2008 ))
2009 .bt());
2010 }
2011 }
2012 self.node_output_views.insert(id, views);
2013 Ok(())
2014 }
2015
2016 /// Whether `id` has been declared as a multi-output producer.
2017 pub fn is_multi_output(&self, id: NodeId) -> bool {
2018 self.node_output_views.contains_key(&id)
2019 }
2020
2021 /// Number of nodes declared as multi-output producers. Mostly for
2022 /// tests and diagnostics.
2023 pub fn multi_output_count(&self) -> usize {
2024 self.node_output_views.len()
2025 }
2026
2027 /// Whether some node in this graph *produces* (binds mid-realize) the
2028 /// runtime value `sym` — i.e. `sym` is **data-determined**, computed by
2029 /// an op during the pass rather than supplied up front. Used to tell a
2030 /// data-determined `DynScalar::Sym` (which is legitimately unbound in
2031 /// the compile-time `SymEnv` and must be resolved at *execute* time)
2032 /// apart from a caller error (a truly-unbound input-determined sym,
2033 /// which must surface as an error at realize). Today the only producer
2034 /// of a data-determined symbol is [`Op::NonZeroIndices`] (its
2035 /// `count_sym`); extend this match as more data-determined producers
2036 /// land.
2037 pub fn binds_data_determined_sym(&self, sym: SymId) -> bool {
2038 self.nodes.iter().any(|n| match &n.op {
2039 Op::NonZeroIndices { count_sym } => *count_sym == sym,
2040 _ => false,
2041 })
2042 }
2043
2044 /// The next data-determined [`SymId`] not yet used by any producer in
2045 /// this graph — one past the max `Op::NonZeroIndices` `count_sym`, or
2046 /// `SymId(0)` if none exist. Lets a builder that emits several
2047 /// data-determined producers (e.g. one `NonZeroIndices` per MoE expert,
2048 /// across several stacked layers on the same graph) allocate
2049 /// non-colliding count syms without threading an external
2050 /// [`fuel_ir::SymGen`]: each call reflects the producers already added,
2051 /// so successive layers claim strictly higher ranges.
2052 ///
2053 /// This covers the data-determined space (the only producers of which
2054 /// are `NonZeroIndices` nodes). A graph that *also* mixes
2055 /// input-determined symbolic extents in the same low sym range should
2056 /// thread a shared `SymGen` instead — those live in a separate
2057 /// compile-time `SymEnv` this scan does not see.
2058 pub fn next_data_determined_sym(&self) -> SymId {
2059 let max = self
2060 .nodes
2061 .iter()
2062 .filter_map(|n| match &n.op {
2063 Op::NonZeroIndices { count_sym } => Some(count_sym.0),
2064 _ => None,
2065 })
2066 .max();
2067 match max {
2068 Some(m) => SymId(m + 1),
2069 None => SymId(0),
2070 }
2071 }
2072
2073 /// Attach a data-determined row count to an `Op::MatMul` node — the
2074 /// sparse-MoE capacity-buffer support. The node's `Node::shape` stays
2075 /// the row-capacity output shape; `row_count` (a [`DynScalar`]) is how
2076 /// many rows to actually compute. See [`NodeHandle::matmul_dyn_m`].
2077 pub fn set_matmul_row_count(&mut self, id: NodeId, row_count: DynScalar) {
2078 assert!(
2079 id.0 < self.nodes.len(),
2080 "set_matmul_row_count: id out of bounds"
2081 );
2082 self.node_matmul_row_count.insert(id, row_count);
2083 }
2084
2085 /// The data-determined row count for `id`, if it carries one (i.e. it
2086 /// is a dynamic-M matmul). `None` ⇒ an ordinary static-M matmul.
2087 pub fn matmul_row_count(&self, id: NodeId) -> Option<DynScalar> {
2088 self.node_matmul_row_count.get(&id).copied()
2089 }
2090
2091 /// Look up the realized storage for a node, if any has been
2092 /// registered. Returns an Arc clone — the slot stays in the map
2093 /// after this call.
2094 pub fn storage_for(&self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2095 self.storage_map.get(&id).cloned()
2096 }
2097
2098 /// Register a realized-storage slot for `id`. Replaces any
2099 /// existing entry (callers responsible for ensuring this is the
2100 /// intended semantics — e.g. re-realization after eviction).
2101 pub fn set_storage(&mut self, id: NodeId, storage: Arc<RwLock<Storage>>) {
2102 assert!(id.0 < self.nodes.len(), "set_storage: id out of bounds");
2103 self.storage_map.insert(id, storage);
2104 }
2105
2106 /// Convenience: register an owned `Storage` directly. Wraps in
2107 /// `Arc<RwLock<...>>`.
2108 pub fn set_storage_owned(&mut self, id: NodeId, storage: Storage) {
2109 self.set_storage(id, Arc::new(RwLock::new(storage)));
2110 }
2111
2112 /// Remove a slot. Used by eviction / `Op::Release` paths.
2113 /// Returns the Arc if present so callers that want to keep the
2114 /// bytes alive can hold it; otherwise drops on the floor and any
2115 /// outstanding Arc clones still see the bytes.
2116 pub fn remove_storage(&mut self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2117 self.storage_map.remove(&id)
2118 }
2119
2120 /// Whether a slot is currently registered for `id`.
2121 pub fn has_storage(&self, id: NodeId) -> bool {
2122 self.storage_map.contains_key(&id)
2123 }
2124
2125 /// Number of registered storage slots.
2126 pub fn storage_len(&self) -> usize {
2127 self.storage_map.len()
2128 }
2129
2130 /// Register a NodeId as a side-effect root — a node whose output
2131 /// isn't reachable from any user-requested root but whose
2132 /// execution the executor must still schedule. Used for
2133 /// destructive ops (e.g. `Op::Release`) emitted by graph-mutating
2134 /// rules: the rule needs Release to run (freeing device memory),
2135 /// but Release's zero-element marker has no consumer.
2136 ///
2137 /// The executor's realize paths walk the user's roots AND these
2138 /// side-effect roots via a single combined `execution_plan` call.
2139 pub fn add_side_effect_root(&mut self, id: NodeId) {
2140 assert!(
2141 id.0 < self.nodes.len(),
2142 "add_side_effect_root: id out of bounds"
2143 );
2144 if !self.side_effect_roots.contains(&id) {
2145 self.side_effect_roots.push(id);
2146 }
2147 }
2148
2149 /// Snapshot the registered side-effect roots. Executor concatenates
2150 /// these with the user's requested roots before computing the plan.
2151 pub fn side_effect_roots(&self) -> &[NodeId] {
2152 &self.side_effect_roots
2153 }
2154
2155 /// The number of nodes currently in the graph.
2156 pub fn len(&self) -> usize {
2157 self.nodes.len()
2158 }
2159
2160 /// Whether the graph has any nodes.
2161 pub fn is_empty(&self) -> bool {
2162 self.nodes.is_empty()
2163 }
2164
2165 /// Borrow a node by ID. Panics if the ID is out of bounds — it should
2166 /// not be possible for a valid `NodeHandle` handle to produce an invalid
2167 /// ID, so any such panic indicates a bug in graph construction.
2168 pub fn node(&self, id: NodeId) -> &Node {
2169 &self.nodes[id.0]
2170 }
2171
2172 /// Produce a one-line human-readable description of a node and its
2173 /// immediate inputs — the identifier string that executor panics
2174 /// prepend so realize-time failures can be localized to the exact
2175 /// graph position that blew up. Format is stable enough for grep
2176 /// but explicitly intended for humans reading panic output, not for
2177 /// parsing.
2178 pub fn describe_node(&self, id: NodeId) -> String {
2179 let n = self.node(id);
2180 // GAP-303: `short_name()` renders every scan as the bare string "Scan",
2181 // so a body built from the WRONG scan was invisible in every dump and
2182 // every executor panic. Baracuda's requirement, adopted verbatim: make
2183 // something PRINT the carry count on the path that constructs the body —
2184 // not assert it. "A control tells you the encoding is sound; only the
2185 // subject's identity tells you what it encoded."
2186 let scan_params = match n.op {
2187 Op::Scan {
2188 n_carries,
2189 n_xs,
2190 bound,
2191 emit,
2192 ref early_exit,
2193 } => format!(
2194 " n_carries={n_carries} n_xs={n_xs} bound={bound} emit={emit:?} early_exit={}",
2195 early_exit.is_some()
2196 ),
2197 Op::ScanPlaceholder { role, index } => format!(" role={role:?} index={index}"),
2198 _ => String::new(),
2199 };
2200 let op_short = n.op.short_name();
2201 if n.inputs.is_empty() {
2202 return format!(
2203 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?})",
2204 id.0, n.shape, n.dtype,
2205 );
2206 }
2207 let inputs: Vec<String> = n
2208 .inputs
2209 .iter()
2210 .map(|&inp| {
2211 let ni = self.node(inp);
2212 let ip = ni.op.short_name();
2213 format!("Node#{}[{ip}, {:?}, {:?}]", inp.0, ni.shape, ni.dtype)
2214 })
2215 .collect();
2216 format!(
2217 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?}, inputs=[{}])",
2218 id.0,
2219 n.shape,
2220 n.dtype,
2221 inputs.join(", "),
2222 )
2223 }
2224
2225 /// Append a node and return its fresh ID. Used by the `NodeHandle`
2226 /// builders, by `opt` passes that canonicalize or rewrite the
2227 /// graph by appending fresh nodes, and by external consumers
2228 /// (fuel-storage's pipelined executor tests, custom-op authors)
2229 /// that need direct graph construction.
2230 ///
2231 /// For metadata-only view ops (`Op::Transpose`, `Op::Permute`,
2232 /// `Op::BroadcastTo`, `Op::Slice`) this also populates the
2233 /// [`layouts`](Self::layout) side-table by deriving the output
2234 /// layout from the input's layout via
2235 /// [`derive_view_output_layout`]. After this call,
2236 /// `graph.layout(new_id)` returns the strided/offset view layout
2237 /// without any further work — the side-table is the single source
2238 /// of truth for layout, with [`Layout::contiguous`] as the
2239 /// fallback for kernel-output nodes.
2240 ///
2241 /// Misuse (malformed Node, dangling input ids, etc.) is caught
2242 /// at execute time as a typed error, not a panic — per project's
2243 /// no-panic-in-production rule.
2244 pub fn push(&mut self, node: Node) -> NodeId {
2245 let id = NodeId(self.nodes.len());
2246 let is_view = node.op.is_view_op();
2247 let view_input = if is_view {
2248 node.inputs.first().copied()
2249 } else {
2250 None
2251 };
2252 let op_for_derive = if is_view { Some(node.op.clone()) } else { None };
2253 self.nodes.push(node);
2254 if let (Some(input_id), Some(op)) = (view_input, op_for_derive)
2255 && input_id.0 < self.nodes.len()
2256 {
2257 let input_layout = self.layout(input_id);
2258 if let Ok(out_layout) = derive_view_output_layout(&op, &input_layout) {
2259 self.set_layout(id, out_layout);
2260 }
2261 }
2262 id
2263 }
2264
2265 /// Rewrite every occurrence of `old_input` in `node`'s input list to
2266 /// `new_input`. In-place mutation — the *only* exception to the
2267 /// otherwise append-only invariant.
2268 ///
2269 /// Callers are responsible for ensuring `new_input` is semantically
2270 /// equivalent to `old_input` at this edge: same shape, same dtype,
2271 /// and produces data the consumer can read without error on the
2272 /// relevant device. Used by transform passes (residency eviction,
2273 /// fusion) that need to redirect a specific consumer's edge.
2274 pub(crate) fn rewrite_input(&mut self, node: NodeId, old_input: NodeId, new_input: NodeId) {
2275 assert!(
2276 node.0 < self.nodes.len(),
2277 "rewrite_input: node out of bounds"
2278 );
2279 let inputs = &mut self.nodes[node.0].inputs;
2280 for inp in inputs.iter_mut() {
2281 if *inp == old_input {
2282 *inp = new_input;
2283 }
2284 }
2285 }
2286
2287 /// **Collapse a decision point to a single baked arm** — the graph-side
2288 /// half of *optimize-time kernel-variant baking* (04-optimization:
2289 /// "kernel-variant choice is largely baked at optimize time"). Given a
2290 /// finalized [`Op::Branch`] and the arm the optimizer chose (`winner_arm`,
2291 /// an index into the branch's `inputs`), this rewrites the graph so the
2292 /// chosen arm is the **realized route** and the branch is no longer a
2293 /// decision point:
2294 ///
2295 /// 1. The `reconverge_at` merge is rewired to read the **winner's exit**
2296 /// (`inputs[winner_arm]`) in place of arm 0's exit (`inputs[0]`). For
2297 /// `winner_arm == 0` this is a no-op (the merge already reads arm 0,
2298 /// the runnability fallback).
2299 /// 2. The branch's `inputs` are reduced to `[winner_exit]` — a **single-arm
2300 /// branch**, which [`run::extract_runs_multi`] / `non_chosen_arm_nodes` /
2301 /// the route picker all treat as *no decision* (`arms.len() < 2`), so the
2302 /// winner's region lowers inline and the non-chosen arms become
2303 /// orphaned (pruned from the reachable set — nothing reads them once the
2304 /// merge is rewired). The arm-0 runnability invariant is preserved:
2305 /// after the reduce, `inputs[0]` is the winner and the merge reads it.
2306 ///
2307 /// This is the "the Branch collapses" resolution the constitution names for
2308 /// same-device **kernel-variant** choices (decomposed-region vs. a fused
2309 /// kernel on the *same* device), as distinct from **placement** choices
2310 /// (arms on *different* devices) which stay live `Op::Branch` decision
2311 /// points for the runtime route picker (06-runtime). The optimizer decides
2312 /// *which* branches are variant branches and computes `winner_arm`; this
2313 /// method only performs the structural collapse.
2314 ///
2315 /// Never-panic: returns [`fuel_ir::Error::InvalidBranch`] on a
2316 /// non-`Op::Branch` node or an out-of-range `winner_arm`, mutating nothing.
2317 /// Idempotent on an already-collapsed (single-arm) branch when
2318 /// `winner_arm == 0`.
2319 pub fn collapse_variant_branch(
2320 &mut self,
2321 branch: NodeId,
2322 winner_arm: usize,
2323 ) -> std::result::Result<(), fuel_ir::Error> {
2324 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2325 if branch.0 >= self.nodes.len() {
2326 return Err(invalid(format!(
2327 "collapse_variant_branch: branch Node#{} is out of bounds \
2328 (graph has {} nodes)",
2329 branch.0,
2330 self.nodes.len(),
2331 )));
2332 }
2333 let reconverge_at = match self.nodes[branch.0].op {
2334 Op::Branch { reconverge_at } => reconverge_at,
2335 ref other => {
2336 return Err(invalid(format!(
2337 "collapse_variant_branch: Node#{} is not an Op::Branch (got \
2338 {other:?})",
2339 branch.0,
2340 )));
2341 }
2342 };
2343 let arms = &self.nodes[branch.0].inputs;
2344 if arms.is_empty() {
2345 return Err(invalid(format!(
2346 "collapse_variant_branch: branch Node#{} has no arms",
2347 branch.0,
2348 )));
2349 }
2350 if winner_arm >= arms.len() {
2351 return Err(invalid(format!(
2352 "collapse_variant_branch: winner_arm {winner_arm} is out of range \
2353 (branch Node#{} has {} arms)",
2354 branch.0,
2355 arms.len(),
2356 )));
2357 }
2358 let old_arm0 = arms[0];
2359 let winner = arms[winner_arm];
2360
2361 // (1) Rewire the merge to read the winner's exit (no-op for arm 0).
2362 if winner != old_arm0 {
2363 self.rewrite_input(reconverge_at, old_arm0, winner);
2364 }
2365 // (2) Reduce the branch to the single winning arm (now arm 0). A
2366 // single-arm branch is inert: the run extractor / picker skip it,
2367 // so the non-chosen arms are pruned and the winner lowers inline.
2368 self.nodes[branch.0].inputs = vec![winner];
2369 Ok(())
2370 }
2371
2372 /// Tag a node with a target device. The executor will validate
2373 /// (post-Phase-1) that the node's op can be evaluated on that
2374 /// device. In Phase 1 the tag is informational only.
2375 pub fn set_placement(&mut self, id: NodeId, loc: DeviceLocation) {
2376 assert!(id.0 < self.nodes.len(), "set_placement: id out of bounds");
2377 self.placements.insert(id, loc);
2378 }
2379
2380 /// Read a node's placement hint, or `None` if the node inherits from
2381 /// the executor default.
2382 pub fn placement(&self, id: NodeId) -> Option<DeviceLocation> {
2383 self.placements.get(&id).copied()
2384 }
2385
2386 /// Open a [`BranchBuilder`] rooted at a shared `diverge` point — the
2387 /// first half of the `open_branch` / `add_arm` / `finalize_branches`
2388 /// trio that constructs an [`Op::Branch`] (phi/merge) node with
2389 /// build-time validation (Phase A PR-A1 of the "plan IS the graph"
2390 /// rebuild).
2391 ///
2392 /// `diverge` names the single node from which every candidate route
2393 /// (arm) departs; each arm's *exit* (added via
2394 /// [`BranchBuilder::add_arm`]) becomes one `inputs[i]` of the emitted
2395 /// `Op::Branch`. The builder borrows nothing — it is a pure
2396 /// accumulator of `NodeId`s — so the graph stays free to keep building
2397 /// arms between `open_branch` and `finalize_branches`. All validation
2398 /// (descendant `reconverge_at`, internally-disjoint arms,
2399 /// cast-to-uniform shape/dtype, arm-0 runnability) happens in
2400 /// [`BranchBuilder::finalize_branches`], which returns a typed
2401 /// [`fuel_ir::error::Error::InvalidBranch`] rather than panicking.
2402 pub fn open_branch(&self, diverge: NodeId) -> BranchBuilder {
2403 BranchBuilder {
2404 diverge,
2405 arms: Vec::new(),
2406 }
2407 }
2408
2409 /// Forward-reachable set (the node and all its transitive *consumers*)
2410 /// from `from`, computed against a precomputed consumer adjacency.
2411 /// Used by branch validation to test descendant-hood and arm
2412 /// containment without re-scanning the whole arena per query.
2413 fn forward_reachable(
2414 consumers: &HashMap<NodeId, Vec<NodeId>>,
2415 from: NodeId,
2416 ) -> HashSet<NodeId> {
2417 let mut seen: HashSet<NodeId> = HashSet::new();
2418 let mut stack = vec![from];
2419 while let Some(n) = stack.pop() {
2420 if !seen.insert(n) {
2421 continue;
2422 }
2423 if let Some(cs) = consumers.get(&n) {
2424 for &c in cs {
2425 if !seen.contains(&c) {
2426 stack.push(c);
2427 }
2428 }
2429 }
2430 }
2431 seen
2432 }
2433
2434 /// Backward-reachable set (the node and all its transitive *inputs*)
2435 /// from `from`. Used to bound an arm to the nodes that actually lie
2436 /// on a path `diverge → exit`.
2437 fn backward_reachable(&self, from: NodeId) -> HashSet<NodeId> {
2438 let mut seen: HashSet<NodeId> = HashSet::new();
2439 let mut stack = vec![from];
2440 while let Some(n) = stack.pop() {
2441 if !seen.insert(n) {
2442 continue;
2443 }
2444 for &inp in &self.nodes[n.0].inputs {
2445 if !seen.contains(&inp) {
2446 stack.push(inp);
2447 }
2448 }
2449 }
2450 seen
2451 }
2452
2453 // -------------------------------------------------------------------
2454 // Compaction of the append-only arena (PR-B4)
2455 // -------------------------------------------------------------------
2456
2457 /// The set of nodes that constitute the **live structure** of the
2458 /// graph relative to `roots`: everything reachable, following node
2459 /// `inputs`, from the union of
2460 ///
2461 /// - the caller's `roots`,
2462 /// - the `side_effect_roots` (nodes the executor must schedule even
2463 /// when no output reads them — e.g. `Op::Release` eviction), and
2464 /// - the full multi-path structure: for every reachable `Op::Branch`,
2465 /// its `reconverge_at` and **all its arms** (the arm exits, which
2466 /// are the Branch node's `inputs`, and transitively their interiors).
2467 /// Phase C's route picker needs every arm, so the alternative arms
2468 /// must survive even though nothing downstream reads them directly
2469 /// (the `reconverge_at` node reads only arm 0).
2470 ///
2471 /// A finalized `Op::Branch` is itself typically orphaned — nothing
2472 /// downstream reads it (PR-A1's runnability invariant has the merge
2473 /// read arm 0 directly, not the Branch). So a plain forward walk from
2474 /// `roots` would miss it. We therefore mirror [`run::extract_runs_multi`]'s
2475 /// `effective_roots` discipline: scan the arena and seed any Branch
2476 /// whose `reconverge_at` (or any arm exit) is already reachable, to a
2477 /// fixpoint, then take the input-closure of all seeds. The result is
2478 /// the exact set compaction must keep.
2479 fn live_set(&self, roots: &[NodeId]) -> HashSet<NodeId> {
2480 // Seeds: roots + side-effect roots. We grow this set with the
2481 // Branch nodes that participate in the reachable computation, then
2482 // take its full input-closure.
2483 let mut seeds: Vec<NodeId> = Vec::new();
2484 let mut seed_set: HashSet<NodeId> = HashSet::new();
2485 let push_seed = |id: NodeId, seeds: &mut Vec<NodeId>, seed_set: &mut HashSet<NodeId>| {
2486 if id.0 < self.nodes.len() && seed_set.insert(id) {
2487 seeds.push(id);
2488 }
2489 };
2490 for &r in roots {
2491 push_seed(r, &mut seeds, &mut seed_set);
2492 }
2493 for &r in &self.side_effect_roots {
2494 push_seed(r, &mut seeds, &mut seed_set);
2495 }
2496
2497 // Grow the seed set with participating Branch nodes to a fixpoint.
2498 // A Branch "participates" when its merge target or any arm exit is
2499 // already reachable from the current seeds (following inputs). Each
2500 // newly-seeded Branch may pull in further arms whose interiors then
2501 // make another Branch participate, hence the fixpoint.
2502 loop {
2503 let reachable = self.input_closure(&seeds);
2504 let mut added = false;
2505 for idx in 0..self.nodes.len() {
2506 let id = NodeId(idx);
2507 if seed_set.contains(&id) {
2508 continue;
2509 }
2510 let Op::Branch { reconverge_at } = self.nodes[idx].op else {
2511 continue;
2512 };
2513 let participates = reachable.contains(&reconverge_at)
2514 || self.nodes[idx].inputs.iter().any(|a| reachable.contains(a));
2515 if participates {
2516 seed_set.insert(id);
2517 seeds.push(id);
2518 added = true;
2519 }
2520 }
2521 if !added {
2522 break;
2523 }
2524 }
2525
2526 // The live set is the full input-closure of the (roots + side-effect
2527 // + participating-Branch) seeds, plus each reachable Branch's
2528 // explicit `reconverge_at` (which is downstream of the arms, so it
2529 // is not pulled in by following inputs from the Branch). The merge
2530 // node is normally reachable from `roots` already, but seeding it
2531 // explicitly makes the live set self-consistent — a Branch never
2532 // outlives its merge target.
2533 let mut live = self.input_closure(&seeds);
2534 let recon_seeds: Vec<NodeId> = live
2535 .iter()
2536 .filter_map(|&id| match self.nodes[id.0].op {
2537 Op::Branch { reconverge_at } => Some(reconverge_at),
2538 _ => None,
2539 })
2540 .collect();
2541 if !recon_seeds.is_empty() {
2542 for n in self.input_closure(&recon_seeds) {
2543 live.insert(n);
2544 }
2545 }
2546 live
2547 }
2548
2549 /// Every node reachable from any of `from`, following node `inputs`
2550 /// transitively (the backward / input cone). Mirrors
2551 /// [`topo_order_multi`] but returns just the set.
2552 fn input_closure(&self, from: &[NodeId]) -> HashSet<NodeId> {
2553 let mut seen: HashSet<NodeId> = HashSet::new();
2554 let mut stack: Vec<NodeId> = from.to_vec();
2555 while let Some(n) = stack.pop() {
2556 if n.0 >= self.nodes.len() || !seen.insert(n) {
2557 continue;
2558 }
2559 for &inp in &self.nodes[n.0].inputs {
2560 if !seen.contains(&inp) {
2561 stack.push(inp);
2562 }
2563 }
2564 }
2565 seen
2566 }
2567
2568 /// **Required compaction of the append-only arena** (PR-B4).
2569 ///
2570 /// Drops every node *not* in the live structure relative to `roots`
2571 /// (the exploration debris that pathfinders leave) and rebuilds the
2572 /// arena with contiguous, renumbered [`NodeId`]s, remapping **every**
2573 /// `NodeId` reference in the graph. Returns the [`NodeRemap`] from old
2574 /// to new ids so callers can fix up their own `NodeHandle` handles / roots.
2575 ///
2576 /// The live set follows node `inputs` from: `roots`, the
2577 /// `side_effect_roots`, and the full multi-path structure — for every
2578 /// reachable [`Op::Branch`], its `reconverge_at` **and all its arms**
2579 /// (so the route picker's alternatives survive). See [`Graph::live_set`].
2580 ///
2581 /// What is remapped (the correctness crux — a missed remap is silent
2582 /// corruption). Every NodeId-bearing structure in the graph:
2583 /// - each surviving [`Node`]'s `inputs`;
2584 /// - the `NodeId` carried *inside* an op variant — [`Op::Branch`]'s
2585 /// `reconverge_at` (the only `Op` variant carrying a `NodeId`);
2586 /// - every NodeId-keyed side-table on [`Graph`]: `placements`,
2587 /// `target_backends`, `layouts`, `storage_map`, `node_output_views`;
2588 /// - the `side_effect_roots` vector.
2589 ///
2590 /// # Not in the per-realize hot path
2591 ///
2592 /// Compaction renumbers `NodeId`s, which would invalidate a realize
2593 /// already built around the current ids (the dispatch order and the
2594 /// `StorageCache` key are `NodeId`). It is therefore a **standalone
2595 /// pass**, deliberately **not** registered as an `Optimizer` in the
2596 /// per-realize driver / `optimize_graph` loop. It runs at load-time
2597 /// **between optimization rounds** (Phase D) and is **required before
2598 /// finalize-to-disk** (Phase E) so the persisted `.fuel` holds the lean
2599 /// result, not exploration debris. Neither caller exists yet.
2600 ///
2601 /// Orphans never change results, so this is a *size* pass, not a
2602 /// *correctness* one — but the remap it performs must be exhaustive or
2603 /// it would itself introduce corruption, which is the property the
2604 /// born-red tests + [`Graph::verify_no_dangling`] guard.
2605 ///
2606 /// This is the implementation behind the free function [`compact`];
2607 /// call that.
2608 fn compact_in_place(&mut self, roots: &[NodeId]) -> NodeRemap {
2609 let live = self.live_set(roots);
2610 let n = self.nodes.len();
2611
2612 // Assign new contiguous ids in ascending old-id order, so the
2613 // relative order of surviving nodes (and hence any topological
2614 // property over them) is preserved.
2615 let mut old_to_new: Vec<Option<NodeId>> = vec![None; n];
2616 let mut next = 0usize;
2617 #[expect(
2618 clippy::needless_range_loop,
2619 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"
2620 )]
2621 for idx in 0..n {
2622 if live.contains(&NodeId(idx)) {
2623 old_to_new[idx] = Some(NodeId(next));
2624 next += 1;
2625 }
2626 }
2627 let remap = NodeRemap { old_to_new };
2628
2629 // Rebuild the node arena, remapping each surviving node's inputs and
2630 // any op-carried NodeId. Surviving nodes' inputs are themselves
2631 // always live (the live set is input-closed), so every `map` here
2632 // resolves.
2633 let mut new_nodes: Vec<Node> = Vec::with_capacity(next);
2634 for idx in 0..n {
2635 if remap.old_to_new[idx].is_none() {
2636 continue;
2637 }
2638 let mut node = self.nodes[idx].clone();
2639 for inp in node.inputs.iter_mut() {
2640 *inp = remap.expect(*inp);
2641 }
2642 if let Op::Branch { reconverge_at } = &mut node.op {
2643 *reconverge_at = remap.expect(*reconverge_at);
2644 }
2645 new_nodes.push(node);
2646 }
2647 self.nodes = new_nodes;
2648
2649 // Remap every NodeId-keyed side-table. Drop entries for dropped
2650 // nodes; rekey survivors to their new id.
2651 self.placements = remap.rekey(std::mem::take(&mut self.placements));
2652 self.target_backends = remap.rekey(std::mem::take(&mut self.target_backends));
2653 self.layouts = remap.rekey(std::mem::take(&mut self.layouts));
2654 self.storage_map = remap.rekey(std::mem::take(&mut self.storage_map));
2655 self.node_output_views = remap.rekey(std::mem::take(&mut self.node_output_views));
2656 self.storage_class = remap.rekey(std::mem::take(&mut self.storage_class));
2657 self.node_matmul_row_count = remap.rekey(std::mem::take(&mut self.node_matmul_row_count));
2658
2659 // Remap the side-effect-roots vector (every entry is live — they
2660 // were reachability seeds — so each maps).
2661 self.side_effect_roots = self
2662 .side_effect_roots
2663 .iter()
2664 .map(|&id| remap.expect(id))
2665 .collect();
2666
2667 debug_assert!(
2668 self.verify_no_dangling().is_ok(),
2669 "compact left a dangling NodeId reference: {:?}",
2670 self.verify_no_dangling().err(),
2671 );
2672 remap
2673 }
2674
2675 /// Verify that **no** `NodeId` reference in the graph points outside
2676 /// the arena — the post-compaction safety net for a missed remap.
2677 /// Checks every node's `inputs`, the op-carried `Op::Branch`
2678 /// `reconverge_at`, every NodeId-keyed side-table, and the
2679 /// `side_effect_roots` vector. Returns the first offending reference as
2680 /// a typed error (never panics); used by [`crate::compact`]'s
2681 /// `debug_assert` and by tests.
2682 pub fn verify_no_dangling(&self) -> std::result::Result<(), fuel_ir::Error> {
2683 let n = self.nodes.len();
2684 let bad = |what: String| {
2685 Err(fuel_ir::Error::Msg(format!(
2686 "dangling NodeId reference: {what} (arena has {n} nodes)",
2687 )))
2688 };
2689 for (idx, node) in self.nodes.iter().enumerate() {
2690 for &inp in &node.inputs {
2691 if inp.0 >= n {
2692 return bad(format!("Node#{idx} input Node#{}", inp.0));
2693 }
2694 }
2695 if let Op::Branch { reconverge_at } = node.op
2696 && reconverge_at.0 >= n
2697 {
2698 return bad(format!(
2699 "Node#{idx} Branch.reconverge_at Node#{}",
2700 reconverge_at.0
2701 ));
2702 }
2703 }
2704 for id in self.placements.keys() {
2705 if id.0 >= n {
2706 return bad(format!("placements key Node#{}", id.0));
2707 }
2708 }
2709 for id in self.target_backends.keys() {
2710 if id.0 >= n {
2711 return bad(format!("target_backends key Node#{}", id.0));
2712 }
2713 }
2714 for id in self.layouts.keys() {
2715 if id.0 >= n {
2716 return bad(format!("layouts key Node#{}", id.0));
2717 }
2718 }
2719 for id in self.storage_map.keys() {
2720 if id.0 >= n {
2721 return bad(format!("storage_map key Node#{}", id.0));
2722 }
2723 }
2724 for id in self.node_output_views.keys() {
2725 if id.0 >= n {
2726 return bad(format!("node_output_views key Node#{}", id.0));
2727 }
2728 }
2729 for id in self.storage_class.keys() {
2730 if id.0 >= n {
2731 return bad(format!("storage_class key Node#{}", id.0));
2732 }
2733 }
2734 for &id in &self.side_effect_roots {
2735 if id.0 >= n {
2736 return bad(format!("side_effect_root Node#{}", id.0));
2737 }
2738 }
2739 Ok(())
2740 }
2741}
2742
2743/// **Required compaction of the append-only arena** (PR-B4).
2744///
2745/// Drops every node *not* in the live structure relative to `roots` (the
2746/// exploration debris that pathfinders leave) and rebuilds the arena with
2747/// contiguous, renumbered [`NodeId`]s, remapping **every** `NodeId`
2748/// reference in the graph. Returns the [`NodeRemap`] from old → new ids so
2749/// callers can fix up their own roots / `NodeHandle` handles.
2750///
2751/// The live set follows node `inputs` from `roots`, the
2752/// `side_effect_roots`, and the full multi-path structure — for every
2753/// reachable [`Op::Branch`], its `reconverge_at` **and all its arms** (so
2754/// Phase C's route picker keeps its alternatives). Everything else is
2755/// dropped.
2756///
2757/// **Not in the per-realize hot path.** Compaction renumbers `NodeId`s,
2758/// which would invalidate a realize built around the current ids (the
2759/// dispatch order + the `StorageCache` key are `NodeId`). It is a
2760/// standalone pass — deliberately **not** registered as an `Optimizer` in
2761/// the per-realize driver / `optimize_graph` loop — run at load-time
2762/// **between optimization rounds** (Phase D) and **required before
2763/// finalize-to-disk** (Phase E). Neither caller exists yet.
2764///
2765/// See [`Graph::verify_no_dangling`] for the post-condition the
2766/// `debug_assert` checks: no `NodeId` reference (node inputs, the
2767/// op-carried `Op::Branch.reconverge_at`, any side-table, or
2768/// `side_effect_roots`) points outside the new arena.
2769pub fn compact(graph: &mut Graph, roots: &[NodeId]) -> NodeRemap {
2770 graph.compact_in_place(roots)
2771}
2772
2773/// The old → new `NodeId` mapping produced by [`compact`].
2774///
2775/// Indexed by the *old* `NodeId`: `old_to_new[old.0]` is `Some(new)` if the
2776/// node survived compaction, or `None` if it was dropped as unreachable
2777/// debris. Callers use [`NodeRemap::get`] to translate roots / `NodeHandle`
2778/// ids they still hold; passes that know a node must have survived use
2779/// `NodeRemap::expect`.
2780#[derive(Debug, Clone)]
2781pub struct NodeRemap {
2782 old_to_new: Vec<Option<NodeId>>,
2783}
2784
2785impl NodeRemap {
2786 /// The new id for `old`, or `None` if `old` was dropped (or is out of
2787 /// range of the pre-compaction arena).
2788 pub fn get(&self, old: NodeId) -> Option<NodeId> {
2789 self.old_to_new.get(old.0).copied().flatten()
2790 }
2791
2792 /// Whether `old` survived compaction.
2793 pub fn survived(&self, old: NodeId) -> bool {
2794 self.get(old).is_some()
2795 }
2796
2797 /// The new id for `old`, asserting it survived. Used internally when
2798 /// remapping a reference that is known-live (a surviving node's input,
2799 /// a reachable Branch's `reconverge_at`, a side-effect root) — a `None`
2800 /// here would mean the live-set computation was unsound.
2801 fn expect(&self, old: NodeId) -> NodeId {
2802 self.get(old).unwrap_or_else(|| {
2803 panic!(
2804 "NodeRemap::expect: Node#{} was expected to survive compaction \
2805 but was dropped — the live set is unsound (a referenced node \
2806 was not kept)",
2807 old.0,
2808 )
2809 })
2810 }
2811
2812 /// Rekey a `NodeId`-keyed side-table: drop entries whose key was
2813 /// dropped, rewrite surviving keys to their new id. Values are moved,
2814 /// not cloned.
2815 fn rekey<V>(&self, table: HashMap<NodeId, V>) -> HashMap<NodeId, V> {
2816 let mut out = HashMap::with_capacity(table.len());
2817 for (old, v) in table {
2818 if let Some(new) = self.get(old) {
2819 out.insert(new, v);
2820 }
2821 }
2822 out
2823 }
2824}
2825
2826/// Accumulates the arms of an in-construction [`Op::Branch`] (phi/merge)
2827/// node before [`finalize_branches`](Self::finalize_branches) validates
2828/// them and emits the node. Created by [`Graph::open_branch`].
2829///
2830/// The multi-path structure is an **arena fact, not an overlay**: a
2831/// `Branch` node's divergent arms are its `inputs` (each input is one
2832/// route's *exit*), and the op carries an explicit `reconverge_at`. The
2833/// builder is a pure `NodeId` accumulator — it holds no graph reference —
2834/// so the graph remains free to keep appending nodes (further arms) while
2835/// the builder is open. Nothing mutates the arena until
2836/// `finalize_branches`, which is the single validation gate.
2837#[derive(Debug, Clone)]
2838pub struct BranchBuilder {
2839 /// The shared node every arm departs from.
2840 diverge: NodeId,
2841 /// Each arm's *exit* node, in priority order. `arms[0]` is the
2842 /// runnability fallback (arm 0): the route a finalized-but-unpicked
2843 /// graph realizes on.
2844 arms: Vec<NodeId>,
2845}
2846
2847impl BranchBuilder {
2848 /// Append one arm by its *exit* node — the node whose value the merge
2849 /// reads for this route. The first arm added is **arm 0**, the
2850 /// runnability fallback: `reconverge_at` must read arm 0's exit so a
2851 /// finalized-but-not-yet-route-picked graph still realizes (validated
2852 /// in [`finalize_branches`](Self::finalize_branches)).
2853 ///
2854 /// Returns `&mut Self` for chaining. Validation is deferred to
2855 /// finalize — `add_arm` never inspects the graph and never fails.
2856 pub fn add_arm(&mut self, exit: NodeId) -> &mut Self {
2857 self.arms.push(exit);
2858 self
2859 }
2860
2861 /// The shared diverge point this branch departs from.
2862 pub fn diverge(&self) -> NodeId {
2863 self.diverge
2864 }
2865
2866 /// The arm exits accumulated so far, in add order (arm 0 first).
2867 pub fn arms(&self) -> &[NodeId] {
2868 &self.arms
2869 }
2870
2871 /// Validate and emit the [`Op::Branch`] node, returning its fresh
2872 /// `NodeId`. This is the single build-time gate; it **never panics**,
2873 /// surfacing every rejection as [`fuel_ir::error::Error::InvalidBranch`].
2874 ///
2875 /// Returns:
2876 /// - `Ok(Some(branch_id))` — a multi-arm branch was emitted.
2877 /// - `Ok(None)` — a **single-arm branch collapsed** to that arm (no
2878 /// real decision point), leaving the arena untouched.
2879 /// - `Err(Error::InvalidBranch { .. })` — a validation rule failed.
2880 ///
2881 /// Validation rules (all checked before any mutation):
2882 /// 1. At least one arm; `diverge`, `reconverge_at`, and every arm
2883 /// exit are in-bounds.
2884 /// 2. **Descendant `reconverge_at`** — the merge must be a forward
2885 /// descendant of (and distinct from) `diverge`.
2886 /// 3. **Internally-disjoint arms** — each arm's interior nodes (the
2887 /// nodes on paths `diverge → exit`, excluding the shared `diverge`)
2888 /// must neither be shared with another arm nor read by any node
2889 /// outside the branch (`reconverge_at` reading an arm exit is the
2890 /// one allowed external consumer).
2891 /// 4. **Cast-to-uniform** — all arm exits agree on shape & dtype.
2892 /// PR-A1 *validates* uniformity and errors on mismatch (it does not
2893 /// insert `Cast` nodes); dtype-lowered alternatives must therefore
2894 /// cast back to the merge dtype *inside* their arm before the exit.
2895 /// 5. **Arm-0 runnability** — `reconverge_at` must read arm 0's exit,
2896 /// so a finalized-but-unpicked graph still realizes on arm 0.
2897 pub fn finalize_branches(
2898 self,
2899 graph: &mut Graph,
2900 reconverge_at: NodeId,
2901 ) -> std::result::Result<Option<NodeId>, fuel_ir::Error> {
2902 let n = graph.nodes.len();
2903 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2904
2905 // (1a) At least one arm.
2906 if self.arms.is_empty() {
2907 return Err(invalid(
2908 "branch has no arms; at least one route is required".to_string(),
2909 ));
2910 }
2911 // (1b) Bounds-check every referenced node up front so later
2912 // arena indexing cannot panic.
2913 let in_bounds = |id: NodeId| id.0 < n;
2914 if !in_bounds(self.diverge) {
2915 return Err(invalid(format!(
2916 "diverge Node#{} is out of bounds (graph has {n} nodes)",
2917 self.diverge.0,
2918 )));
2919 }
2920 if !in_bounds(reconverge_at) {
2921 return Err(invalid(format!(
2922 "reconverge_at Node#{} is out of bounds (graph has {n} nodes)",
2923 reconverge_at.0,
2924 )));
2925 }
2926 for &arm in &self.arms {
2927 if !in_bounds(arm) {
2928 return Err(invalid(format!(
2929 "arm exit Node#{} is out of bounds (graph has {n} nodes)",
2930 arm.0,
2931 )));
2932 }
2933 }
2934
2935 // (d) Single-arm branches collapse back to that arm — no real
2936 // decision point, so no Op::Branch is emitted and the arena is
2937 // left untouched.
2938 if self.arms.len() == 1 {
2939 return Ok(None);
2940 }
2941
2942 // Build a consumer (reverse) adjacency once for the reachability
2943 // queries below.
2944 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2945 for (idx, node) in graph.nodes.iter().enumerate() {
2946 let consumer = NodeId(idx);
2947 for &inp in &node.inputs {
2948 consumers.entry(inp).or_default().push(consumer);
2949 }
2950 }
2951
2952 // (2) reconverge_at must be a forward descendant of diverge and
2953 // distinct from it.
2954 if reconverge_at == self.diverge {
2955 return Err(invalid(format!(
2956 "reconverge_at Node#{} must be a strict descendant of the \
2957 diverge point, not the diverge point itself",
2958 reconverge_at.0,
2959 )));
2960 }
2961 let fwd_from_diverge = Graph::forward_reachable(&consumers, self.diverge);
2962 if !fwd_from_diverge.contains(&reconverge_at) {
2963 return Err(invalid(format!(
2964 "reconverge_at Node#{} is not a descendant of diverge Node#{}",
2965 reconverge_at.0, self.diverge.0,
2966 )));
2967 }
2968
2969 // (4) Cast-to-uniform: every arm exit must agree on shape & dtype
2970 // with arm 0 (PR-A1 validates uniformity rather than inserting
2971 // Cast nodes).
2972 let arm0 = self.arms[0];
2973 let (want_shape, want_dtype) = {
2974 let a0 = &graph.nodes[arm0.0];
2975 (a0.shape.clone(), a0.dtype)
2976 };
2977 for &arm in &self.arms[1..] {
2978 let node = &graph.nodes[arm.0];
2979 if node.shape != want_shape || node.dtype != want_dtype {
2980 return Err(invalid(format!(
2981 "arm exit Node#{} ({:?} {:?}) disagrees with arm 0 Node#{} \
2982 ({:?} {:?}); arms must cast to a uniform shape & dtype at \
2983 reconverge",
2984 arm.0, node.shape, node.dtype, arm0.0, want_shape, want_dtype,
2985 )));
2986 }
2987 }
2988
2989 // (5) Arm-0 runnability: reconverge_at must read arm 0's exit, so
2990 // an unpicked graph realizes on arm 0.
2991 if !graph.nodes[reconverge_at.0].inputs.contains(&arm0) {
2992 return Err(invalid(format!(
2993 "reconverge_at Node#{} does not read arm-0 exit Node#{}; the \
2994 arm-0 runnability invariant requires the merge to read arm 0 \
2995 so a not-yet-route-picked graph still realizes",
2996 reconverge_at.0, arm0.0,
2997 )));
2998 }
2999
3000 // (3) Internal disjointness. Each arm's node set is the nodes on
3001 // paths diverge → exit: backward-reachable from the exit AND
3002 // forward-reachable from diverge. The arm *interior* excludes the
3003 // shared diverge point.
3004 let mut arm_interiors: Vec<HashSet<NodeId>> = Vec::with_capacity(self.arms.len());
3005 for &exit in &self.arms {
3006 let back = graph.backward_reachable(exit);
3007 let mut interior: HashSet<NodeId> =
3008 back.intersection(&fwd_from_diverge).copied().collect();
3009 interior.remove(&self.diverge);
3010 // The exit itself is always part of the arm even if (for a
3011 // degenerate arm) it equals the diverge point — but a
3012 // diverge-equals-exit arm has an empty interior, which would
3013 // make the arm indistinguishable from "no route", so reject.
3014 if interior.is_empty() {
3015 return Err(invalid(format!(
3016 "arm exit Node#{} has no interior strictly after diverge \
3017 Node#{}; an arm must add at least one node between the \
3018 diverge point and its exit",
3019 exit.0, self.diverge.0,
3020 )));
3021 }
3022 arm_interiors.push(interior);
3023 }
3024
3025 // (3a) Arms must not share interior nodes.
3026 for i in 0..arm_interiors.len() {
3027 for j in (i + 1)..arm_interiors.len() {
3028 if let Some(shared) = arm_interiors[i].intersection(&arm_interiors[j]).next() {
3029 return Err(invalid(format!(
3030 "arms {i} and {j} share interior Node#{}; arms must be \
3031 internally disjoint",
3032 shared.0,
3033 )));
3034 }
3035 }
3036 }
3037
3038 // (3b) No arm-interior node may be read from outside the branch.
3039 // The branch's universe is the union of all arm interiors plus
3040 // the merge node; reconverge_at reading an arm exit is the one
3041 // legitimate "external" consumer.
3042 let mut branch_universe: HashSet<NodeId> = HashSet::new();
3043 for interior in &arm_interiors {
3044 branch_universe.extend(interior.iter().copied());
3045 }
3046 branch_universe.insert(reconverge_at);
3047 for (i, interior) in arm_interiors.iter().enumerate() {
3048 for &m in interior {
3049 if let Some(cs) = consumers.get(&m) {
3050 for &c in cs {
3051 if !branch_universe.contains(&c) {
3052 return Err(invalid(format!(
3053 "arm {i} interior Node#{} is read from outside \
3054 the branch by Node#{}; arm interiors must not be \
3055 reachable from outside the branch",
3056 m.0, c.0,
3057 )));
3058 }
3059 }
3060 }
3061 }
3062 }
3063
3064 // All validation passed — emit the Branch node. Its inputs ARE the
3065 // arm exits, in priority order (arm 0 first); reconverge_at is
3066 // carried on the op. Shape/dtype mirror arm 0 (the uniform merge
3067 // type validated above).
3068 let branch = graph.push(Node {
3069 op: Op::Branch { reconverge_at },
3070 inputs: self.arms.clone(),
3071 shape: want_shape,
3072 dtype: want_dtype,
3073 });
3074 Ok(Some(branch))
3075 }
3076}
3077
3078/// A shared, mutable graph. Builders clone this cheaply and hand it to
3079/// every derived tensor so that all tensors in one computation point to
3080/// the same arena.
3081pub type SharedGraph = Arc<RwLock<Graph>>;
3082
3083/// A handle to a node in a shared graph. Cheap to clone. Carries the
3084/// graph reference so builder methods have everything they need to append
3085/// a new node.
3086#[derive(Debug, Clone)]
3087pub struct NodeHandle {
3088 graph: SharedGraph,
3089 id: NodeId,
3090}
3091
3092impl NodeHandle {
3093 /// Wrap an existing `(graph, node_id)` pair as a NodeHandle handle.
3094 /// Used by graph-rewriting passes (e.g., `opt::insert_copies`)
3095 /// that produce new root `NodeId`s and need to hand them back to
3096 /// call sites as Tensors.
3097 pub fn from_existing(graph: SharedGraph, id: NodeId) -> Self {
3098 Self { graph, id }
3099 }
3100
3101 /// The node ID this handle points to.
3102 pub fn id(&self) -> NodeId {
3103 self.id
3104 }
3105
3106 /// The shared graph this handle belongs to. Exposed so executors and
3107 /// tests can walk the underlying arena.
3108 pub fn graph(&self) -> &SharedGraph {
3109 &self.graph
3110 }
3111
3112 /// This tensor's graph identity — see [`GraphId`].
3113 ///
3114 /// Two tensors can be combined **iff** their `graph_id`s match. Affinity is
3115 /// still *checked* by pointer identity (`Arc::ptr_eq`, which cannot alias);
3116 /// this is the human-readable form, so a failure can say *which* graphs are
3117 /// involved rather than only that they differ.
3118 pub fn graph_id(&self) -> GraphId {
3119 self.graph.read().unwrap().id()
3120 }
3121
3122 /// The shape of this tensor, read from the underlying node.
3123 pub fn shape(&self) -> Shape {
3124 self.graph.read().unwrap().node(self.id).shape.clone()
3125 }
3126
3127 /// The dtype of this tensor, read from the underlying node.
3128 pub fn dtype(&self) -> DType {
3129 self.graph.read().unwrap().node(self.id).dtype
3130 }
3131
3132 /// Phase 7.5 work item G: look up the realized-storage slot for
3133 /// this tensor's node, if any. Returns an Arc clone so the slot
3134 /// stays in the map after this call and the caller's Arc keeps
3135 /// the bytes alive even if a later eviction removes the map
3136 /// entry. `None` means "not realized yet" — the caller should
3137 /// realize the graph first.
3138 pub fn storage_for(&self) -> Option<Arc<RwLock<Storage>>> {
3139 self.graph.read().unwrap().storage_for(self.id)
3140 }
3141
3142 /// The placement hint for this tensor's node, if one was set. `None`
3143 /// means "inherit from the executor's default device."
3144 pub fn placement(&self) -> Option<DeviceLocation> {
3145 self.graph.read().unwrap().placement(self.id)
3146 }
3147
3148 /// Tag this tensor's node with a target device. The executor will
3149 /// validate (post-Phase-1) that the node's op can be evaluated on
3150 /// that device. Returns the same `NodeHandle` handle so this composes
3151 /// with builder-style graph construction:
3152 ///
3153 /// ```ignore
3154 /// let y = a.matmul(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3155 /// ```
3156 pub fn on_device(self, loc: DeviceLocation) -> Self {
3157 self.graph.write().unwrap().set_placement(self.id, loc);
3158 self
3159 }
3160
3161 /// Release this tensor's device-resident storage. Appends an
3162 /// `Op::Release` node whose output is a zero-element marker (shape
3163 /// `[0]`, same dtype as self). Destructive on `self` — after this
3164 /// op runs, `self`'s storage is gone.
3165 ///
3166 /// The ordering-analysis pass (`opt::derive_ordering`, arriving in
3167 /// a follow-up PR) automatically pins the Release to run after
3168 /// every non-destructive reader of `self`. Callers should NOT
3169 /// invoke this directly in a graph that has other readers of
3170 /// `self` until that pass is in place — today's executor has no
3171 /// mechanism to stop them running in the wrong order.
3172 pub fn release(&self) -> Self {
3173 let dtype = self.dtype();
3174 let id = self.graph.write().unwrap().push(Node {
3175 op: Op::Release,
3176 inputs: vec![self.id],
3177 shape: Shape::from_dims(&[0]),
3178 dtype,
3179 });
3180 NodeHandle {
3181 graph: Arc::clone(&self.graph),
3182 id,
3183 }
3184 }
3185
3186 /// Move this tensor's data to `target` device — destroying the
3187 /// source in the process. Appends an `Op::Move` node. The output
3188 /// has the same shape and dtype as the input and lives on
3189 /// `target`; the source's device storage is freed once the op
3190 /// runs.
3191 ///
3192 /// Semantically equivalent to `copy_to_device(target)` followed
3193 /// by dropping the source. Use this when you KNOW the source
3194 /// won't be needed after the transfer — it lets backends skip
3195 /// the intermediate alloc in fast-path cases and lets the
3196 /// scheduler free the source's device memory immediately.
3197 ///
3198 /// If the source may still be read by other ops, use
3199 /// [`Self::copy_to_device`] instead — Copy leaves the source
3200 /// resident.
3201 ///
3202 /// The ordering-analysis pass (`opt::derive_ordering`)
3203 /// automatically pins this op to run after every non-destructive
3204 /// reader of the source. The caller does NOT need to worry about
3205 /// topo ordering — just emit the Move wherever the data-flow
3206 /// says it should go.
3207 pub fn move_to_device(&self, target: DeviceLocation) -> Self {
3208 let shape = self.shape();
3209 let dtype = self.dtype();
3210 let id = self.graph.write().unwrap().push(Node {
3211 op: Op::Move { target },
3212 inputs: vec![self.id],
3213 shape,
3214 dtype,
3215 });
3216 NodeHandle {
3217 graph: Arc::clone(&self.graph),
3218 id,
3219 }
3220 }
3221
3222 /// Copy this tensor's data to `target` device. Source stays
3223 /// resident. Appends an `Op::Copy` node. The output has the same
3224 /// shape and dtype as the input; only residency changes.
3225 ///
3226 /// Same-device copies are still a legal thing to ask for — the
3227 /// backend can optimize them into a cheap clone (or the scheduler
3228 /// can elide the Copy node entirely). Cross-device copies resolve
3229 /// through the pipelined executor's Copy arm (kernel lookup at
3230 /// `(OpKind::Copy, [dt, dt], source backend)`) — today a host
3231 /// round-trip; P2P comes later.
3232 pub fn copy_to_device(&self, target: DeviceLocation) -> Self {
3233 let shape = self.shape();
3234 let dtype = self.dtype();
3235 let id = self.graph.write().unwrap().push(Node {
3236 op: Op::Copy { target },
3237 inputs: vec![self.id],
3238 shape,
3239 dtype,
3240 });
3241 NodeHandle {
3242 graph: Arc::clone(&self.graph),
3243 id,
3244 }
3245 }
3246
3247 /// Project one logical output out of a multi-output producer node.
3248 ///
3249 /// `self` must have been declared as a multi-output producer via
3250 /// [`Graph::set_output_views`] (Session 2's authoring contract will
3251 /// drive this for real fused ops; Session 1 tests drive it
3252 /// directly). The View's output shape, dtype, and layout come from
3253 /// `output_views(self.id)[slot]`. Zero bytes are moved at
3254 /// realization time — the View shares the producer's bundled
3255 /// `Arc<RwLock<Storage>>` and exposes the slot's typed window.
3256 ///
3257 /// **Returns `Result`**: the producer must have declared its slot
3258 /// specs; `slot` must be in range. Errors at graph-build time
3259 /// (per the `validate-at-graph-build-time` rule); the executor
3260 /// never sees a malformed View node.
3261 pub fn view(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3262 let mut graph_w = self.graph.write().unwrap();
3263 let (slot_shape, slot_dtype, slot_byte_offset, slot_layout) = {
3264 let views = graph_w.output_views(self.id).ok_or_else(|| {
3265 fuel_ir::Error::Msg(format!(
3266 "NodeHandle::view: Node#{} is not a multi-output \
3267 producer (no output_views registered)",
3268 self.id.0,
3269 ))
3270 .bt()
3271 })?;
3272 let idx = slot as usize;
3273 let v = views.get(idx).ok_or_else(|| {
3274 fuel_ir::Error::Msg(format!(
3275 "NodeHandle::view: slot {idx} out of range \
3276 (producer has {} slots)",
3277 views.len(),
3278 ))
3279 .bt()
3280 })?;
3281 (v.shape.clone(), v.dtype, v.byte_offset, v.layout.clone())
3282 };
3283 let id = graph_w.push(Node {
3284 op: Op::View { slot },
3285 inputs: vec![self.id],
3286 shape: slot_shape.clone(),
3287 dtype: slot_dtype,
3288 });
3289 // Compose the slot's intrinsic layout (which carries
3290 // slot-relative strides + start_offset) with the slot's
3291 // byte_offset inside the bundle. The result is the layout a
3292 // downstream kernel sees when treating the producer's bundle
3293 // bytes as `slot_dtype` elements: start_offset is in slot-
3294 // dtype-element units; bundle byte_offset is divided by the
3295 // dtype's size_in_bytes to land at the slot's first byte. The
3296 // bundled allocator (`compose_bundle`) aligns each slot's
3297 // byte_offset to its dtype size — so the division is exact.
3298 let dtype_bytes = slot_dtype.size_in_bytes().max(1);
3299 let extra_offset = slot_byte_offset / dtype_bytes;
3300 let effective_layout = if extra_offset == 0 {
3301 slot_layout
3302 } else {
3303 Layout::new(
3304 slot_layout.shape().clone(),
3305 slot_layout.stride().to_vec().into_iter().collect(),
3306 slot_layout.start_offset() + extra_offset,
3307 )
3308 };
3309 // The side-table is set whenever the effective layout differs
3310 // from `Layout::contiguous(slot_shape)` — i.e. whenever the
3311 // slot has a strided layout OR a non-zero composed offset
3312 // (slot 1+ in any bundle).
3313 if effective_layout != Layout::contiguous(slot_shape) {
3314 graph_w.set_layout(id, effective_layout);
3315 }
3316 drop(graph_w);
3317 Ok(NodeHandle {
3318 graph: Arc::clone(&self.graph),
3319 id,
3320 })
3321 }
3322
3323 /// Owned variant of [`Self::view`] — the slot's bytes are copied
3324 /// into a fresh contiguous Storage at realization time, so the
3325 /// producer's bundle Arc can drop independently. Output layout
3326 /// is always contiguous.
3327 ///
3328 /// Same validation as `view`; same error surface.
3329 pub fn view_owned(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3330 let mut graph_w = self.graph.write().unwrap();
3331 let (slot_shape, slot_dtype) = {
3332 let views = graph_w.output_views(self.id).ok_or_else(|| {
3333 fuel_ir::Error::Msg(format!(
3334 "NodeHandle::view_owned: Node#{} is not a multi-output \
3335 producer (no output_views registered)",
3336 self.id.0,
3337 ))
3338 .bt()
3339 })?;
3340 let idx = slot as usize;
3341 let v = views.get(idx).ok_or_else(|| {
3342 fuel_ir::Error::Msg(format!(
3343 "NodeHandle::view_owned: slot {idx} out of range \
3344 (producer has {} slots)",
3345 views.len(),
3346 ))
3347 .bt()
3348 })?;
3349 (v.shape.clone(), v.dtype)
3350 };
3351 let id = graph_w.push(Node {
3352 op: Op::ViewOwned { slot },
3353 inputs: vec![self.id],
3354 shape: slot_shape,
3355 dtype: slot_dtype,
3356 });
3357 drop(graph_w);
3358 Ok(NodeHandle {
3359 graph: Arc::clone(&self.graph),
3360 id,
3361 })
3362 }
3363
3364 /// Append an `Op::WriteSlice` node — copies `source`'s bytes into
3365 /// `self` at the rectangular slab defined by `ranges`. Per-axis,
3366 /// `ranges[i] = (start, end)` is the half-open destination range;
3367 /// `source.dims()[i]` must equal `end - start`, and `end` must
3368 /// not exceed `self.dims()[i]`. Dtypes must match.
3369 ///
3370 /// Destructive on `self`: after the write, `self`'s NodeId is no
3371 /// longer readable (the scheduler pins this op to run after every
3372 /// other reader of `self` via [`opt::derive_ordering`]). The
3373 /// returned tensor adopts `self`'s Storage and Layout; downstream
3374 /// consumers read post-write bytes through this NodeId.
3375 ///
3376 /// Phase E.3.2: introduced to back persistent KV-cache writes
3377 /// (`InferenceContext` + `KvCache`). Non-differentiable.
3378 ///
3379 /// **Returns `Result`**: rank/shape/range mismatches surface as a
3380 /// typed error.
3381 pub fn write_slice(
3382 &self,
3383 source: &NodeHandle,
3384 ranges: Vec<(usize, usize)>,
3385 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3386 self.require_same_graph(source, "write_slice", "source")?;
3387 let dest_shape = self.shape();
3388 let dest_dims = dest_shape.dims();
3389 let src_shape = source.shape();
3390 let src_dims = src_shape.dims();
3391 let rank = dest_dims.len();
3392 if ranges.len() != rank {
3393 return Err(fuel_ir::Error::Msg(format!(
3394 "write_slice: ranges.len() ({}) must equal destination rank ({rank})",
3395 ranges.len(),
3396 ))
3397 .bt());
3398 }
3399 if src_dims.len() != rank {
3400 return Err(fuel_ir::Error::Msg(format!(
3401 "write_slice: source rank ({}) must equal destination rank ({rank})",
3402 src_dims.len(),
3403 ))
3404 .bt());
3405 }
3406 for (i, &(start, end)) in ranges.iter().enumerate() {
3407 if end < start {
3408 return Err(fuel_ir::Error::Msg(format!(
3409 "write_slice: ranges[{i}] = ({start}, {end}) has end < start"
3410 ))
3411 .bt());
3412 }
3413 if end > dest_dims[i] {
3414 return Err(fuel_ir::Error::Msg(format!(
3415 "write_slice: ranges[{i}].end ({end}) > destination dim {i} ({})",
3416 dest_dims[i],
3417 ))
3418 .bt());
3419 }
3420 let slab = end - start;
3421 if src_dims[i] != slab {
3422 return Err(fuel_ir::Error::Msg(format!(
3423 "write_slice: source dim {i} ({}) must equal slab width ({slab}) \
3424 = ranges[{i}].end - ranges[{i}].start",
3425 src_dims[i],
3426 ))
3427 .bt());
3428 }
3429 }
3430 if self.dtype() != source.dtype() {
3431 return Err(fuel_ir::Error::Msg(format!(
3432 "write_slice: dtype mismatch — destination {:?} vs source {:?}",
3433 self.dtype(),
3434 source.dtype(),
3435 ))
3436 .bt());
3437 }
3438 let dtype = self.dtype();
3439 let id = self.graph.write().unwrap().push(Node {
3440 op: Op::WriteSlice {
3441 ranges,
3442 dyn_offset: None,
3443 },
3444 inputs: vec![self.id, source.id],
3445 shape: dest_shape,
3446 dtype,
3447 });
3448 Ok(NodeHandle {
3449 graph: Arc::clone(&self.graph),
3450 id,
3451 })
3452 }
3453
3454 /// Append an `Op::WriteSlice` whose start on `dyn_axis` is a runtime
3455 /// value resolved through the per-pass [`fuel_ir::SymEnv`] at
3456 /// realize, rather than the build-time `ranges[dyn_axis].0`.
3457 ///
3458 /// This is the **input-determined** dynamic-offset path (a
3459 /// [`DynScalar`] over the one `SymEnv`), distinct from
3460 /// [`Self::write_slice_rotating`]'s **data-determined** position (a
3461 /// tensor input read mid-pass). It backs the persistent decode
3462 /// KV-cache write: the append offset is `cached_len`, a per-token
3463 /// runtime value over a fixed-capacity buffer, so the graph
3464 /// structure (and every shape) stays identical across tokens and the
3465 /// plan is reused (Phase D symbolic extents).
3466 ///
3467 /// On `dyn_axis`, `ranges[dyn_axis].0` is ignored (the start is
3468 /// dynamic) and `ranges[dyn_axis].1 - ranges[dyn_axis].0` is the slab
3469 /// width, which must equal `source.dims()[dyn_axis]` and not exceed
3470 /// the destination capacity on that axis. On every other axis the
3471 /// same shape contract as [`Self::write_slice`] applies. The runtime
3472 /// `offset + width` is bounds-checked against the destination
3473 /// capacity at realize (a typed error, never a panic).
3474 ///
3475 /// **Returns `Result`**: rank/dtype/axis-bound/width mismatches
3476 /// surface as a typed error at build time.
3477 pub fn write_slice_dyn(
3478 &self,
3479 source: &NodeHandle,
3480 ranges: Vec<(usize, usize)>,
3481 dyn_axis: usize,
3482 offset: DynScalar,
3483 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3484 self.require_same_graph(source, "write_slice_dyn", "source")?;
3485 let dest_shape = self.shape();
3486 let dest_dims = dest_shape.dims();
3487 let src_shape = source.shape();
3488 let src_dims = src_shape.dims();
3489 let rank = dest_dims.len();
3490 if ranges.len() != rank {
3491 return Err(fuel_ir::Error::Msg(format!(
3492 "write_slice_dyn: ranges.len() ({}) must equal destination rank ({rank})",
3493 ranges.len(),
3494 ))
3495 .bt());
3496 }
3497 if src_dims.len() != rank {
3498 return Err(fuel_ir::Error::Msg(format!(
3499 "write_slice_dyn: source rank ({}) must equal destination rank ({rank})",
3500 src_dims.len(),
3501 ))
3502 .bt());
3503 }
3504 if dyn_axis >= rank {
3505 return Err(fuel_ir::Error::Msg(format!(
3506 "write_slice_dyn: dyn_axis ({dyn_axis}) out of bounds for rank {rank}",
3507 ))
3508 .bt());
3509 }
3510 for (i, &(start, end)) in ranges.iter().enumerate() {
3511 if end < start {
3512 return Err(fuel_ir::Error::Msg(format!(
3513 "write_slice_dyn: ranges[{i}] = ({start}, {end}) has end < start"
3514 ))
3515 .bt());
3516 }
3517 let slab = end - start;
3518 if src_dims[i] != slab {
3519 return Err(fuel_ir::Error::Msg(format!(
3520 "write_slice_dyn: source dim {i} ({}) must equal slab width ({slab}) \
3521 = ranges[{i}].end - ranges[{i}].start",
3522 src_dims[i],
3523 ))
3524 .bt());
3525 }
3526 if i == dyn_axis {
3527 // The start on `dyn_axis` is dynamic, so `ranges[i].0`/`.1`
3528 // are not bounded by `dest_dims[i]` here — only the slab
3529 // WIDTH must fit the capacity. The runtime `offset + width`
3530 // is bounds-checked against `dest_dims[i]` at realize.
3531 if slab > dest_dims[i] {
3532 return Err(fuel_ir::Error::Msg(format!(
3533 "write_slice_dyn: dynamic-axis slab width ({slab}) > destination capacity \
3534 dim {i} ({})",
3535 dest_dims[i],
3536 ))
3537 .bt());
3538 }
3539 } else if end > dest_dims[i] {
3540 return Err(fuel_ir::Error::Msg(format!(
3541 "write_slice_dyn: ranges[{i}].end ({end}) > destination dim {i} ({})",
3542 dest_dims[i],
3543 ))
3544 .bt());
3545 }
3546 }
3547 if self.dtype() != source.dtype() {
3548 return Err(fuel_ir::Error::Msg(format!(
3549 "write_slice_dyn: dtype mismatch — destination {:?} vs source {:?}",
3550 self.dtype(),
3551 source.dtype(),
3552 ))
3553 .bt());
3554 }
3555 let dtype = self.dtype();
3556 let id = self.graph.write().unwrap().push(Node {
3557 op: Op::WriteSlice {
3558 ranges,
3559 dyn_offset: Some((dyn_axis, offset)),
3560 },
3561 inputs: vec![self.id, source.id],
3562 shape: dest_shape,
3563 dtype,
3564 });
3565 Ok(NodeHandle {
3566 graph: Arc::clone(&self.graph),
3567 id,
3568 })
3569 }
3570
3571 /// Append an [`Op::WriteSliceRotating`] node — copies `source`'s
3572 /// bytes into `self` at the rectangular slab defined by `ranges`,
3573 /// with the `axis` axis wrapping modulo `modulus`. The dynamic
3574 /// write position comes through `position` (a rank-0 `U32`
3575 /// tensor); the kernel computes `start = position % modulus` and
3576 /// splits the write across the ring boundary if needed.
3577 ///
3578 /// `ranges[axis].0` is ignored (the rotating-axis start is
3579 /// dynamic). `ranges[axis].1 - ranges[axis].0` is the write
3580 /// length on the rotating axis and must equal `source.dims()[axis]`.
3581 /// On every other axis the same shape contract as `write_slice`
3582 /// applies.
3583 ///
3584 /// Destructive on `self`; scheduled like `write_slice`. Backward
3585 /// panics — sliding-window KV-cache writes are forward-only.
3586 ///
3587 /// **Returns `Result`**: rank/dtype/axis-bound/modulus/range
3588 /// mismatches surface as a typed error at build time.
3589 pub fn write_slice_rotating(
3590 &self,
3591 source: &NodeHandle,
3592 position: &NodeHandle,
3593 axis: usize,
3594 modulus: usize,
3595 ranges: Vec<(usize, usize)>,
3596 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3597 self.require_same_graph(source, "write_slice_rotating", "source")?;
3598 self.require_same_graph(position, "write_slice_rotating", "position")?;
3599 let dest_shape = self.shape();
3600 let dest_dims = dest_shape.dims();
3601 let src_shape = source.shape();
3602 let src_dims = src_shape.dims();
3603 let rank = dest_dims.len();
3604 if ranges.len() != rank {
3605 return Err(fuel_ir::Error::Msg(format!(
3606 "write_slice_rotating: ranges.len() ({}) must equal destination rank ({rank})",
3607 ranges.len(),
3608 ))
3609 .bt());
3610 }
3611 if src_dims.len() != rank {
3612 return Err(fuel_ir::Error::Msg(format!(
3613 "write_slice_rotating: source rank ({}) must equal destination rank ({rank})",
3614 src_dims.len(),
3615 ))
3616 .bt());
3617 }
3618 if axis >= rank {
3619 return Err(fuel_ir::Error::Msg(format!(
3620 "write_slice_rotating: axis {axis} out of bounds for rank {rank}",
3621 ))
3622 .bt());
3623 }
3624 if modulus == 0 {
3625 return Err(
3626 fuel_ir::Error::Msg("write_slice_rotating: modulus must be >= 1".into()).bt(),
3627 );
3628 }
3629 if modulus > dest_dims[axis] {
3630 return Err(fuel_ir::Error::Msg(format!(
3631 "write_slice_rotating: modulus ({modulus}) must not exceed destination dim {axis} ({})",
3632 dest_dims[axis],
3633 )).bt());
3634 }
3635 for (i, &(start, end)) in ranges.iter().enumerate() {
3636 if end < start {
3637 return Err(fuel_ir::Error::Msg(format!(
3638 "write_slice_rotating: ranges[{i}] = ({start}, {end}) has end < start"
3639 ))
3640 .bt());
3641 }
3642 let slab = end - start;
3643 if i == axis {
3644 if slab == 0 {
3645 return Err(fuel_ir::Error::Msg(format!(
3646 "write_slice_rotating: ranges[axis={axis}] slab is 0",
3647 ))
3648 .bt());
3649 }
3650 if slab > modulus {
3651 return Err(fuel_ir::Error::Msg(format!(
3652 "write_slice_rotating: rotating-axis write length ({slab}) > modulus ({modulus})",
3653 )).bt());
3654 }
3655 if src_dims[i] != slab {
3656 return Err(fuel_ir::Error::Msg(format!(
3657 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3658 src_dims[i],
3659 ))
3660 .bt());
3661 }
3662 // ranges[axis].1 itself isn't bounded by dest_dims[axis] —
3663 // the kernel wraps the start, so the logical end is meaningless.
3664 // We still require .1 <= modulus to make the slab description
3665 // self-consistent inside the window.
3666 if end > modulus {
3667 return Err(fuel_ir::Error::Msg(format!(
3668 "write_slice_rotating: ranges[axis={axis}].end ({end}) > modulus ({modulus})",
3669 )).bt());
3670 }
3671 } else {
3672 if end > dest_dims[i] {
3673 return Err(fuel_ir::Error::Msg(format!(
3674 "write_slice_rotating: ranges[{i}].end ({end}) > destination dim {i} ({})",
3675 dest_dims[i],
3676 ))
3677 .bt());
3678 }
3679 if src_dims[i] != slab {
3680 return Err(fuel_ir::Error::Msg(format!(
3681 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3682 src_dims[i],
3683 ))
3684 .bt());
3685 }
3686 }
3687 }
3688 if self.dtype() != source.dtype() {
3689 return Err(fuel_ir::Error::Msg(format!(
3690 "write_slice_rotating: dtype mismatch — destination {:?} vs source {:?}",
3691 self.dtype(),
3692 source.dtype(),
3693 ))
3694 .bt());
3695 }
3696 if position.dtype() != DType::U32 {
3697 return Err(fuel_ir::Error::Msg(format!(
3698 "write_slice_rotating: position must be U32, got {:?}",
3699 position.dtype(),
3700 ))
3701 .bt());
3702 }
3703 if !position.shape().dims().is_empty() {
3704 return Err(fuel_ir::Error::Msg(format!(
3705 "write_slice_rotating: position must be rank-0 scalar, got {:?}",
3706 position.shape().dims(),
3707 ))
3708 .bt());
3709 }
3710 let dtype = self.dtype();
3711 let id = self.graph.write().unwrap().push(Node {
3712 op: Op::WriteSliceRotating {
3713 axis,
3714 modulus,
3715 ranges,
3716 },
3717 inputs: vec![self.id, source.id, position.id],
3718 shape: dest_shape,
3719 dtype,
3720 });
3721 Ok(NodeHandle {
3722 graph: Arc::clone(&self.graph),
3723 id,
3724 })
3725 }
3726
3727 /// Append an [`Op::WriteSliceDoff`] node — copies `source`'s bytes
3728 /// into `self` at the rectangular slab defined by `ranges`, with
3729 /// the start on `axis` read from `offset` (a rank-0 `I64` tensor)
3730 /// **device-side** at kernel launch. No modulo wrap: `offset` is
3731 /// the raw start on `axis`.
3732 ///
3733 /// `ranges[axis].0` is ignored (the dynamic-axis start is device-
3734 /// resident). `ranges[axis].1 - ranges[axis].0` is the write width
3735 /// on `axis` and must equal `source.dims()[axis]`. On every other
3736 /// axis the same shape contract as [`write_slice`](Self::write_slice)
3737 /// applies.
3738 ///
3739 /// **Bounds are the caller's contract**: `offset` is device-only at
3740 /// build time, so `offset + width <= dest_dims[axis]` cannot be
3741 /// checked here and the kernel does NOT clamp. The caller must size
3742 /// `self`'s capacity on `axis` to cover the largest offset (this is
3743 /// the CUDA-graph-capturable KV-cache append; `DecodeSession` sizes
3744 /// `max_seq`). The static slab width IS checked against capacity.
3745 ///
3746 /// Destructive on `self`; scheduled like `write_slice`. Backward
3747 /// panics — decode-time KV-cache appends are forward-only.
3748 ///
3749 /// **Returns `Result`**: rank / dtype / axis-bound / static-width /
3750 /// offset-dtype mismatches surface as a typed error at build time.
3751 pub fn write_slice_doff(
3752 &self,
3753 source: &NodeHandle,
3754 offset: &NodeHandle,
3755 axis: usize,
3756 ranges: Vec<(usize, usize)>,
3757 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3758 self.require_same_graph(source, "write_slice_doff", "source")?;
3759 self.require_same_graph(offset, "write_slice_doff", "offset")?;
3760 let dest_shape = self.shape();
3761 let dest_dims = dest_shape.dims();
3762 let src_dims = source.shape().dims().to_vec();
3763 let rank = dest_dims.len();
3764 if ranges.len() != rank {
3765 return Err(fuel_ir::Error::Msg(format!(
3766 "write_slice_doff: ranges.len() ({}) must equal destination rank ({rank})",
3767 ranges.len(),
3768 ))
3769 .bt());
3770 }
3771 if src_dims.len() != rank {
3772 return Err(fuel_ir::Error::Msg(format!(
3773 "write_slice_doff: source rank ({}) must equal destination rank ({rank})",
3774 src_dims.len(),
3775 ))
3776 .bt());
3777 }
3778 if axis >= rank {
3779 return Err(fuel_ir::Error::Msg(format!(
3780 "write_slice_doff: axis {axis} out of bounds for rank {rank}",
3781 ))
3782 .bt());
3783 }
3784 for (i, &(start, end)) in ranges.iter().enumerate() {
3785 if end < start {
3786 return Err(fuel_ir::Error::Msg(format!(
3787 "write_slice_doff: ranges[{i}] = ({start}, {end}) has end < start"
3788 ))
3789 .bt());
3790 }
3791 let slab = end - start;
3792 if i == axis {
3793 if slab == 0 {
3794 return Err(fuel_ir::Error::Msg(format!(
3795 "write_slice_doff: ranges[axis={axis}] slab is 0",
3796 ))
3797 .bt());
3798 }
3799 // The write width can't exceed the buffer capacity on
3800 // `axis` even at offset 0 (the offset itself is dynamic
3801 // and bounds-checked device-side by the caller's sizing).
3802 if slab > dest_dims[axis] {
3803 return Err(fuel_ir::Error::Msg(format!(
3804 "write_slice_doff: dynamic-axis write width ({slab}) > destination dim {axis} ({})",
3805 dest_dims[axis],
3806 )).bt());
3807 }
3808 if src_dims[i] != slab {
3809 return Err(fuel_ir::Error::Msg(format!(
3810 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3811 src_dims[i],
3812 ))
3813 .bt());
3814 }
3815 } else {
3816 if end > dest_dims[i] {
3817 return Err(fuel_ir::Error::Msg(format!(
3818 "write_slice_doff: ranges[{i}].end ({end}) > destination dim {i} ({})",
3819 dest_dims[i],
3820 ))
3821 .bt());
3822 }
3823 if src_dims[i] != slab {
3824 return Err(fuel_ir::Error::Msg(format!(
3825 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3826 src_dims[i],
3827 ))
3828 .bt());
3829 }
3830 }
3831 }
3832 if self.dtype() != source.dtype() {
3833 return Err(fuel_ir::Error::Msg(format!(
3834 "write_slice_doff: dtype mismatch — destination {:?} vs source {:?}",
3835 self.dtype(),
3836 source.dtype(),
3837 ))
3838 .bt());
3839 }
3840 if offset.dtype() != DType::I64 {
3841 return Err(fuel_ir::Error::Msg(format!(
3842 "write_slice_doff: offset must be I64 (device-resident start), got {:?}",
3843 offset.dtype(),
3844 ))
3845 .bt());
3846 }
3847 if !offset.shape().dims().is_empty() {
3848 return Err(fuel_ir::Error::Msg(format!(
3849 "write_slice_doff: offset must be rank-0 scalar, got {:?}",
3850 offset.shape().dims(),
3851 ))
3852 .bt());
3853 }
3854 let dtype = self.dtype();
3855 let id = self.graph.write().unwrap().push(Node {
3856 op: Op::WriteSliceDoff { axis, ranges },
3857 inputs: vec![self.id, source.id, offset.id],
3858 shape: dest_shape,
3859 dtype,
3860 });
3861 Ok(NodeHandle {
3862 graph: Arc::clone(&self.graph),
3863 id,
3864 })
3865 }
3866
3867 /// Build a `Const` tensor from an `f32` slice and shape on a fresh
3868 /// graph. The new graph is returned via the tensor's `graph` handle.
3869 ///
3870 /// `data` takes `impl Into<Arc<[f32]>>` so both `Vec<f32>` (one-time
3871 /// conversion at the call site) and `Arc<[f32]>` (free clone that
3872 /// shares buffers across forward passes) work.
3873 ///
3874 /// Phase 7.5 work item G2: `device` is the device on which the
3875 /// realized Storage is allocated. The graph's storage_map slot is
3876 /// populated with that Storage and `Op::Const` is emitted —
3877 /// no host-side `ConstData` payload rides on the node.
3878 pub fn from_f32(
3879 data: impl Into<Arc<[f32]>>,
3880 shape: impl Into<Shape>,
3881 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3882 ) -> Result<Self, fuel_ir::Error> {
3883 let v: Arc<[f32]> = data.into();
3884 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
3885 Self::from_host_buffer(buf, DType::F32, shape, device)
3886 }
3887
3888 /// Build a `Const` tensor from an `f64` slice and shape on a fresh graph.
3889 /// `device` selects where the realized Storage is allocated.
3890 pub fn from_f64(
3891 data: impl Into<Arc<[f64]>>,
3892 shape: impl Into<Shape>,
3893 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3894 ) -> Result<Self, fuel_ir::Error> {
3895 let v: Arc<[f64]> = data.into();
3896 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
3897 Self::from_host_buffer(buf, DType::F64, shape, device)
3898 }
3899
3900 /// Build a `Const` tensor from a `bf16` slice and shape on a fresh graph.
3901 /// `device` selects where the realized Storage is allocated.
3902 pub fn from_bf16(
3903 data: impl Into<Arc<[bf16]>>,
3904 shape: impl Into<Shape>,
3905 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3906 ) -> Result<Self, fuel_ir::Error> {
3907 let v: Arc<[bf16]> = data.into();
3908 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
3909 Self::from_host_buffer(buf, DType::BF16, shape, device)
3910 }
3911
3912 /// Build a `Const` tensor from an `f16` slice and shape on a fresh graph.
3913 /// `device` selects where the realized Storage is allocated.
3914 pub fn from_f16(
3915 data: impl Into<Arc<[f16]>>,
3916 shape: impl Into<Shape>,
3917 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3918 ) -> Result<Self, fuel_ir::Error> {
3919 let v: Arc<[f16]> = data.into();
3920 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
3921 Self::from_host_buffer(buf, DType::F16, shape, device)
3922 }
3923
3924 /// Build a `Const` tensor from a `u32` slice and shape on a fresh
3925 /// graph. Primarily used to construct index tensors for gather /
3926 /// scatter / index_select. `u32` is the index type all real fuel
3927 /// backends use (Candle CPU, CUDA, Metal), so keeping the reference
3928 /// on the same type means oracle-equivalence tests do not need any
3929 /// index-type translation. `device` selects where the realized
3930 /// Storage is allocated.
3931 pub fn from_u32(
3932 data: impl Into<Arc<[u32]>>,
3933 shape: impl Into<Shape>,
3934 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3935 ) -> Result<Self, fuel_ir::Error> {
3936 let v: Arc<[u32]> = data.into();
3937 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
3938 Self::from_host_buffer(buf, DType::U32, shape, device)
3939 }
3940
3941 /// G2 internal funnel: allocate Storage on `device` from `buf`,
3942 /// register the slot, emit `Op::Const`. Per-dtype `from_*` methods
3943 /// delegate here.
3944 fn from_host_buffer(
3945 buf: fuel_ir::HostBuffer,
3946 dtype: DType,
3947 shape: impl Into<Shape>,
3948 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3949 ) -> Result<Self, fuel_ir::Error> {
3950 let graph = Arc::new(RwLock::new(Graph::new()));
3951 Self::from_host_buffer_on(&graph, buf, dtype, shape, device)
3952 }
3953
3954 /// `from_host_buffer` against an **existing** graph — the shared body of the
3955 /// `from_*_on` family. Identical to `from_host_buffer` except that the caller
3956 /// supplies the graph instead of one being minted.
3957 fn from_host_buffer_on(
3958 graph: &SharedGraph,
3959 buf: fuel_ir::HostBuffer,
3960 dtype: DType,
3961 shape: impl Into<Shape>,
3962 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3963 ) -> Result<Self, fuel_ir::Error> {
3964 let shape = shape.into();
3965 let n = host_buffer_elem_count(&buf);
3966 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM because
3967 // `docs/gaps.md` and `CLAUDE.md` both anchor on it -- a prose anchor is
3968 // rename-proof, so changing the words here would orphan two citations
3969 // that no identifier rename could have touched.
3970 if n != shape.elem_count() {
3971 return Err(fuel_ir::Error::Msg(format!(
3972 "NodeHandle::from_*: data length {n} does not match shape element count {}",
3973 shape.elem_count(),
3974 )));
3975 }
3976 // GAP-003: was `.expect(...)`. This is the sibling panic the row's
3977 // anchor could not see -- it carries a DIFFERENT message, and a
3978 // message-specific anchor is blind to exactly that.
3979 let backend_storage = device
3980 .storage_from_host_buffer_owned_dyn(buf)
3981 .map_err(|e| {
3982 fuel_ir::Error::Msg(format!(
3983 "NodeHandle::from_*: device.storage_from_host_buffer_owned_dyn failed: {e}"
3984 ))
3985 })?;
3986 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
3987 let id = {
3988 let mut g = graph.write().unwrap();
3989 let id = g.push(Node {
3990 op: Op::Const,
3991 inputs: vec![],
3992 shape,
3993 dtype,
3994 });
3995 g.set_storage(id, storage_arc);
3996 id
3997 };
3998 Ok(Self {
3999 graph: Arc::clone(graph),
4000 id,
4001 })
4002 }
4003
4004 /// Build an `f32` `Const` leaf **on the graph you pass in**, rather than on a
4005 /// fresh one.
4006 ///
4007 /// This is the non-anchor route for adding a tensor to an existing graph.
4008 /// `NodeHandle::from_f32` mints a NEW graph, so two `from_*` tensors can never be
4009 /// combined; `from_f32_on` puts the new leaf on `graph`, and
4010 /// [`const_f32_like`](Self::const_f32_like) does the same thing when what you
4011 /// have to hand is a sibling *tensor* rather than the graph itself.
4012 ///
4013 /// ```ignore
4014 /// let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
4015 /// let a = NodeHandle::from_f32_on(&g, a_data, [2, 3], &device);
4016 /// let w = NodeHandle::from_f32_on(&g, w_data, [3, 2], &device);
4017 /// let y = a.matmul(&w); // same graph ✓
4018 /// ```
4019 pub fn from_f32_on(
4020 graph: &SharedGraph,
4021 data: impl Into<Arc<[f32]>>,
4022 shape: impl Into<Shape>,
4023 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4024 ) -> Result<Self, fuel_ir::Error> {
4025 let v: Arc<[f32]> = data.into();
4026 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
4027 Self::from_host_buffer_on(graph, buf, DType::F32, shape, device)
4028 }
4029
4030 /// `f64` sibling of [`from_f32_on`](Self::from_f32_on) — builds on the given
4031 /// graph rather than a fresh one.
4032 pub fn from_f64_on(
4033 graph: &SharedGraph,
4034 data: impl Into<Arc<[f64]>>,
4035 shape: impl Into<Shape>,
4036 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4037 ) -> Result<Self, fuel_ir::Error> {
4038 let v: Arc<[f64]> = data.into();
4039 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
4040 Self::from_host_buffer_on(graph, buf, DType::F64, shape, device)
4041 }
4042
4043 /// `bf16` sibling of [`from_f32_on`](Self::from_f32_on). The common
4044 /// mixed-precision shape — f32 activations, bf16 weights — is exactly this
4045 /// plus [`from_f32_on`](Self::from_f32_on) against one shared graph.
4046 pub fn from_bf16_on(
4047 graph: &SharedGraph,
4048 data: impl Into<Arc<[half::bf16]>>,
4049 shape: impl Into<Shape>,
4050 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4051 ) -> Result<Self, fuel_ir::Error> {
4052 let v: Arc<[half::bf16]> = data.into();
4053 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
4054 Self::from_host_buffer_on(graph, buf, DType::BF16, shape, device)
4055 }
4056
4057 /// `f16` sibling of [`from_f32_on`](Self::from_f32_on).
4058 pub fn from_f16_on(
4059 graph: &SharedGraph,
4060 data: impl Into<Arc<[half::f16]>>,
4061 shape: impl Into<Shape>,
4062 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4063 ) -> Result<Self, fuel_ir::Error> {
4064 let v: Arc<[half::f16]> = data.into();
4065 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
4066 Self::from_host_buffer_on(graph, buf, DType::F16, shape, device)
4067 }
4068
4069 /// `u32` sibling of [`from_f32_on`](Self::from_f32_on) — index tensors for
4070 /// gather/index_select built straight onto the graph they will be used on.
4071 pub fn from_u32_on(
4072 graph: &SharedGraph,
4073 data: impl Into<Arc<[u32]>>,
4074 shape: impl Into<Shape>,
4075 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4076 ) -> Result<Self, fuel_ir::Error> {
4077 let v: Arc<[u32]> = data.into();
4078 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
4079 Self::from_host_buffer_on(graph, buf, DType::U32, shape, device)
4080 }
4081
4082 /// Phase 7.5 work item G2: build a `Const` leaf on a fresh graph
4083 /// whose realized bytes already live in `storage`. The graph's
4084 /// storage_map slot for the new node is populated with `storage`
4085 /// directly. The executor's slot-first dispatch returns the slot's
4086 /// Arc on realize.
4087 pub fn from_storage(
4088 storage: Arc<RwLock<Storage>>,
4089 shape: impl Into<Shape>,
4090 dtype: DType,
4091 ) -> Self {
4092 let shape = shape.into();
4093 // Sanity-check the slot's dtype matches the declared dtype.
4094 // The slot's bytes don't carry a logical shape — that's the
4095 // node's job — so we don't validate elem_count here.
4096 debug_assert_eq!(
4097 storage.read().unwrap().dtype(),
4098 dtype,
4099 "NodeHandle::from_storage: declared dtype {:?} does not match storage dtype {:?}",
4100 dtype,
4101 storage.read().unwrap().dtype(),
4102 );
4103 let graph = Arc::new(RwLock::new(Graph::new()));
4104 let id = {
4105 let mut g = graph.write().unwrap();
4106 let id = g.push(Node {
4107 op: Op::Const,
4108 inputs: vec![],
4109 shape,
4110 dtype,
4111 });
4112 g.set_storage(id, storage);
4113 id
4114 };
4115 Self { graph, id }
4116 }
4117
4118 /// Build a second `Const` tensor that lives on the same graph as
4119 /// `self`. Use this to add more inputs to an existing computation.
4120 ///
4121 /// Phase 7.5 G2: the realized Storage is allocated on the device
4122 /// derived from `self`'s graph (any existing slot's device — the
4123 /// graph always has at least one slot-bearing leaf by the time
4124 /// const_*_like is called). For cross-device const construction,
4125 /// build a fresh graph with [`NodeHandle::from_f32`] and link via
4126 /// [`Op::Move`] / [`Op::Copy`].
4127 pub fn const_f32_like(
4128 &self,
4129 data: impl Into<Arc<[f32]>>,
4130 shape: impl Into<Shape>,
4131 ) -> Result<Self, fuel_ir::Error> {
4132 let v: Arc<[f32]> = data.into();
4133 self.const_like_host_buffer(fuel_ir::HostBuffer::F32(v.to_vec()), DType::F32, shape)
4134 }
4135
4136 /// Build a second `Const f64` tensor on the same graph as `self`.
4137 pub fn const_f64_like(
4138 &self,
4139 data: impl Into<Arc<[f64]>>,
4140 shape: impl Into<Shape>,
4141 ) -> Result<Self, fuel_ir::Error> {
4142 let v: Arc<[f64]> = data.into();
4143 self.const_like_host_buffer(fuel_ir::HostBuffer::F64(v.to_vec()), DType::F64, shape)
4144 }
4145
4146 /// Build a second `Const bf16` tensor on the same graph as `self`.
4147 pub fn const_bf16_like(
4148 &self,
4149 data: impl Into<Arc<[bf16]>>,
4150 shape: impl Into<Shape>,
4151 ) -> Result<Self, fuel_ir::Error> {
4152 let v: Arc<[bf16]> = data.into();
4153 self.const_like_host_buffer(fuel_ir::HostBuffer::BF16(v.to_vec()), DType::BF16, shape)
4154 }
4155
4156 /// Build a second `Const f16` tensor on the same graph as `self`.
4157 pub fn const_f16_like(
4158 &self,
4159 data: impl Into<Arc<[f16]>>,
4160 shape: impl Into<Shape>,
4161 ) -> Result<Self, fuel_ir::Error> {
4162 let v: Arc<[f16]> = data.into();
4163 self.const_like_host_buffer(fuel_ir::HostBuffer::F16(v.to_vec()), DType::F16, shape)
4164 }
4165
4166 /// Build a second `Const u32` (index) tensor on the same graph as `self`.
4167 pub fn const_u32_like(
4168 &self,
4169 data: impl Into<Arc<[u32]>>,
4170 shape: impl Into<Shape>,
4171 ) -> Result<Self, fuel_ir::Error> {
4172 let v: Arc<[u32]> = data.into();
4173 self.const_like_host_buffer(fuel_ir::HostBuffer::U32(v.to_vec()), DType::U32, shape)
4174 }
4175
4176 /// Build a sibling U8 `Const` on the same graph. Used by
4177 /// byte-stream inputs (e.g. NF4 quantized weights packed two
4178 /// codes per byte).
4179 pub fn const_u8_like(
4180 &self,
4181 data: impl Into<Arc<[u8]>>,
4182 shape: impl Into<Shape>,
4183 ) -> Result<Self, fuel_ir::Error> {
4184 let v: Arc<[u8]> = data.into();
4185 self.const_like_host_buffer(fuel_ir::HostBuffer::U8(v.to_vec()), DType::U8, shape)
4186 }
4187
4188 /// Build a sibling I64 `Const` on the same graph. Used by
4189 /// integer-target ops (e.g. cross-entropy with class indices in
4190 /// PyTorch convention).
4191 pub fn const_i64_like(
4192 &self,
4193 data: impl Into<Arc<[i64]>>,
4194 shape: impl Into<Shape>,
4195 ) -> Result<Self, fuel_ir::Error> {
4196 let v: Arc<[i64]> = data.into();
4197 self.const_like_host_buffer(fuel_ir::HostBuffer::I64(v.to_vec()), DType::I64, shape)
4198 }
4199
4200 /// G2 internal funnel for the per-graph const_*_like family. The
4201 /// device is derived from `self`'s graph slot (any existing one)
4202 /// so callers don't have to thread a device through hot paths
4203 /// like RoPE table construction or LoRA application — the const
4204 /// goes on the same device as the graph it joins.
4205 fn const_like_host_buffer(
4206 &self,
4207 buf: fuel_ir::HostBuffer,
4208 dtype: DType,
4209 shape: impl Into<Shape>,
4210 ) -> Result<Self, fuel_ir::Error> {
4211 let shape = shape.into();
4212 let n = host_buffer_elem_count(&buf);
4213 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM -- gaps.md
4214 // and CLAUDE.md both anchor on this prose, and a prose anchor is the one
4215 // an identifier rename cannot reach.
4216 if n != shape.elem_count() {
4217 return Err(fuel_ir::Error::Msg(format!(
4218 "const_*_like: data length {n} does not match shape element count {}",
4219 shape.elem_count(),
4220 )));
4221 }
4222 let device = pick_device_from_graph(&self.graph);
4223 // GAP-003: the sibling panic, converted with it -- the same pair
4224 // `from_host_buffer_on` had, and the second anchor the row named.
4225 let backend_storage = device
4226 .storage_from_host_buffer_owned_dyn(buf)
4227 .map_err(|e| {
4228 fuel_ir::Error::Msg(format!(
4229 "NodeHandle::const_like: device.storage_from_host_buffer_owned_dyn failed: {e}"
4230 ))
4231 })?;
4232 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
4233 let id = {
4234 let mut g = self.graph.write().unwrap();
4235 let id = g.push(Node {
4236 op: Op::Const,
4237 inputs: vec![],
4238 shape,
4239 dtype,
4240 });
4241 g.set_storage(id, storage_arc);
4242 id
4243 };
4244 Ok(Self {
4245 graph: self.graph.clone(),
4246 id,
4247 })
4248 }
4249
4250 /// Push a `Const` node on the same graph as `self` **without**
4251 /// populating the graph's storage_map. The caller is responsible
4252 /// for binding the storage Arc into the realize call's initial
4253 /// StorageCache, typically via
4254 /// [`InferenceContext::insert`](../fuel_core/inference_context/struct.InferenceContext.html#method.insert).
4255 ///
4256 /// Used by the Phase 7.6 step 9c E.3.3 forward path to bind
4257 /// pre-allocated KV-cache storage Arcs (held as the new
4258 /// `Arc<RwLock<fuel_memory::Storage>>` type, not the legacy
4259 /// `fuel_backend_contract::Storage` that `const_like_from_storage` takes)
4260 /// into a per-step graph without re-uploading or type-converting.
4261 ///
4262 /// **Caller contract**: the same NodeId must appear in the
4263 /// `initial` StorageCache passed to the realize call. If not, the
4264 /// executor surfaces a clean error pointing at the missing slot
4265 /// — there's no implicit fallback to `graph.storage_map`.
4266 pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: DType) -> Self {
4267 let shape = shape.into();
4268 let id = {
4269 let mut g = self.graph.write().unwrap();
4270 g.push(Node {
4271 op: Op::Const,
4272 inputs: vec![],
4273 shape,
4274 dtype,
4275 })
4276 };
4277 Self {
4278 graph: self.graph.clone(),
4279 id,
4280 }
4281 }
4282
4283 /// Phase 7.5 work item G2: build a second `Const` leaf on the same
4284 /// graph as `self` whose realized bytes already live in `storage`.
4285 /// Companion to [`NodeHandle::from_storage`] for the multi-input case.
4286 pub fn const_like_from_storage(
4287 &self,
4288 storage: Arc<RwLock<Storage>>,
4289 shape: impl Into<Shape>,
4290 dtype: DType,
4291 ) -> Self {
4292 let shape = shape.into();
4293 debug_assert_eq!(
4294 storage.read().unwrap().dtype(),
4295 dtype,
4296 "NodeHandle::const_like_from_storage: declared dtype {:?} does not match storage dtype {:?}",
4297 dtype,
4298 storage.read().unwrap().dtype(),
4299 );
4300 let id = {
4301 let mut g = self.graph.write().unwrap();
4302 let id = g.push(Node {
4303 op: Op::Const,
4304 inputs: vec![],
4305 shape,
4306 dtype,
4307 });
4308 g.set_storage(id, storage);
4309 id
4310 };
4311 Self {
4312 graph: self.graph.clone(),
4313 id,
4314 }
4315 }
4316
4317 /// Append an `Add` node `self + other` to the shared graph and return
4318 /// a handle to the result. Requires matching shapes and matching
4319 /// graphs.
4320 ///
4321 /// # Panics
4322 ///
4323 /// Panics if any operand belongs to a different [`Graph`] than the one this
4324 /// builder is building into. Operand identity is graph-scoped and checked by
4325 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4326 /// deliberate and replaces the hang a cross-graph handle used to produce.
4327 /// Build every operand from one graph, or use a `Result`-returning entry
4328 /// point where one exists.
4329 pub fn add(&self, other: &NodeHandle) -> NodeHandle {
4330 self.binary_op("add", Op::Add, other, self.shape())
4331 }
4332
4333 /// Append a `Mul` node `self * other`.
4334 ///
4335 /// # Panics
4336 ///
4337 /// Panics if any operand belongs to a different [`Graph`] than the one this
4338 /// builder is building into. Operand identity is graph-scoped and checked by
4339 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4340 /// deliberate and replaces the hang a cross-graph handle used to produce.
4341 /// Build every operand from one graph, or use a `Result`-returning entry
4342 /// point where one exists.
4343 pub fn mul(&self, other: &NodeHandle) -> NodeHandle {
4344 self.binary_op("mul", Op::Mul, other, self.shape())
4345 }
4346
4347 /// Append a `MatMul` node. Both operands must have rank ≥ 2. The
4348 /// last two dims are the matrix dims; leading dims are batch dims.
4349 ///
4350 /// - If both operands have the same rank, their batch dims must
4351 /// match exactly.
4352 /// - If one operand is rank-2 and the other is higher rank, the
4353 /// rank-2 operand is auto-broadcast to match the higher-rank
4354 /// operand's batch prefix. This is the common "linear layer
4355 /// across a batch" pattern (`[batch, seq, d_model] @ [d_model, d_out]`).
4356 /// - Any other rank combination panics; users must reshape first.
4357 ///
4358 /// Shape examples:
4359 /// - `[m, k] @ [k, n]` → `[m, n]`
4360 /// - `[batch, m, k] @ [batch, k, n]` → `[batch, m, n]`
4361 /// - `[batch, seq, k] @ [k, n]` → `[batch, seq, n]` (rhs auto-broadcast)
4362 /// - `[k, n]` @ `[batch, n, m]` → `[batch, k, m]` (lhs auto-broadcast)
4363 ///
4364 /// # Panics
4365 ///
4366 /// Panics if any operand belongs to a different [`Graph`] than the one this
4367 /// builder is building into. Operand identity is graph-scoped and checked by
4368 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4369 /// deliberate and replaces the hang a cross-graph handle used to produce.
4370 /// Build every operand from one graph, or use a `Result`-returning entry
4371 /// point where one exists.
4372 pub fn matmul(&self, other: &NodeHandle) -> NodeHandle {
4373 assert!(
4374 Arc::ptr_eq(&self.graph, &other.graph),
4375 "matmul: tensors must live on the same graph — lhs is on graph #{}, rhs on graph \
4376 #{}; each `from_*` constructor mints a NEW graph, so build `other` on this \
4377 tensor's graph with `from_f32_on(self.graph(), ..)` or `const_*_like`",
4378 self.graph_id(),
4379 other.graph_id(),
4380 );
4381 // Mixed-precision matmul: activations stay in their native
4382 // dtype while weights can live as a lower-precision type on
4383 // device. Currently supported: (F32 × BF16) and (F32 × F16) →
4384 // F32 for half-precision LLM serving (ROADMAP row 34). Other
4385 // heterogeneous combinations are rejected.
4386 let dtypes_ok = self.dtype() == other.dtype()
4387 || (self.dtype() == DType::F32 && matches!(other.dtype(), DType::BF16 | DType::F16));
4388 assert!(
4389 dtypes_ok,
4390 "matmul: unsupported dtype combination: lhs={:?}, rhs={:?}",
4391 self.dtype(),
4392 other.dtype(),
4393 );
4394 let l = self.shape();
4395 let r = other.shape();
4396 let ld = l.dims();
4397 let rd = r.dims();
4398 assert!(
4399 ld.len() >= 2 && rd.len() >= 2,
4400 "matmul: both operands must be rank ≥ 2, got {ld:?} and {rd:?}",
4401 );
4402
4403 // Auto-broadcast the rank-2 operand against the other's batch
4404 // prefix. If ranks already match, this is a no-op.
4405 let (lhs, rhs) = if ld.len() == rd.len() {
4406 (self.clone(), other.clone())
4407 } else if ld.len() == 2 && rd.len() > 2 {
4408 let mut bc_shape: Vec<usize> = rd[..rd.len() - 2].to_vec();
4409 bc_shape.push(ld[0]);
4410 bc_shape.push(ld[1]);
4411 (
4412 self.broadcast_to(Shape::from_dims(&bc_shape)),
4413 other.clone(),
4414 )
4415 } else if rd.len() == 2 && ld.len() > 2 {
4416 let mut bc_shape: Vec<usize> = ld[..ld.len() - 2].to_vec();
4417 bc_shape.push(rd[0]);
4418 bc_shape.push(rd[1]);
4419 (
4420 self.clone(),
4421 other.broadcast_to(Shape::from_dims(&bc_shape)),
4422 )
4423 } else {
4424 panic!(
4425 "matmul: unsupported rank combination {} vs {} — only same-rank or (rank-2 × higher-rank) is supported; reshape first",
4426 ld.len(),
4427 rd.len(),
4428 );
4429 };
4430
4431 // Now both operands have the same rank. Validate batch prefix
4432 // and build the output node.
4433 let lhs_shape = lhs.shape();
4434 let rhs_shape = rhs.shape();
4435 let l = lhs_shape.dims();
4436 let r = rhs_shape.dims();
4437 let rank = l.len();
4438 let batch_rank = rank - 2;
4439 for i in 0..batch_rank {
4440 // GQA-style matmul: A may have more batch heads than B
4441 // (e.g. Q[1,32,1,64] @ K^T[1,4,64,S]). The n_rep factor
4442 // is inferred by the backend at dispatch time; at the
4443 // graph level we just validate divisibility.
4444 let (la, ra) = (l[i], r[i]);
4445 let ok = la == ra || (la > ra && ra > 0 && la % ra == 0);
4446 assert!(
4447 ok,
4448 "matmul: batch dim mismatch at axis {i}: {la} vs {ra} (not equal and not a GQA-divisible pair)",
4449 );
4450 }
4451 let k = l[rank - 1];
4452 let k2 = r[rank - 2];
4453 assert_eq!(k, k2, "matmul: inner dim mismatch (lhs k={k}, rhs k={k2})",);
4454 // Output shape + dtype now flow from primitive_shape (the single source
4455 // of truth); the same-rank operands + validated batch prefix / inner
4456 // dim above guarantee it infers cleanly. (The GQA batch-prefix carry
4457 // uses lhs's batch dims, matching primitive_shape's `l[..rank-2]`.)
4458 let (shape, dtype) = crate::shape::primitive_shape(
4459 &Op::MatMul,
4460 &[lhs_shape.clone(), rhs_shape.clone()],
4461 &[lhs.dtype(), rhs.dtype()],
4462 )
4463 .expect("matmul: operands validated (same-rank, inner dim) before primitive_shape");
4464 let id = self.graph.write().unwrap().push(Node {
4465 op: Op::MatMul,
4466 inputs: vec![lhs.id, rhs.id],
4467 shape,
4468 dtype,
4469 });
4470 Self {
4471 graph: self.graph.clone(),
4472 id,
4473 }
4474 }
4475
4476 /// Data-determined-M matmul: like [`Self::matmul`], but the LHS row
4477 /// count `M` is a **runtime** value `row_count` rather than the static
4478 /// `lhs.shape[-2]`. The LHS and output are **capacity buffers** of
4479 /// `lhs.shape[-2]` rows; only `row_count` rows are computed, the rest
4480 /// left zeroed. This is the sparse-MoE expert-FFN primitive — gather an
4481 /// expert's `count_e` routed tokens into a capacity buffer, then
4482 /// compute exactly `count_e` FFN rows (the FLOP saving). `row_count`
4483 /// resolves at compile if input-determined, else at execute from the
4484 /// producer-bound `SymEnv` (e.g. `Op::NonZeroIndices`'s count). The
4485 /// output shape is the capacity shape `[..., lhs.shape[-2], n]`.
4486 ///
4487 /// # Panics
4488 ///
4489 /// Panics if any operand belongs to a different [`Graph`] than the one this
4490 /// builder is building into. Operand identity is graph-scoped and checked by
4491 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4492 /// deliberate and replaces the hang a cross-graph handle used to produce.
4493 /// Build every operand from one graph, or use a `Result`-returning entry
4494 /// point where one exists.
4495 pub fn matmul_dyn_m(&self, other: &NodeHandle, row_count: DynScalar) -> NodeHandle {
4496 self.assert_same_graph(other, "matmul_dyn_m", "other");
4497 // Only the F32 CPU capacity kernel honors a data-determined row
4498 // count today; other dtypes/backends compute all capacity rows.
4499 // Guard here so a dynamic-M matmul can never be built where it
4500 // would silently over-compute.
4501 assert_eq!(
4502 self.dtype(),
4503 DType::F32,
4504 "matmul_dyn_m: data-determined-M is F32-only today (got lhs {:?})",
4505 self.dtype(),
4506 );
4507 let out = self.matmul(other);
4508 self.graph
4509 .write()
4510 .unwrap()
4511 .set_matmul_row_count(out.id, row_count);
4512 out
4513 }
4514
4515 /// Append an [`Op::Fused`] node carrying
4516 /// [`crate::registry::FusedOpParams::QMatMul`] that multiplies `self` (F32
4517 /// activations, shape `[..., M, K]`) with a Q-type quantized
4518 /// weight matrix of logical shape `[N, K]` stored as a raw byte
4519 /// stream (passed in as a U32 tensor; length = n_bytes / 4).
4520 ///
4521 /// Output shape: `[..., M, N]` F32. The backend dequantizes the
4522 /// weight blocks on the fly inside the matmul kernel, so the
4523 /// quantized blocks stay resident at their compressed size.
4524 ///
4525 /// # Panics
4526 ///
4527 /// Panics if any operand belongs to a different [`Graph`] than the one this
4528 /// builder is building into. Operand identity is graph-scoped and checked by
4529 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4530 /// deliberate and replaces the hang a cross-graph handle used to produce.
4531 /// Build every operand from one graph, or use a `Result`-returning entry
4532 /// point where one exists.
4533 pub fn qmatmul(
4534 &self,
4535 weight_bytes: &NodeHandle,
4536 quant_type: QuantType,
4537 k: usize,
4538 n: usize,
4539 ) -> NodeHandle {
4540 assert!(
4541 Arc::ptr_eq(&self.graph, &weight_bytes.graph),
4542 "qmatmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
4543 );
4544 assert_eq!(
4545 self.dtype(),
4546 DType::F32,
4547 "qmatmul: activations must be F32, got {:?}",
4548 self.dtype(),
4549 );
4550 assert_eq!(
4551 weight_bytes.dtype(),
4552 DType::U32,
4553 "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
4554 weight_bytes.dtype(),
4555 );
4556 let a_dims = self.shape();
4557 let a_dims = a_dims.dims();
4558 assert!(
4559 a_dims.len() >= 2,
4560 "qmatmul: activations must be rank ≥ 2, got {a_dims:?}",
4561 );
4562 assert_eq!(
4563 a_dims[a_dims.len() - 1],
4564 k,
4565 "qmatmul: last dim of activations ({}) must equal k ({k})",
4566 a_dims[a_dims.len() - 1],
4567 );
4568 assert_eq!(
4569 k % quant_type.elements_per_block(),
4570 0,
4571 "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({})",
4572 quant_type.elements_per_block(),
4573 );
4574 // Validate the weight byte count matches [N, K/block_size] blocks.
4575 let expected_bytes =
4576 n * (k / quant_type.elements_per_block()) * quant_type.bytes_per_block();
4577 let expected_u32_elems = expected_bytes / 4;
4578 assert_eq!(
4579 weight_bytes.shape().elem_count(),
4580 expected_u32_elems,
4581 "qmatmul: weight_bytes has {} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
4582 weight_bytes.shape().elem_count(),
4583 );
4584 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
4585 out_dims.push(n);
4586 // Phase 7.6 step 4 (final): emits Op::Fused(QMATMUL, _) per
4587 // the registry split.
4588 let id = self.graph.write().unwrap().push(Node {
4589 op: Op::Fused(
4590 crate::registry::FusedOps::QMATMUL,
4591 crate::registry::FusedOpParams::QMatMul { quant_type, k, n },
4592 ),
4593 inputs: vec![self.id, weight_bytes.id],
4594 shape: Shape::from_dims(&out_dims),
4595 dtype: DType::F32,
4596 });
4597 Self {
4598 graph: self.graph.clone(),
4599 id,
4600 }
4601 }
4602
4603 /// Append an [`Op::Fused`] node carrying
4604 /// [`crate::registry::FusedOpParams::Conv2D`]. `self` must be `[N, Cin, H, W]`
4605 /// (rank 4); `weight` must be `[Cout, Cin/groups, Kh, Kw]` (rank
4606 /// 4) and live on the same graph. `bias` is optional — when
4607 /// present it must be rank 1 with length `Cout`. Returns a rank-4
4608 /// tensor of shape `[N, Cout, Hout, Wout]`.
4609 ///
4610 /// Panics if the input ranks don't match, the channel counts are
4611 /// inconsistent with `groups`, or the output spatial dims would
4612 /// be non-positive.
4613 ///
4614 /// # Panics
4615 ///
4616 /// Panics if any operand belongs to a different [`Graph`] than the one this
4617 /// builder is building into. Operand identity is graph-scoped and checked by
4618 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4619 /// deliberate and replaces the hang a cross-graph handle used to produce.
4620 /// Build every operand from one graph, or use a `Result`-returning entry
4621 /// point where one exists.
4622 pub fn conv2d(
4623 &self,
4624 weight: &NodeHandle,
4625 bias: Option<&NodeHandle>,
4626 stride: (usize, usize),
4627 padding: (usize, usize),
4628 groups: usize,
4629 ) -> NodeHandle {
4630 assert!(
4631 Arc::ptr_eq(&self.graph, &weight.graph),
4632 "conv2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4633 );
4634 if let Some(b) = bias {
4635 assert!(
4636 Arc::ptr_eq(&self.graph, &b.graph),
4637 "conv2d: bias must live on the same graph; use `const_*_like` to build on an existing graph",
4638 );
4639 }
4640 assert!(groups >= 1, "conv2d: groups must be ≥ 1, got {groups}");
4641 let x_dims = self.shape();
4642 let x_dims = x_dims.dims();
4643 let w_dims = weight.shape();
4644 let w_dims = w_dims.dims();
4645 assert_eq!(
4646 x_dims.len(),
4647 4,
4648 "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4649 );
4650 assert_eq!(
4651 w_dims.len(),
4652 4,
4653 "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
4654 );
4655 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4656 let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4657 assert_eq!(
4658 cin,
4659 cin_per_g * groups,
4660 "conv2d: x has {cin} in-channels but weight expects {} ({}·{groups})",
4661 cin_per_g * groups,
4662 cin_per_g,
4663 );
4664 assert_eq!(
4665 cout % groups,
4666 0,
4667 "conv2d: Cout={cout} must be divisible by groups={groups}",
4668 );
4669 if let Some(b) = bias {
4670 let b_dims = b.shape();
4671 let b_dims = b_dims.dims();
4672 assert_eq!(
4673 b_dims,
4674 &[cout],
4675 "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
4676 );
4677 }
4678 // Hout = (H + 2·pad.0 − Kh) / stride.0 + 1
4679 let (stride_h, stride_w) = stride;
4680 let (pad_h, pad_w) = padding;
4681 assert!(stride_h >= 1 && stride_w >= 1, "conv2d: stride must be ≥ 1");
4682 let h_padded = h_in + 2 * pad_h;
4683 let w_padded = w_in + 2 * pad_w;
4684 assert!(
4685 h_padded >= kh && w_padded >= kw,
4686 "conv2d: padded input ({h_padded}×{w_padded}) smaller than kernel ({kh}×{kw})",
4687 );
4688 let h_out = (h_padded - kh) / stride_h + 1;
4689 let w_out = (w_padded - kw) / stride_w + 1;
4690 let dtype = self.dtype();
4691 let mut inputs = vec![self.id, weight.id];
4692 if let Some(b) = bias {
4693 inputs.push(b.id);
4694 }
4695 // Phase 7.6 step 4 (continued): emit
4696 // `Op::Fused(FusedOps::CONV2D, FusedOpParams::Conv2D { … })`
4697 // through the registry-extended arm. The legacy
4698 // `Op::Conv2D { … }` variant remains in the enum during
4699 // migration (Conv2D's backward still constructs inner
4700 // `Op::Fused(CONV2D, _)` nodes; the legacy variant is reached
4701 // only by direct tests until step 5 drops it).
4702 let id = self.graph.write().unwrap().push(Node {
4703 op: Op::Fused(
4704 crate::registry::FusedOps::CONV2D,
4705 crate::registry::FusedOpParams::Conv2D {
4706 stride,
4707 padding,
4708 groups,
4709 },
4710 ),
4711 inputs,
4712 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4713 dtype,
4714 });
4715 Self {
4716 graph: self.graph.clone(),
4717 id,
4718 }
4719 }
4720
4721 /// Append an [`Op::Fused`] node carrying
4722 /// [`crate::registry::FusedOpParams::PagedAttn`]. `self` is the Q tensor of shape
4723 /// `[B, Hq, Sq, D]`; `k_cache` and `v_cache` are the paged caches
4724 /// shaped `[num_blocks, block_size, Hkv, D]`; `block_table` is
4725 /// `[B, max_num_blocks_per_seq]` (u32) mapping logical → physical
4726 /// blocks; `context_lens` is `[B]` (u32) of per-sequence lengths;
4727 /// `alibi_slopes` is the optional `[Hq]` per-head bias.
4728 ///
4729 /// Returns a tensor with `q`'s shape `[B, Hq, Sq, D]`.
4730 ///
4731 /// # Panics
4732 ///
4733 /// Panics if any operand belongs to a different [`Graph`] than the one this
4734 /// builder is building into. Operand identity is graph-scoped and checked by
4735 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4736 /// deliberate and replaces the hang a cross-graph handle used to produce.
4737 /// Build every operand from one graph, or use a `Result`-returning entry
4738 /// point where one exists.
4739 pub fn paged_attn(
4740 &self,
4741 k_cache: &NodeHandle,
4742 v_cache: &NodeHandle,
4743 block_table: &NodeHandle,
4744 context_lens: &NodeHandle,
4745 alibi_slopes: Option<&NodeHandle>,
4746 softmax_scale: f32,
4747 block_size: usize,
4748 softcap: Option<f32>,
4749 ) -> NodeHandle {
4750 let g = &self.graph;
4751 assert!(
4752 Arc::ptr_eq(g, &k_cache.graph),
4753 "paged_attn: q + k_cache must share graph"
4754 );
4755 assert!(
4756 Arc::ptr_eq(g, &v_cache.graph),
4757 "paged_attn: q + v_cache must share graph"
4758 );
4759 assert!(
4760 Arc::ptr_eq(g, &block_table.graph),
4761 "paged_attn: q + block_table must share graph"
4762 );
4763 assert!(
4764 Arc::ptr_eq(g, &context_lens.graph),
4765 "paged_attn: q + context_lens must share graph"
4766 );
4767 if let Some(a) = alibi_slopes {
4768 assert!(
4769 Arc::ptr_eq(g, &a.graph),
4770 "paged_attn: alibi_slopes must share graph"
4771 );
4772 }
4773 assert!(block_size >= 1, "paged_attn: block_size must be ≥ 1");
4774
4775 let q_dims = self.shape();
4776 let q_dims = q_dims.dims();
4777 let kc_dims = k_cache.shape();
4778 let kc_dims = kc_dims.dims();
4779 let vc_dims = v_cache.shape();
4780 let vc_dims = vc_dims.dims();
4781 let bt_dims = block_table.shape();
4782 let bt_dims = bt_dims.dims();
4783 let cl_dims = context_lens.shape();
4784 let cl_dims = cl_dims.dims();
4785 assert_eq!(
4786 q_dims.len(),
4787 4,
4788 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
4789 );
4790 assert_eq!(
4791 kc_dims.len(),
4792 4,
4793 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}"
4794 );
4795 assert_eq!(
4796 vc_dims.len(),
4797 4,
4798 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}"
4799 );
4800 assert_eq!(
4801 bt_dims.len(),
4802 2,
4803 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}"
4804 );
4805 assert_eq!(
4806 cl_dims.len(),
4807 1,
4808 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}"
4809 );
4810 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
4811 assert_eq!(
4812 kc_dims[1], block_size,
4813 "paged_attn: k_cache block dim {} != block_size {block_size}",
4814 kc_dims[1]
4815 );
4816 assert_eq!(
4817 vc_dims[1], block_size,
4818 "paged_attn: v_cache block dim {} != block_size {block_size}",
4819 vc_dims[1]
4820 );
4821 let hkv = kc_dims[2];
4822 assert_eq!(
4823 vc_dims[2], hkv,
4824 "paged_attn: Hkv mismatch k_cache vs v_cache"
4825 );
4826 assert_eq!(kc_dims[3], d, "paged_attn: D mismatch q vs k_cache");
4827 assert_eq!(vc_dims[3], d, "paged_attn: D mismatch q vs v_cache");
4828 assert_eq!(
4829 hq % hkv,
4830 0,
4831 "paged_attn: Hq={hq} must be a multiple of Hkv={hkv}"
4832 );
4833 assert_eq!(
4834 bt_dims[0], b,
4835 "paged_attn: block_table batch dim {} != B={b}",
4836 bt_dims[0]
4837 );
4838 assert_eq!(
4839 cl_dims[0], b,
4840 "paged_attn: context_lens len {} != B={b}",
4841 cl_dims[0]
4842 );
4843 assert_eq!(
4844 block_table.dtype(),
4845 crate::DType::U32,
4846 "paged_attn: block_table must be U32"
4847 );
4848 assert_eq!(
4849 context_lens.dtype(),
4850 crate::DType::U32,
4851 "paged_attn: context_lens must be U32"
4852 );
4853 if let Some(a) = alibi_slopes {
4854 let ad = a.shape();
4855 let ad = ad.dims();
4856 assert_eq!(
4857 ad,
4858 &[hq],
4859 "paged_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
4860 );
4861 }
4862
4863 let dtype = self.dtype();
4864 let mut inputs = vec![
4865 self.id,
4866 k_cache.id,
4867 v_cache.id,
4868 block_table.id,
4869 context_lens.id,
4870 ];
4871 if let Some(a) = alibi_slopes {
4872 inputs.push(a.id);
4873 }
4874 // Phase 7.6 step 4 (final): emits Op::Fused(PAGED_ATTN, _).
4875 let id = self.graph.write().unwrap().push(Node {
4876 op: Op::Fused(
4877 crate::registry::FusedOps::PAGED_ATTN,
4878 crate::registry::FusedOpParams::PagedAttn {
4879 softmax_scale,
4880 block_size,
4881 softcap,
4882 },
4883 ),
4884 inputs,
4885 shape: Shape::from_dims(q_dims),
4886 dtype,
4887 });
4888 Self {
4889 graph: self.graph.clone(),
4890 id,
4891 }
4892 }
4893
4894 /// Append an [`Op::Fused`] node carrying
4895 /// [`crate::registry::FusedOpParams::ConvTranspose2D`]. `self` must be
4896 /// `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
4897 /// (note transposed channel order vs `conv2d`). Returns a rank-4
4898 /// tensor `[N, Cout, Hout, Wout]`.
4899 ///
4900 /// Panics if ranks don't match, channel counts are inconsistent
4901 /// with `groups`, or output spatial dims would be non-positive.
4902 ///
4903 /// # Panics
4904 ///
4905 /// Panics if any operand belongs to a different [`Graph`] than the one this
4906 /// builder is building into. Operand identity is graph-scoped and checked by
4907 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4908 /// deliberate and replaces the hang a cross-graph handle used to produce.
4909 /// Build every operand from one graph, or use a `Result`-returning entry
4910 /// point where one exists.
4911 pub fn conv_transpose2d(
4912 &self,
4913 weight: &NodeHandle,
4914 stride: (usize, usize),
4915 padding: (usize, usize),
4916 output_padding: (usize, usize),
4917 dilation: (usize, usize),
4918 groups: usize,
4919 ) -> NodeHandle {
4920 assert!(
4921 Arc::ptr_eq(&self.graph, &weight.graph),
4922 "conv_transpose2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4923 );
4924 assert!(
4925 groups >= 1,
4926 "conv_transpose2d: groups must be ≥ 1, got {groups}"
4927 );
4928 let x_dims = self.shape();
4929 let x_dims = x_dims.dims();
4930 let w_dims = weight.shape();
4931 let w_dims = w_dims.dims();
4932 assert_eq!(
4933 x_dims.len(),
4934 4,
4935 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4936 );
4937 assert_eq!(
4938 w_dims.len(),
4939 4,
4940 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
4941 );
4942 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4943 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4944 assert_eq!(
4945 cin, cin_w,
4946 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
4947 );
4948 assert_eq!(
4949 cin % groups,
4950 0,
4951 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
4952 );
4953 let cout = cout_per_g * groups;
4954 let (stride_h, stride_w) = stride;
4955 let (pad_h, pad_w) = padding;
4956 let (out_pad_h, out_pad_w) = output_padding;
4957 let (dil_h, dil_w) = dilation;
4958 assert!(
4959 stride_h >= 1 && stride_w >= 1,
4960 "conv_transpose2d: stride must be ≥ 1"
4961 );
4962 assert!(
4963 dil_h >= 1 && dil_w >= 1,
4964 "conv_transpose2d: dilation must be ≥ 1"
4965 );
4966 // Hout = (Hin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1
4967 let h_out = (h_in.saturating_sub(1)) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
4968 let w_out = (w_in.saturating_sub(1)) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
4969 assert!(
4970 h_out > 2 * pad_h && w_out > 2 * pad_w,
4971 "conv_transpose2d: padding ({pad_h}×{pad_w}) is larger than the produced output dims",
4972 );
4973 let h_out = h_out - 2 * pad_h;
4974 let w_out = w_out - 2 * pad_w;
4975 let dtype = self.dtype();
4976 // Phase 7.6 step 4 (final): emits Op::Fused(CONV_TRANSPOSE2D, _).
4977 let id = self.graph.write().unwrap().push(Node {
4978 op: Op::Fused(
4979 crate::registry::FusedOps::CONV_TRANSPOSE2D,
4980 crate::registry::FusedOpParams::ConvTranspose2D {
4981 stride,
4982 padding,
4983 output_padding,
4984 dilation,
4985 groups,
4986 },
4987 ),
4988 inputs: vec![self.id, weight.id],
4989 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4990 dtype,
4991 });
4992 Self {
4993 graph: self.graph.clone(),
4994 id,
4995 }
4996 }
4997
4998 /// Append a transposed 1D convolution by lifting `self` and
4999 /// `weight` into the rank-4 path and dispatching through
5000 /// [`Self::conv_transpose2d`]. `self` is `[N, Cin, Lin]`;
5001 /// `weight` is `[Cin, Cout/groups, K]` (transposed channel
5002 /// order, matches PyTorch). Returns `[N, Cout, Lout]` where
5003 /// `Lout = (Lin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1`.
5004 ///
5005 /// Used by audio codec models (DAC / EnCodec / SNAC / Mimi /
5006 /// Parler-TTS / MetaVoice / CSM) where the decoder upsamples
5007 /// quantized latents back to waveform with strided transposed
5008 /// convs.
5009 ///
5010 /// # Panics
5011 ///
5012 /// Panics if any operand belongs to a different [`Graph`] than the one this
5013 /// builder is building into. Operand identity is graph-scoped and checked by
5014 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5015 /// deliberate and replaces the hang a cross-graph handle used to produce.
5016 /// Build every operand from one graph, or use a `Result`-returning entry
5017 /// point where one exists.
5018 pub fn conv_transpose1d(
5019 &self,
5020 weight: &NodeHandle,
5021 stride: usize,
5022 padding: usize,
5023 output_padding: usize,
5024 dilation: usize,
5025 groups: usize,
5026 ) -> NodeHandle {
5027 self.assert_same_graph(weight, "conv_transpose1d", "weight");
5028 let x_dims = self.shape();
5029 let x_dims = x_dims.dims();
5030 let w_dims = weight.shape();
5031 let w_dims = w_dims.dims();
5032 assert_eq!(
5033 x_dims.len(),
5034 3,
5035 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
5036 );
5037 assert_eq!(
5038 w_dims.len(),
5039 3,
5040 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
5041 );
5042 let (n, cin, l_in) = (x_dims[0], x_dims[1], x_dims[2]);
5043 let (cin_w, cout_per_g, k) = (w_dims[0], w_dims[1], w_dims[2]);
5044 let x4 = self.reshape(Shape::from_dims(&[n, cin, 1, l_in]));
5045 let w4 = weight.reshape(Shape::from_dims(&[cin_w, cout_per_g, 1, k]));
5046 let y4 = x4.conv_transpose2d(
5047 &w4,
5048 (1, stride),
5049 (0, padding),
5050 (0, output_padding),
5051 (1, dilation),
5052 groups,
5053 );
5054 let y_dims = y4.shape();
5055 let y_dims = y_dims.dims();
5056 let (n_o, cout, _h_one, l_out) = (y_dims[0], y_dims[1], y_dims[2], y_dims[3]);
5057 y4.reshape(Shape::from_dims(&[n_o, cout, l_out]))
5058 }
5059
5060 /// Append an [`Op::Fused`] node carrying
5061 /// [`crate::registry::FusedOpParams::FlashAttn`]. `self` is `q` of shape
5062 /// `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]` with
5063 /// `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional) is
5064 /// `[Hq]`. Returns a tensor with `q`'s shape.
5065 /// Build the `flash_attn` node.
5066 ///
5067 /// # Panics
5068 ///
5069 /// Panics if any operand belongs to a different [`Graph`] than the one this
5070 /// builder is building into. Operand identity is graph-scoped and checked by
5071 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5072 /// deliberate and replaces the hang a cross-graph handle used to produce.
5073 /// Build every operand from one graph, or use a `Result`-returning entry
5074 /// point where one exists.
5075 pub fn flash_attn(
5076 &self,
5077 k: &NodeHandle,
5078 v: &NodeHandle,
5079 alibi_slopes: Option<&NodeHandle>,
5080 softmax_scale: f32,
5081 causal: bool,
5082 window_size_left: Option<usize>,
5083 window_size_right: Option<usize>,
5084 softcap: Option<f32>,
5085 ) -> NodeHandle {
5086 assert!(
5087 Arc::ptr_eq(&self.graph, &k.graph),
5088 "flash_attn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5089 );
5090 assert!(
5091 Arc::ptr_eq(&self.graph, &v.graph),
5092 "flash_attn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5093 );
5094 if let Some(a) = alibi_slopes {
5095 assert!(
5096 Arc::ptr_eq(&self.graph, &a.graph),
5097 "flash_attn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5098 );
5099 }
5100 let q_dims = self.shape();
5101 let q_dims = q_dims.dims();
5102 let k_dims = k.shape();
5103 let k_dims = k_dims.dims();
5104 let v_dims = v.shape();
5105 let v_dims = v_dims.dims();
5106 assert_eq!(
5107 q_dims.len(),
5108 4,
5109 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5110 );
5111 assert_eq!(
5112 k_dims.len(),
5113 4,
5114 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}"
5115 );
5116 assert_eq!(
5117 v_dims.len(),
5118 4,
5119 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}"
5120 );
5121 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5122 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5123 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5124 assert_eq!(b, bk, "flash_attn: B mismatch q vs k ({b} vs {bk})");
5125 assert_eq!(b, bv, "flash_attn: B mismatch q vs v");
5126 assert_eq!(hkv, hkv_v, "flash_attn: Hkv mismatch k vs v");
5127 assert_eq!(sk, sk_v, "flash_attn: Sk mismatch k vs v");
5128 assert_eq!(d, dk, "flash_attn: head_dim mismatch q vs k");
5129 assert_eq!(d, dv, "flash_attn: head_dim mismatch q vs v");
5130 assert_eq!(
5131 hq % hkv,
5132 0,
5133 "flash_attn: Hq={hq} must be a multiple of Hkv={hkv}"
5134 );
5135 if let Some(a) = alibi_slopes {
5136 let ad = a.shape();
5137 let ad = ad.dims();
5138 assert_eq!(
5139 ad,
5140 &[hq],
5141 "flash_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5142 );
5143 }
5144 let dtype = self.dtype();
5145 let mut inputs = vec![self.id, k.id, v.id];
5146 if let Some(a) = alibi_slopes {
5147 inputs.push(a.id);
5148 }
5149 // Phase 7.6 step 4 (final): emits Op::Fused(FLASH_ATTN, _).
5150 let id = self.graph.write().unwrap().push(Node {
5151 op: Op::Fused(
5152 crate::registry::FusedOps::FLASH_ATTN,
5153 crate::registry::FusedOpParams::FlashAttn {
5154 softmax_scale,
5155 causal,
5156 window_size_left,
5157 window_size_right,
5158 softcap,
5159 k_len: None,
5160 },
5161 ),
5162 inputs,
5163 shape: Shape::from_dims(&[b, hq, sq, d]),
5164 dtype,
5165 });
5166 Self {
5167 graph: self.graph.clone(),
5168 id,
5169 }
5170 }
5171
5172 /// Append an [`Op::Fused`] node carrying
5173 /// [`crate::registry::FusedOpParams::FlashAttn`] over a fixed-**capacity** K/V whose
5174 /// attended length is a **runtime** value (`k_len`) resolved through
5175 /// the per-pass [`fuel_ir::SymEnv`] at realize, decoupled
5176 /// from K's allocated shape.
5177 ///
5178 /// `self` is `q` of shape `[B, Hq, Sq, D]`; `k`/`v` are the capacity
5179 /// buffers `[B, Hkv, max_seq, D]` (GQA: `Hq % Hkv == 0`). Only the
5180 /// first `k_len.resolve(env)` rows along the K/V length axis are
5181 /// attended; the causal mask (when `causal`) is bottom-right-aligned
5182 /// at offset `k_len - Sq` — the standard FlashAttention-2 convention,
5183 /// equal to `cached_len` in autoregressive decode. Returns a tensor
5184 /// with `q`'s shape.
5185 ///
5186 /// This is the flash counterpart of [`Self::write_slice_dyn`]: the
5187 /// decode KV-cache write appends at the runtime offset and flash
5188 /// attends the runtime prefix, so the graph structure stays
5189 /// identical across tokens (Phase D symbolic extents).
5190 ///
5191 /// # Panics
5192 ///
5193 /// Panics if any operand belongs to a different [`Graph`] than the one this
5194 /// builder is building into. Operand identity is graph-scoped and checked by
5195 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5196 /// deliberate and replaces the hang a cross-graph handle used to produce.
5197 /// Build every operand from one graph, or use a `Result`-returning entry
5198 /// point where one exists.
5199 pub fn flash_attn_dyn(
5200 &self,
5201 k: &NodeHandle,
5202 v: &NodeHandle,
5203 alibi_slopes: Option<&NodeHandle>,
5204 softmax_scale: f32,
5205 causal: bool,
5206 window_size_left: Option<usize>,
5207 window_size_right: Option<usize>,
5208 softcap: Option<f32>,
5209 k_len: fuel_ir::DynScalar,
5210 ) -> NodeHandle {
5211 assert!(
5212 Arc::ptr_eq(&self.graph, &k.graph),
5213 "flash_attn_dyn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5214 );
5215 assert!(
5216 Arc::ptr_eq(&self.graph, &v.graph),
5217 "flash_attn_dyn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5218 );
5219 if let Some(a) = alibi_slopes {
5220 assert!(
5221 Arc::ptr_eq(&self.graph, &a.graph),
5222 "flash_attn_dyn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5223 );
5224 }
5225 let q_dims = self.shape();
5226 let q_dims = q_dims.dims();
5227 let k_dims = k.shape();
5228 let k_dims = k_dims.dims();
5229 let v_dims = v.shape();
5230 let v_dims = v_dims.dims();
5231 assert_eq!(
5232 q_dims.len(),
5233 4,
5234 "flash_attn_dyn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5235 );
5236 assert_eq!(
5237 k_dims.len(),
5238 4,
5239 "flash_attn_dyn: k must be rank 4 [B, Hkv, max_seq, D], got {k_dims:?}"
5240 );
5241 assert_eq!(
5242 v_dims.len(),
5243 4,
5244 "flash_attn_dyn: v must be rank 4 [B, Hkv, max_seq, D], got {v_dims:?}"
5245 );
5246 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5247 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5248 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5249 assert_eq!(b, bk, "flash_attn_dyn: B mismatch q vs k ({b} vs {bk})");
5250 assert_eq!(b, bv, "flash_attn_dyn: B mismatch q vs v");
5251 assert_eq!(hkv, hkv_v, "flash_attn_dyn: Hkv mismatch k vs v");
5252 assert_eq!(
5253 sk, sk_v,
5254 "flash_attn_dyn: capacity (max_seq) mismatch k vs v ({sk} vs {sk_v})"
5255 );
5256 assert_eq!(d, dk, "flash_attn_dyn: head_dim mismatch q vs k");
5257 assert_eq!(d, dv, "flash_attn_dyn: head_dim mismatch q vs v");
5258 assert_eq!(
5259 hq % hkv,
5260 0,
5261 "flash_attn_dyn: Hq={hq} must be a multiple of Hkv={hkv}"
5262 );
5263 // A build-time constant k_len must fit the capacity and cover Sq.
5264 if let fuel_ir::DynScalar::Concrete(kl) = k_len {
5265 assert!(
5266 kl <= sk,
5267 "flash_attn_dyn: k_len ({kl}) exceeds K capacity ({sk})"
5268 );
5269 assert!(
5270 kl >= sq,
5271 "flash_attn_dyn: k_len ({kl}) must be >= Sq ({sq}) for a valid causal prefix"
5272 );
5273 }
5274 if let Some(a) = alibi_slopes {
5275 let ad = a.shape();
5276 let ad = ad.dims();
5277 assert_eq!(
5278 ad,
5279 &[hq],
5280 "flash_attn_dyn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5281 );
5282 }
5283 let dtype = self.dtype();
5284 let mut inputs = vec![self.id, k.id, v.id];
5285 if let Some(a) = alibi_slopes {
5286 inputs.push(a.id);
5287 }
5288 let id = self.graph.write().unwrap().push(Node {
5289 op: Op::Fused(
5290 crate::registry::FusedOps::FLASH_ATTN,
5291 crate::registry::FusedOpParams::FlashAttn {
5292 softmax_scale,
5293 causal,
5294 window_size_left,
5295 window_size_right,
5296 softcap,
5297 k_len: Some(k_len),
5298 },
5299 ),
5300 inputs,
5301 shape: Shape::from_dims(&[b, hq, sq, d]),
5302 dtype,
5303 });
5304 Self {
5305 graph: self.graph.clone(),
5306 id,
5307 }
5308 }
5309
5310 /// Append a `Relu` node `max(0, self)`.
5311 pub fn relu(&self) -> NodeHandle {
5312 self.unary_op(Op::Relu)
5313 }
5314
5315 /// Append a `Sqr` node `self * self`.
5316 pub fn sqr(&self) -> NodeHandle {
5317 self.unary_op(Op::Sqr)
5318 }
5319
5320 /// Append an `Exp` node `e^self`.
5321 pub fn exp(&self) -> NodeHandle {
5322 self.unary_op(Op::Exp)
5323 }
5324
5325 /// Append a `Permute` node rearranging the axes according to `axes`.
5326 /// `out.shape[i] = self.shape[axes[i]]`. The axes vector must be a
5327 /// permutation of `0..rank`. For a rank-3 input with `axes = [2, 0, 1]`,
5328 /// the shape transform is `[a, b, c] → [c, a, b]`.
5329 pub fn permute(&self, axes: &[usize]) -> NodeHandle {
5330 let in_shape = self.shape();
5331 let in_dims = in_shape.dims();
5332 let rank = in_dims.len();
5333 assert_eq!(
5334 axes.len(),
5335 rank,
5336 "permute: axes length {} must equal tensor rank {}",
5337 axes.len(),
5338 rank,
5339 );
5340 // Validate that axes is a permutation of 0..rank.
5341 let mut seen = vec![false; rank];
5342 for &ax in axes {
5343 assert!(
5344 ax < rank,
5345 "permute: axis {ax} out of bounds for rank {rank}"
5346 );
5347 assert!(!seen[ax], "permute: duplicate axis {ax} in axes");
5348 seen[ax] = true;
5349 }
5350 let out_dims: Vec<usize> = axes.iter().map(|&ax| in_dims[ax]).collect();
5351 let dtype = self.dtype();
5352 let id = self.graph.write().unwrap().push(Node {
5353 op: Op::Permute(axes.to_vec()),
5354 inputs: vec![self.id],
5355 shape: Shape::from_dims(&out_dims),
5356 dtype,
5357 });
5358 Self {
5359 graph: self.graph.clone(),
5360 id,
5361 }
5362 }
5363
5364 /// Result-returning sibling of [`Self::permute`]. Surfaces bad
5365 /// axes (wrong length, out-of-bounds entry, or duplicate) as a
5366 /// typed error rather than panicking.
5367 pub fn try_permute(&self, axes: &[usize]) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5368 let in_shape = self.shape();
5369 let rank = in_shape.dims().len();
5370 if axes.len() != rank {
5371 return Err(fuel_ir::Error::Msg(format!(
5372 "permute: axes length {} must equal tensor rank {}",
5373 axes.len(),
5374 rank,
5375 ))
5376 .bt());
5377 }
5378 let mut seen = vec![false; rank];
5379 for &ax in axes {
5380 if ax >= rank {
5381 return Err(fuel_ir::Error::Msg(format!(
5382 "permute: axis {ax} out of bounds for rank {rank}",
5383 ))
5384 .bt());
5385 }
5386 if seen[ax] {
5387 return Err(
5388 fuel_ir::Error::Msg(format!("permute: duplicate axis {ax} in axes",)).bt(),
5389 );
5390 }
5391 seen[ax] = true;
5392 }
5393 let op = Op::Permute(axes.to_vec());
5394 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5395 let id = self.graph.write().unwrap().push(Node {
5396 op,
5397 inputs: vec![self.id],
5398 shape,
5399 dtype,
5400 });
5401 Ok(Self {
5402 graph: self.graph.clone(),
5403 id,
5404 })
5405 }
5406
5407 /// Append a `Transpose` node that swaps the last two dimensions of a
5408 /// tensor of rank ≥ 2. Leading dims are unchanged. For a rank-2
5409 /// tensor this is the ordinary matrix transpose; for higher ranks,
5410 /// every batch slice is transposed independently.
5411 pub fn transpose(&self) -> NodeHandle {
5412 let in_shape = self.shape();
5413 assert!(
5414 in_shape.dims().len() >= 2,
5415 "transpose: input must be rank ≥ 2, got shape {:?}",
5416 in_shape.dims(),
5417 );
5418 let op = Op::Transpose;
5419 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
5420 .expect("transpose: rank validated above");
5421 let id = self.graph.write().unwrap().push(Node {
5422 op,
5423 inputs: vec![self.id],
5424 shape,
5425 dtype,
5426 });
5427 Self {
5428 graph: self.graph.clone(),
5429 id,
5430 }
5431 }
5432
5433 /// Result-returning sibling of [`Self::transpose`]. Surfaces
5434 /// rank < 2 as a typed error rather than panicking.
5435 pub fn try_transpose(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5436 let in_shape = self.shape();
5437 if in_shape.dims().len() < 2 {
5438 return Err(fuel_ir::Error::Msg(format!(
5439 "transpose: input must be rank ≥ 2, got shape {:?}",
5440 in_shape.dims(),
5441 ))
5442 .bt());
5443 }
5444 let op = Op::Transpose;
5445 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5446 let id = self.graph.write().unwrap().push(Node {
5447 op,
5448 inputs: vec![self.id],
5449 shape,
5450 dtype,
5451 });
5452 Ok(Self {
5453 graph: self.graph.clone(),
5454 id,
5455 })
5456 }
5457
5458 // --- additional element-wise binary ops ---
5459
5460 /// Append a `Sub` node `self - other`. Requires matching shapes and dtypes.
5461 ///
5462 /// # Panics
5463 ///
5464 /// Panics if any operand belongs to a different [`Graph`] than the one this
5465 /// builder is building into. Operand identity is graph-scoped and checked by
5466 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5467 /// deliberate and replaces the hang a cross-graph handle used to produce.
5468 /// Build every operand from one graph, or use a `Result`-returning entry
5469 /// point where one exists.
5470 pub fn sub(&self, other: &NodeHandle) -> NodeHandle {
5471 self.binary_op("sub", Op::Sub, other, self.shape())
5472 }
5473
5474 /// Append a `Div` node `self / other`. Requires matching shapes and dtypes.
5475 ///
5476 /// # Panics
5477 ///
5478 /// Panics if any operand belongs to a different [`Graph`] than the one this
5479 /// builder is building into. Operand identity is graph-scoped and checked by
5480 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5481 /// deliberate and replaces the hang a cross-graph handle used to produce.
5482 /// Build every operand from one graph, or use a `Result`-returning entry
5483 /// point where one exists.
5484 pub fn div(&self, other: &NodeHandle) -> NodeHandle {
5485 self.binary_op("div", Op::Div, other, self.shape())
5486 }
5487
5488 // --- additional element-wise unary ops ---
5489
5490 /// Append a `Neg` node `-self`.
5491 pub fn neg(&self) -> NodeHandle {
5492 self.unary_op(Op::Neg)
5493 }
5494
5495 /// Append a `Sqrt` node `sqrt(self)`.
5496 pub fn sqrt(&self) -> NodeHandle {
5497 self.unary_op(Op::Sqrt)
5498 }
5499
5500 /// Append a `Log` node `ln(self)`.
5501 pub fn log(&self) -> NodeHandle {
5502 self.unary_op(Op::Log)
5503 }
5504
5505 /// Append a `Sin` node.
5506 pub fn sin(&self) -> NodeHandle {
5507 self.unary_op(Op::Sin)
5508 }
5509
5510 /// Append a `Cos` node.
5511 pub fn cos(&self) -> NodeHandle {
5512 self.unary_op(Op::Cos)
5513 }
5514
5515 /// Append a `Tanh` node.
5516 pub fn tanh(&self) -> NodeHandle {
5517 self.unary_op(Op::Tanh)
5518 }
5519
5520 /// Append a `Sigmoid` node.
5521 pub fn sigmoid(&self) -> NodeHandle {
5522 self.unary_op(Op::Sigmoid)
5523 }
5524
5525 /// Append a `Silu` node (SiLU/Swish activation: `x · sigmoid(x)`).
5526 pub fn silu(&self) -> NodeHandle {
5527 self.unary_op(Op::Silu)
5528 }
5529
5530 /// Append a `GeluTanh` node (tanh-approximation GELU).
5531 pub fn gelu_tanh(&self) -> NodeHandle {
5532 self.unary_op(Op::GeluTanh)
5533 }
5534
5535 /// Append a `Step` node (Heaviside step: `1` where `x > 0`, else `0`).
5536 pub fn step(&self) -> NodeHandle {
5537 self.unary_op(Op::Step)
5538 }
5539
5540 /// Append a `Recip` node (`1 / self`).
5541 pub fn recip(&self) -> NodeHandle {
5542 self.unary_op(Op::Recip)
5543 }
5544
5545 /// Append an `Abs` node (`|self|`).
5546 pub fn abs(&self) -> NodeHandle {
5547 self.unary_op(Op::Abs)
5548 }
5549
5550 // ---- In-place unary builders (Phase 2 of the in-place ops
5551 // infrastructure) ----
5552 //
5553 // Each emits an `Op::*Inplace` node whose input is `self`. The
5554 // returned `NodeHandle` shares the underlying graph and is the new
5555 // root; subsequent ops should use the returned handle to make the
5556 // mutation-after-read ordering observable to `derive_ordering`.
5557 //
5558 // Phase 4 (the mutation-safety pass) is what makes these safe to
5559 // call on tape-tracked tensors. Until Phase 4 lands, calling these
5560 // on a tensor that's been saved for backward will panic at
5561 // `NodeHandle::backward` time (clear error, no silent gradient
5562 // corruption).
5563
5564 /// Append a `ReluInplace` node — mutates `self`'s storage with
5565 /// `max(0, self)`. See `NodeHandle::relu` for the functional variant.
5566 pub fn relu_inplace(&self) -> NodeHandle {
5567 self.unary_op(Op::ReluInplace)
5568 }
5569
5570 /// Append a `SiluInplace` node — mutates `self`'s storage with
5571 /// `self * sigmoid(self)`. See `NodeHandle::silu` for the functional
5572 /// variant.
5573 pub fn silu_inplace(&self) -> NodeHandle {
5574 self.unary_op(Op::SiluInplace)
5575 }
5576
5577 /// Append a `GeluTanhInplace` node — mutates `self`'s storage with
5578 /// the tanh-approximation GELU. See `NodeHandle::gelu_tanh` for the
5579 /// functional variant.
5580 pub fn gelu_tanh_inplace(&self) -> NodeHandle {
5581 self.unary_op(Op::GeluTanhInplace)
5582 }
5583
5584 /// Append a `TanhInplace` node — mutates `self`'s storage with
5585 /// `tanh(self)`. See `NodeHandle::tanh` for the functional variant.
5586 pub fn tanh_inplace(&self) -> NodeHandle {
5587 self.unary_op(Op::TanhInplace)
5588 }
5589
5590 /// Append a `SigmoidInplace` node — mutates `self`'s storage
5591 /// with `sigmoid(self)`. See `NodeHandle::sigmoid` for the functional
5592 /// variant.
5593 pub fn sigmoid_inplace(&self) -> NodeHandle {
5594 self.unary_op(Op::SigmoidInplace)
5595 }
5596
5597 /// Append a `NegInplace` node — mutates `self`'s storage with
5598 /// `-self`. See `NodeHandle::neg` for the functional variant.
5599 pub fn neg_inplace(&self) -> NodeHandle {
5600 self.unary_op(Op::NegInplace)
5601 }
5602
5603 /// Append an `AbsInplace` node — mutates `self`'s storage with
5604 /// `|self|`. See `NodeHandle::abs` for the functional variant.
5605 pub fn abs_inplace(&self) -> NodeHandle {
5606 self.unary_op(Op::AbsInplace)
5607 }
5608
5609 /// Append a `SqrInplace` node — mutates `self`'s storage with
5610 /// `self²`. See `NodeHandle::sqr` for the functional variant.
5611 pub fn sqr_inplace(&self) -> NodeHandle {
5612 self.unary_op(Op::SqrInplace)
5613 }
5614
5615 /// Append a `SqrtInplace` node — mutates `self`'s storage with
5616 /// `√self`. See `NodeHandle::sqrt` for the functional variant.
5617 pub fn sqrt_inplace(&self) -> NodeHandle {
5618 self.unary_op(Op::SqrtInplace)
5619 }
5620
5621 /// Append a `RsqrtInplace` node — mutates `self`'s storage with
5622 /// `1/√self`. See `NodeHandle::rsqrt` for the functional variant.
5623 pub fn rsqrt_inplace(&self) -> NodeHandle {
5624 self.unary_op(Op::RsqrtInplace)
5625 }
5626
5627 /// Append a `RecipInplace` node — mutates `self`'s storage with
5628 /// `1/self`. See `NodeHandle::recip` for the functional variant.
5629 pub fn recip_inplace(&self) -> NodeHandle {
5630 self.unary_op(Op::RecipInplace)
5631 }
5632
5633 /// Append an `ExpInplace` node — mutates `self`'s storage with
5634 /// `exp(self)`. See `NodeHandle::exp` for the functional variant.
5635 pub fn exp_inplace(&self) -> NodeHandle {
5636 self.unary_op(Op::ExpInplace)
5637 }
5638
5639 /// Append a `LogInplace` node — mutates `self`'s storage with
5640 /// `ln(self)`. See `NodeHandle::log` for the functional variant.
5641 pub fn log_inplace(&self) -> NodeHandle {
5642 self.unary_op(Op::LogInplace)
5643 }
5644
5645 /// Append a `SinInplace` node — mutates `self`'s storage with
5646 /// `sin(self)`. See `NodeHandle::sin` for the functional variant.
5647 pub fn sin_inplace(&self) -> NodeHandle {
5648 self.unary_op(Op::SinInplace)
5649 }
5650
5651 /// Append a `CosInplace` node — mutates `self`'s storage with
5652 /// `cos(self)`. See `NodeHandle::cos` for the functional variant.
5653 pub fn cos_inplace(&self) -> NodeHandle {
5654 self.unary_op(Op::CosInplace)
5655 }
5656
5657 /// Append a `SignInplace` node — mutates `self`'s storage with
5658 /// `sign(self)`. See `NodeHandle::sign` for the functional variant.
5659 pub fn sign_inplace(&self) -> NodeHandle {
5660 self.unary_op(Op::SignInplace)
5661 }
5662
5663 /// Append a `FloorInplace` node — mutates `self`'s storage with
5664 /// `⌊self⌋`. See `NodeHandle::floor` for the functional variant.
5665 pub fn floor_inplace(&self) -> NodeHandle {
5666 self.unary_op(Op::FloorInplace)
5667 }
5668
5669 /// Append a `CeilInplace` node — mutates `self`'s storage with
5670 /// `⌈self⌉`. See `NodeHandle::ceil` for the functional variant.
5671 pub fn ceil_inplace(&self) -> NodeHandle {
5672 self.unary_op(Op::CeilInplace)
5673 }
5674
5675 /// Append a `RoundInplace` node — mutates `self`'s storage with
5676 /// `round(self)`. See `NodeHandle::round` for the functional variant.
5677 pub fn round_inplace(&self) -> NodeHandle {
5678 self.unary_op(Op::RoundInplace)
5679 }
5680
5681 /// Append an `ErfInplace` node — mutates `self`'s storage with
5682 /// `erf(self)`. See `NodeHandle::erf` for the functional variant.
5683 pub fn erf_inplace(&self) -> NodeHandle {
5684 self.unary_op(Op::ErfInplace)
5685 }
5686
5687 /// Append a `GeluInplace` node — mutates `self`'s storage
5688 /// with the exact-GeLU formula. See `NodeHandle::gelu` for the
5689 /// functional variant.
5690 pub fn gelu_inplace(&self) -> NodeHandle {
5691 self.unary_op(Op::GeluInplace)
5692 }
5693
5694 /// Append a `ClampInplace { min, max }` node — mutates `self`'s
5695 /// storage with `clamp(self, min, max)`. See `NodeHandle::clamp` for
5696 /// the functional variant.
5697 pub fn clamp_inplace(&self, min: f64, max: f64) -> NodeHandle {
5698 self.unary_op(Op::ClampInplace { min, max })
5699 }
5700
5701 /// Append a `PowIInplace(exp)` node — mutates `self`'s storage
5702 /// with `self.powi(exp)`. See `NodeHandle::powi` for the functional
5703 /// variant.
5704 pub fn powi_inplace(&self, exp: i32) -> NodeHandle {
5705 self.unary_op(Op::PowIInplace(exp))
5706 }
5707
5708 /// Append an `Op::Fused(INPLACE_AFFINE, ...)` node — mutates
5709 /// `self`'s storage with `self = mul · self + add`. Single-input
5710 /// fused op (no functional `Op::Affine` exists on
5711 /// `fuel-graph::Op`; the non-inplace equivalent is `self
5712 /// .mul_scalar(mul).add_scalar(add)`). Wired to baracuda's
5713 /// `affine_inplace_*` symbol on CUDA when Phase 3 lands.
5714 pub fn affine_inplace(&self, mul: f64, add: f64) -> NodeHandle {
5715 let shape = self.shape();
5716 let dtype = self.dtype();
5717 let id = self.graph.write().unwrap().push(Node {
5718 op: Op::Fused(
5719 crate::registry::FusedOps::INPLACE_AFFINE,
5720 crate::registry::FusedOpParams::InplaceAffine { mul, add },
5721 ),
5722 inputs: vec![self.id],
5723 shape,
5724 dtype,
5725 });
5726 Self {
5727 graph: self.graph.clone(),
5728 id,
5729 }
5730 }
5731
5732 /// Append a `Floor` node (`⌊self⌋`). Output dtype = input dtype.
5733 /// Backward is the zero distribution almost everywhere; gradient
5734 /// is dropped silently.
5735 pub fn floor(&self) -> NodeHandle {
5736 self.unary_op(Op::Floor)
5737 }
5738
5739 /// Append a `Ceil` node (`⌈self⌉`). Output dtype = input dtype.
5740 /// Backward drops gradient (non-differentiable almost everywhere).
5741 pub fn ceil(&self) -> NodeHandle {
5742 self.unary_op(Op::Ceil)
5743 }
5744
5745 /// Append a `Round` node — banker's rounding (round-half-to-even,
5746 /// IEEE 754 roundeven). 0.5 → 0, 1.5 → 2, 2.5 → 2, 3.5 → 4.
5747 /// Output dtype = input dtype. Backward drops gradient.
5748 pub fn round(&self) -> NodeHandle {
5749 self.unary_op(Op::Round)
5750 }
5751
5752 /// Append a `Sign` node (`-1` / `0` / `1`). `sign(0) = 0` by
5753 /// subgradient convention. Output dtype = input dtype. Backward
5754 /// drops gradient.
5755 pub fn sign(&self) -> NodeHandle {
5756 self.unary_op(Op::Sign)
5757 }
5758
5759 /// Append an `Erf` node (Gauss error function). Output dtype =
5760 /// input dtype. Differentiable.
5761 pub fn erf(&self) -> NodeHandle {
5762 self.unary_op(Op::Erf)
5763 }
5764
5765 /// Append a `Gelu` node — exact-erf formulation of GELU
5766 /// (`0.5 * x * (1 + erf(x/√2))`). Distinct from [`Self::gelu_tanh`]
5767 /// (tanh approximation). Output dtype = input dtype.
5768 /// Differentiable.
5769 pub fn gelu(&self) -> NodeHandle {
5770 self.unary_op(Op::Gelu)
5771 }
5772
5773 /// Append a `Pow` node `pow(self, other)` element-wise (real
5774 /// exponent). Both operands must share dtype and shape. Distinct
5775 /// from [`Self::powi`] (scalar `i32` exponent). NaN follows
5776 /// IEEE-754 (`pow(-2, 0.5) = NaN`).
5777 ///
5778 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5779 /// typed error, not a panic.
5780 pub fn pow(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5781 let out_shape = self.shape();
5782 self.try_binary_op("pow", Op::Pow, other, out_shape)
5783 }
5784
5785 /// Append an `Rsqrt` node (`1 / sqrt(self)`). Same dtype as
5786 /// input. Single op rather than `sqrt(x).recip()` — one kernel
5787 /// launch and matches RMSNorm's `x * rsqrt(...)` shape.
5788 /// Differentiable.
5789 pub fn rsqrt(&self) -> NodeHandle {
5790 self.unary_op(Op::Rsqrt)
5791 }
5792
5793 /// Append a `Rem` node `self % other` element-wise (PyTorch
5794 /// convention: `a - floor(a/b) * b`, sign of result matches
5795 /// divisor). Both operands must share dtype and shape.
5796 /// Differentiable.
5797 ///
5798 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5799 /// typed error, not a panic.
5800 pub fn rem(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5801 let out_shape = self.shape();
5802 self.try_binary_op("rem", Op::Rem, other, out_shape)
5803 }
5804
5805 /// Append a `Flip` node — reverses element order along `dim`.
5806 /// Output shape == input shape. Materializing op (real byte
5807 /// shuffle; not a metadata-only view). Differentiable
5808 /// (involutive: backward is another Flip on the same dim).
5809 ///
5810 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5811 pub fn flip(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5812 let in_shape = self.shape();
5813 let rank = in_shape.dims().len();
5814 if dim >= rank {
5815 return Err(fuel_ir::Error::Msg(format!(
5816 "flip: dim {dim} out of bounds for rank {rank}",
5817 ))
5818 .bt());
5819 }
5820 let op = Op::Flip { dim };
5821 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5822 let id = self.graph.write().unwrap().push(Node {
5823 op,
5824 inputs: vec![self.id],
5825 shape,
5826 dtype,
5827 });
5828 Ok(Self {
5829 graph: self.graph.clone(),
5830 id,
5831 })
5832 }
5833
5834 /// Append a `Roll` node — cyclic shift along `dim` by `shift`
5835 /// positions. Positive `shift` moves elements to higher indices
5836 /// (wrapping); negative the opposite. Output shape == input
5837 /// shape. Differentiable (backward is `Roll { dim, -shift }`).
5838 ///
5839 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5840 pub fn roll(&self, dim: usize, shift: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5841 let in_shape = self.shape();
5842 let rank = in_shape.dims().len();
5843 if dim >= rank {
5844 return Err(fuel_ir::Error::Msg(format!(
5845 "roll: dim {dim} out of bounds for rank {rank}",
5846 ))
5847 .bt());
5848 }
5849 let op = Op::Roll { dim, shift };
5850 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5851 let id = self.graph.write().unwrap().push(Node {
5852 op,
5853 inputs: vec![self.id],
5854 shape,
5855 dtype,
5856 });
5857 Ok(Self {
5858 graph: self.graph.clone(),
5859 id,
5860 })
5861 }
5862
5863 /// Append a `CumSum` node — running cumulative sum along `dim`.
5864 /// Output shape == input shape. Differentiable; backward is
5865 /// reverse-cumsum (`Flip → CumSum → Flip`).
5866 ///
5867 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5868 pub fn cumsum(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5869 let in_shape = self.shape();
5870 let rank = in_shape.dims().len();
5871 if dim >= rank {
5872 return Err(fuel_ir::Error::Msg(format!(
5873 "cumsum: dim {dim} out of bounds for rank {rank}",
5874 ))
5875 .bt());
5876 }
5877 let dtype = self.dtype();
5878 let id = self.graph.write().unwrap().push(Node {
5879 op: Op::CumSum { dim },
5880 inputs: vec![self.id],
5881 shape: in_shape,
5882 dtype,
5883 });
5884 Ok(Self {
5885 graph: self.graph.clone(),
5886 id,
5887 })
5888 }
5889
5890 /// Append a `Triu` node — upper-triangular mask along the last two
5891 /// dims. `diagonal = 0` keeps the main diagonal and above; positive
5892 /// values shift the cutoff up (keeping less); negative shift down
5893 /// (keeping more, including subdiagonals).
5894 ///
5895 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
5896 pub fn triu(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5897 let in_shape = self.shape();
5898 let rank = in_shape.dims().len();
5899 if rank < 2 {
5900 return Err(fuel_ir::Error::Msg(format!(
5901 "triu: input must have rank >= 2, got {rank}",
5902 ))
5903 .bt());
5904 }
5905 let dtype = self.dtype();
5906 let id = self.graph.write().unwrap().push(Node {
5907 op: Op::Triu { diagonal },
5908 inputs: vec![self.id],
5909 shape: in_shape,
5910 dtype,
5911 });
5912 Ok(Self {
5913 graph: self.graph.clone(),
5914 id,
5915 })
5916 }
5917
5918 /// Append an [`Op::Scan`] node — a bounded `lax.scan` recurrence.
5919 /// `self` is the `init_carry`. The body must already be built in the same
5920 /// graph, referencing `Op::ScanPlaceholder{Carry,0}` for the per-step
5921 /// carry and `Op::ScanPlaceholder{Elem,i}` for the per-step slice of
5922 /// `xs[i]`; `consts` are referenced by real NodeId. `body_new_carry` /
5923 /// `body_y` are the body's two exit nodes. Always a 2-slot bundle
5924 /// (slot 0 = stacked `ys` `[bound] ++ body_y`, slot 1 = final carry);
5925 /// `emit` selects which slot this call projects. `early_exit` is Phase 2
5926 /// (always `None` here).
5927 ///
5928 /// **Returns `Result`**: a malformed body/carry/bound surfaces as a typed
5929 /// error — never a panic.
5930 pub fn scan(
5931 &self,
5932 xs: &[NodeHandle],
5933 consts: &[NodeHandle],
5934 body_new_carry: &NodeHandle,
5935 body_y: &NodeHandle,
5936 bound: usize,
5937 emit: ScanEmit,
5938 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5939 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
5940 if !same_graph(body_new_carry)
5941 || !same_graph(body_y)
5942 || !xs.iter().all(same_graph)
5943 || !consts.iter().all(same_graph)
5944 {
5945 return Err(fuel_ir::Error::Msg(
5946 "scan: init_carry, xs, consts, and body exits must live on one graph".into(),
5947 )
5948 .bt());
5949 }
5950 if bound == 0 {
5951 return Err(fuel_ir::Error::Msg("scan: bound must be >= 1".into()).bt());
5952 }
5953 let carry_shape = self.shape();
5954 if body_new_carry.shape().dims() != carry_shape.dims() {
5955 return Err(fuel_ir::Error::Msg(format!(
5956 "scan: body_new_carry shape {:?} must equal init_carry shape {:?}",
5957 body_new_carry.shape().dims(),
5958 carry_shape.dims(),
5959 ))
5960 .bt());
5961 }
5962 // Validate body placeholders at graph-build time (single-carry; every
5963 // Elem index < n_xs) so a malformed body is a typed Err here, not a
5964 // later `elem[index]` panic on the unroll / forward-driver path.
5965 {
5966 let g = self.graph.read().unwrap();
5967 crate::scan::validate_scan_body_placeholders(
5968 &g,
5969 &[body_new_carry.id, body_y.id],
5970 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
5971 // construction below); the IR and the unroll are not.
5972 1,
5973 xs.len(),
5974 )?;
5975 }
5976 let carry_dtype = self.dtype();
5977 let y_dtype = body_y.dtype();
5978
5979 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
5980 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
5981 ys_dims.push(bound);
5982 ys_dims.extend_from_slice(body_y.shape().dims());
5983 let ys_shape = Shape::from_dims(&ys_dims);
5984 let specs = vec![
5985 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
5986 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
5987 ];
5988 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs)
5989 .map_err(|e| fuel_ir::Error::Msg(format!("scan: compose_bundle failed: {e}")).bt())?;
5990
5991 let mut inputs: Vec<NodeId> = Vec::with_capacity(2 + xs.len() + consts.len() + 2);
5992 inputs.push(self.id);
5993 inputs.extend(xs.iter().map(|t| t.id));
5994 inputs.extend(consts.iter().map(|t| t.id));
5995 inputs.push(body_new_carry.id);
5996 inputs.push(body_y.id);
5997
5998 let id = {
5999 let mut g = self.graph.write().unwrap();
6000 // Node.shape/dtype are the PRIMARY (slot-0) shape/dtype per the
6001 // multi-output authoring contract.
6002 let id = g.push(Node {
6003 op: Op::Scan {
6004 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6005 // `parse_scan_layout` and `build_scan_step` all handle N
6006 // carries. This BUILDER deliberately still constructs ONE.
6007 //
6008 // Widening it means N+1 output-view specs through
6009 // `compose_bundle` below -- i.e. the bundle arity -- which is
6010 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6011 // is NOT this change. A reader must not read "the builder makes
6012 // one" as "multi-carry does not work".
6013 n_carries: 1,
6014 n_xs: xs.len(),
6015 bound,
6016 emit,
6017 early_exit: None,
6018 },
6019 inputs,
6020 shape: ys_shape,
6021 dtype: y_dtype,
6022 });
6023 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6024 .map_err(|e| {
6025 fuel_ir::Error::Msg(format!("scan: set_output_views failed: {e}")).bt()
6026 })?;
6027 id
6028 };
6029 let producer = Self {
6030 graph: self.graph.clone(),
6031 id,
6032 };
6033 match emit {
6034 ScanEmit::All => producer.view(0),
6035 ScanEmit::Final => producer.view(1),
6036 }
6037 }
6038
6039 /// Append an early-exit [`Op::Scan`] node — the `Result`-returning sibling
6040 /// of [`NodeHandle::scan`] that carries a convergence predicate as the extra
6041 /// trailing input (`early_exit = Some(ScanPredicate)`). `self` is the
6042 /// `init_carry`; `pred_exit` is a scalar-`U8` sub-DAG over the carry
6043 /// (`Op::ScanPlaceholder{Carry,0}` for the pre-step carry, and the shared
6044 /// `body_new_carry` node for the post-step carry) that stops iteration when
6045 /// it fires. The runtime stop count is data-dependent under the static
6046 /// capacity `bound`.
6047 ///
6048 /// **`consts` must include every const referenced by the body OR the
6049 /// predicate** — the clone/unroll machinery shares only `consts`; a
6050 /// predicate const outside `consts` would be re-cloned dataless and fail at
6051 /// realize.
6052 ///
6053 /// **Returns `Result`**: a malformed body/carry/bound, or a non-scalar /
6054 /// non-`U8` / `Elem`-referencing predicate, surfaces as a typed error —
6055 /// never a panic (validated at graph-build time).
6056 pub fn scan_until(
6057 &self,
6058 xs: &[NodeHandle],
6059 consts: &[NodeHandle],
6060 body_new_carry: &NodeHandle,
6061 body_y: &NodeHandle,
6062 pred_exit: &NodeHandle,
6063 bound: usize,
6064 emit: ScanEmit,
6065 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6066 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6067 if !same_graph(body_new_carry)
6068 || !same_graph(body_y)
6069 || !same_graph(pred_exit)
6070 || !xs.iter().all(same_graph)
6071 || !consts.iter().all(same_graph)
6072 {
6073 return Err(fuel_ir::Error::Msg(
6074 "scan_until: init_carry, xs, consts, body exits, and pred_exit must live on one graph".into(),
6075 ).bt());
6076 }
6077 if bound == 0 {
6078 return Err(fuel_ir::Error::Msg("scan_until: bound must be >= 1".into()).bt());
6079 }
6080 let carry_shape = self.shape();
6081 if body_new_carry.shape().dims() != carry_shape.dims() {
6082 return Err(fuel_ir::Error::Msg(format!(
6083 "scan_until: body_new_carry shape {:?} must equal init_carry shape {:?}",
6084 body_new_carry.shape().dims(),
6085 carry_shape.dims(),
6086 ))
6087 .bt());
6088 }
6089 // Validate body placeholders at graph-build time (single-carry; every
6090 // Elem index < n_xs) so a malformed body is a typed Err here, not a
6091 // later `elem[index]` panic in the forward driver's build_scan_step.
6092 {
6093 let g = self.graph.read().unwrap();
6094 crate::scan::validate_scan_body_placeholders(
6095 &g,
6096 &[body_new_carry.id, body_y.id],
6097 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6098 // construction below); the IR and the unroll are not.
6099 1,
6100 xs.len(),
6101 )?;
6102 }
6103 // Predicate must be a scalar Bool (shape [] or product == 1) — a
6104 // convergence flag, not a per-element mask. Validate at build time.
6105 // GAP-168(c): Bool, not U8. A predicate's natural producer is a
6106 // comparison, and those now yield Bool, so requiring U8 here would make
6107 // the ordinary `carry.ge(&thr)` path unusable as a predicate.
6108 if pred_exit.dtype() != fuel_ir::DType::Bool {
6109 return Err(fuel_ir::Error::Msg(format!(
6110 "scan_until: pred_exit must be Bool (a boolean flag), got {:?}",
6111 pred_exit.dtype(),
6112 ))
6113 .bt());
6114 }
6115 let pred_dims = pred_exit.shape();
6116 let pred_numel: usize = pred_dims.dims().iter().product();
6117 if pred_numel != 1 {
6118 return Err(fuel_ir::Error::Msg(format!(
6119 "scan_until: pred_exit must be a scalar (shape [] or [1]/all-ones), got {:?}",
6120 pred_dims.dims(),
6121 ))
6122 .bt());
6123 }
6124 // Every ScanPlaceholder reachable from pred_exit must be Carry{0} — the
6125 // predicate is over the carry, never a per-step Elem slice.
6126 {
6127 let g = self.graph.read().unwrap();
6128 for &id in &crate::topo_order_multi(&g, &[pred_exit.id]) {
6129 if let Op::ScanPlaceholder { role, index } = &g.node(id).op {
6130 let bad = matches!(role, ScanRole::Elem) || *index != 0;
6131 if bad {
6132 return Err(fuel_ir::Error::Msg(format!(
6133 "scan_until: pred_exit references ScanPlaceholder{{{role:?}, {index}}} — \
6134 the predicate may only read the carry (Carry, index 0)",
6135 )).bt());
6136 }
6137 }
6138 }
6139 }
6140 let carry_dtype = self.dtype();
6141 let y_dtype = body_y.dtype();
6142
6143 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6144 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6145 ys_dims.push(bound);
6146 ys_dims.extend_from_slice(body_y.shape().dims());
6147 let ys_shape = Shape::from_dims(&ys_dims);
6148 let specs = vec![
6149 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6150 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6151 ];
6152 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs).map_err(|e| {
6153 fuel_ir::Error::Msg(format!("scan_until: compose_bundle failed: {e}")).bt()
6154 })?;
6155
6156 let mut inputs: Vec<NodeId> = Vec::with_capacity(3 + xs.len() + consts.len());
6157 inputs.push(self.id);
6158 inputs.extend(xs.iter().map(|t| t.id));
6159 inputs.extend(consts.iter().map(|t| t.id));
6160 inputs.push(body_new_carry.id);
6161 inputs.push(body_y.id);
6162 inputs.push(pred_exit.id); // <-- the C1 trailing predicate
6163
6164 let id = {
6165 let mut g = self.graph.write().unwrap();
6166 let id = g.push(Node {
6167 op: Op::Scan {
6168 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6169 // `parse_scan_layout` and `build_scan_step` all handle N
6170 // carries. This BUILDER deliberately still constructs ONE.
6171 //
6172 // Widening it means N+1 output-view specs through
6173 // `compose_bundle` below -- i.e. the bundle arity -- which is
6174 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6175 // is NOT this change. A reader must not read "the builder makes
6176 // one" as "multi-carry does not work".
6177 n_carries: 1,
6178 n_xs: xs.len(),
6179 bound,
6180 emit,
6181 early_exit: Some(ScanPredicate),
6182 },
6183 inputs,
6184 shape: ys_shape,
6185 dtype: y_dtype,
6186 });
6187 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6188 .map_err(|e| {
6189 fuel_ir::Error::Msg(format!("scan_until: set_output_views failed: {e}")).bt()
6190 })?;
6191 id
6192 };
6193 let producer = Self {
6194 graph: self.graph.clone(),
6195 id,
6196 };
6197 match emit {
6198 ScanEmit::All => producer.view(0),
6199 ScanEmit::Final => producer.view(1),
6200 }
6201 }
6202
6203 /// Append a `Tril` node — lower-triangular mask along the last two
6204 /// dims. `diagonal = 0` keeps the main diagonal and below.
6205 /// `tril(diagonal = 0)` is the canonical causal-attention mask.
6206 ///
6207 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6208 pub fn tril(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6209 let in_shape = self.shape();
6210 let rank = in_shape.dims().len();
6211 if rank < 2 {
6212 return Err(fuel_ir::Error::Msg(format!(
6213 "tril: input must have rank >= 2, got {rank}",
6214 ))
6215 .bt());
6216 }
6217 let dtype = self.dtype();
6218 let id = self.graph.write().unwrap().push(Node {
6219 op: Op::Tril { diagonal },
6220 inputs: vec![self.id],
6221 shape: in_shape,
6222 dtype,
6223 });
6224 Ok(Self {
6225 graph: self.graph.clone(),
6226 id,
6227 })
6228 }
6229
6230 /// Append a `LogSoftmaxLastDim` node. Output shape == input shape.
6231 /// Numerically stable (max-subtracting formula) — preferred over
6232 /// `log(softmax(x))` for NLL / cross-entropy loss.
6233 ///
6234 /// **Returns `Result`**: rank < 1 surfaces as a typed error.
6235 pub fn log_softmax_last_dim(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6236 let in_shape = self.shape();
6237 if in_shape.dims().is_empty() {
6238 return Err(fuel_ir::Error::Msg(
6239 "log_softmax_last_dim: input must have rank >= 1".to_string(),
6240 )
6241 .bt());
6242 }
6243 let dtype = self.dtype();
6244 let id = self.graph.write().unwrap().push(Node {
6245 op: Op::LogSoftmaxLastDim,
6246 inputs: vec![self.id],
6247 shape: in_shape,
6248 dtype,
6249 });
6250 Ok(Self {
6251 graph: self.graph.clone(),
6252 id,
6253 })
6254 }
6255
6256 /// Append a `MaskedFill` node. `mask` must be `Bool` (GAP-168(c)) and have
6257 /// the same shape as `self`. Every position where `mask` is true gets `value`;
6258 /// every position where `mask == 0` passes `self` through. `value`
6259 /// is a scalar of `self`'s dtype.
6260 ///
6261 /// **Returns `Result`**: shape or dtype mismatches surface as typed
6262 /// errors.
6263 pub fn masked_fill(
6264 &self,
6265 mask: &NodeHandle,
6266 value: Scalar,
6267 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6268 self.require_same_graph(mask, "masked_fill", "mask")?;
6269 if self.shape().dims() != mask.shape().dims() {
6270 return Err(fuel_ir::Error::Msg(format!(
6271 "masked_fill: x.shape={:?} != mask.shape={:?}",
6272 self.shape().dims(),
6273 mask.shape().dims(),
6274 ))
6275 .bt());
6276 }
6277 if mask.dtype() != DType::Bool {
6278 return Err(fuel_ir::Error::Msg(format!(
6279 "masked_fill: mask dtype must be Bool, got {:?} — cast a numeric \
6280 mask to Bool explicitly (GAP-168(c))",
6281 mask.dtype(),
6282 ))
6283 .bt());
6284 }
6285 // GAP-002 (D5) / GAP-075 (fix B): classify EVERY dtype explicitly — no
6286 // wildcard default. The guard is SEMANTIC: masked_fill needs a
6287 // representable fill value AND a zero (the backward fills with zero), so
6288 // it rejects the packed formats (F4/F6*, no scalar fill) and the
6289 // block-scales (F8E8M0/F8E6M2, no zero), and permits the ordinary
6290 // numeric dtypes. Rejecting on the guard's own terms also keeps the
6291 // `Scalar::zero` Err branch in the MaskedFill `backward` arm provably
6292 // unreachable in a well-formed graph.
6293 //
6294 // Under the OLD denylist (`matches!(reject-set)`, else allow) a FUTURE
6295 // dtype fell through to "permitted" SILENTLY. With new dtypes scheduled
6296 // (GAP-097: e5m2, complex, sub-byte int, …) that would silently accept
6297 // masked_fill on formats whose fill semantics are unsettled. An
6298 // exhaustive match makes a new dtype a COMPILE ERROR here, forcing the
6299 // person who adds it to decide its permission consciously — the compiler
6300 // is the real guard; the tests below protect the existing classification.
6301 //
6302 // NOTE: "permitted" is a graph-build PERMISSION (is masked_fill
6303 // semantically well-defined?), NOT a promise a backend can allocate/run
6304 // the dtype. An unimplemented storage still declines loudly downstream
6305 // (typed `UnsupportedDTypeForOp` at allocation), which is the sound
6306 // composition — a semantically-true guard upstream, a loud capability
6307 // decline downstream.
6308 match self.dtype() {
6309 DType::F4 | DType::F6E2M3 | DType::F6E3M2 | DType::F8E8M0 | DType::F8E6M2 => {
6310 return Err(
6311 fuel_ir::Error::UnsupportedDTypeForOp(self.dtype(), "masked_fill").bt(),
6312 );
6313 }
6314 DType::U8
6315 | DType::I8
6316 | DType::U32
6317 | DType::I16
6318 | DType::I32
6319 | DType::I64
6320 | DType::BF16
6321 | DType::F16
6322 | DType::F32
6323 | DType::F64
6324 | DType::F8E4M3
6325 // GAP-097: F8E5M2 is PERMITTED, on the guard's own semantic terms.
6326 //
6327 // The reject set above is not "exotic dtypes" — it is two distinct
6328 // NON-VALUE categories: the block-scales (F8E8M0/F8E6M2) ride as
6329 // sibling operands and are not element value dtypes at all, and the
6330 // block-scoped elements (F4/F6*) have no standalone byte layout, so
6331 // a single element is not addressable without its block. Neither has
6332 // a well-defined fill-one-element operation, which is what this op
6333 // needs. F8E5M2 is a value dtype in exactly the way F8E4M3 (already
6334 // permitted, directly above) is: sign + exponent + mantissa, a
6335 // standalone byte layout, a representable zero for the backward, and
6336 // a representable fill value. So permitting it CONTINUES the
6337 // existing classification; rejecting would be the exception.
6338 //
6339 // Weighed and rejected as grounds for the opposite call: F8E5M2
6340 // currently has NO host or CUDA storage (fuel-cpu-backend and
6341 // fuel-cuda-backend both decline it), so this permits a graph the
6342 // backends cannot yet allocate — GAP(GAP-161) tracks that storage
6343 // decline and its expiry. That is the NOTE above working as
6344 // designed — permission is semantic, allocation is a capability, and
6345 // they are different questions. Writing REJECT here would encode the
6346 // claim "F8E5M2 has no representable fill value", which is FALSE and
6347 // would outlive the storage gap that motivated it.
6348 | DType::F8E5M2
6349 // GAP-168(c): Bool is a value dtype with a representable fill value
6350 // (true/false) and a zero for the backward (false) — permitted on
6351 // this guard's own semantic terms, exactly as the FP8 value dtypes
6352 // are. (This is the FILLED tensor's dtype; the MASK dtype is checked
6353 // separately above.)
6354 | DType::Bool => {}
6355 }
6356 if value.dtype() != self.dtype() {
6357 return Err(fuel_ir::Error::Msg(format!(
6358 "masked_fill: value dtype {:?} != x dtype {:?}",
6359 value.dtype(),
6360 self.dtype(),
6361 ))
6362 .bt());
6363 }
6364 let op = Op::MaskedFill { value };
6365 let (shape, dtype) = crate::shape::primitive_shape(
6366 &op,
6367 &[self.shape(), mask.shape()],
6368 &[self.dtype(), mask.dtype()],
6369 )
6370 .expect("masked_fill: shapes/dtypes validated above");
6371 let id = self.graph.write().unwrap().push(Node {
6372 op,
6373 inputs: vec![self.id, mask.id],
6374 shape,
6375 dtype,
6376 });
6377 Ok(Self {
6378 graph: self.graph.clone(),
6379 id,
6380 })
6381 }
6382
6383 /// Append a `Pad` node — multi-dim padding. `padding[i] = (before, after)`
6384 /// for axis `i`; `padding.len()` must equal `self.rank()`.
6385 /// Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
6386 /// `value` is the fill constant for [`PadMode::Constant`]
6387 /// (ignored for other modes).
6388 ///
6389 /// Only Constant mode is wired through the executor in the v1
6390 /// cut; the other modes produce a clean error at realize time.
6391 /// Differentiable for Constant (backward slices the gradient
6392 /// along each padded axis to restore the input shape).
6393 ///
6394 /// **Returns `Result`**: rank mismatch surfaces as a typed error.
6395 pub fn pad(
6396 &self,
6397 padding: Vec<(usize, usize)>,
6398 mode: PadMode,
6399 value: f64,
6400 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6401 let in_shape = self.shape();
6402 let rank = in_shape.dims().len();
6403 if padding.len() != rank {
6404 return Err(fuel_ir::Error::Msg(format!(
6405 "pad: padding.len() ({}) must equal tensor rank ({rank})",
6406 padding.len(),
6407 ))
6408 .bt());
6409 }
6410 let op = Op::Pad {
6411 padding,
6412 mode,
6413 value,
6414 };
6415 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6416 let id = self.graph.write().unwrap().push(Node {
6417 op,
6418 inputs: vec![self.id],
6419 shape,
6420 dtype,
6421 });
6422 Ok(Self {
6423 graph: self.graph.clone(),
6424 id,
6425 })
6426 }
6427
6428 /// Append an `Equal` node (`self == other`) producing a `Bool` mask.
6429 /// Both operands must share dtype and shape; output dtype is `Bool`
6430 /// (`1` where equal, `0` otherwise). NaN follows IEEE-754
6431 /// (`NaN == NaN` is false). Non-differentiable.
6432 ///
6433 /// # Panics
6434 ///
6435 /// Panics if any operand belongs to a different [`Graph`] than the one this
6436 /// builder is building into. Operand identity is graph-scoped and checked by
6437 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6438 /// deliberate and replaces the hang a cross-graph handle used to produce.
6439 /// Build every operand from one graph, or use a `Result`-returning entry
6440 /// point where one exists.
6441 pub fn eq(&self, other: &NodeHandle) -> NodeHandle {
6442 self.binary_compare_op("eq", Op::Equal, other)
6443 }
6444
6445 /// Append a `Ne` node (`self != other`) producing a `Bool` mask.
6446 /// Same shape/dtype contract as [`Self::eq`]. NaN follows
6447 /// IEEE-754 (`NaN != NaN` is true → `1`). Non-differentiable.
6448 ///
6449 /// # Panics
6450 ///
6451 /// Panics if any operand belongs to a different [`Graph`] than the one this
6452 /// builder is building into. Operand identity is graph-scoped and checked by
6453 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6454 /// deliberate and replaces the hang a cross-graph handle used to produce.
6455 /// Build every operand from one graph, or use a `Result`-returning entry
6456 /// point where one exists.
6457 pub fn ne(&self, other: &NodeHandle) -> NodeHandle {
6458 self.binary_compare_op("ne", Op::Ne, other)
6459 }
6460
6461 /// Append an `Lt` node (`self < other`) producing a `Bool` mask.
6462 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6463 /// is always `0` (IEEE-754 unordered). Non-differentiable.
6464 ///
6465 /// # Panics
6466 ///
6467 /// Panics if any operand belongs to a different [`Graph`] than the one this
6468 /// builder is building into. Operand identity is graph-scoped and checked by
6469 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6470 /// deliberate and replaces the hang a cross-graph handle used to produce.
6471 /// Build every operand from one graph, or use a `Result`-returning entry
6472 /// point where one exists.
6473 pub fn lt(&self, other: &NodeHandle) -> NodeHandle {
6474 self.binary_compare_op("lt", Op::Lt, other)
6475 }
6476
6477 /// Append an `Le` node (`self <= other`) producing a `Bool` mask.
6478 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6479 /// is always `0`. Non-differentiable.
6480 ///
6481 /// # Panics
6482 ///
6483 /// Panics if any operand belongs to a different [`Graph`] than the one this
6484 /// builder is building into. Operand identity is graph-scoped and checked by
6485 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6486 /// deliberate and replaces the hang a cross-graph handle used to produce.
6487 /// Build every operand from one graph, or use a `Result`-returning entry
6488 /// point where one exists.
6489 pub fn le(&self, other: &NodeHandle) -> NodeHandle {
6490 self.binary_compare_op("le", Op::Le, other)
6491 }
6492
6493 /// Append a `Gt` node (`self > other`) producing a `Bool` mask.
6494 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6495 /// is always `0`. Non-differentiable.
6496 ///
6497 /// # Panics
6498 ///
6499 /// Panics if any operand belongs to a different [`Graph`] than the one this
6500 /// builder is building into. Operand identity is graph-scoped and checked by
6501 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6502 /// deliberate and replaces the hang a cross-graph handle used to produce.
6503 /// Build every operand from one graph, or use a `Result`-returning entry
6504 /// point where one exists.
6505 pub fn gt(&self, other: &NodeHandle) -> NodeHandle {
6506 self.binary_compare_op("gt", Op::Gt, other)
6507 }
6508
6509 /// Append a `Ge` node (`self >= other`) producing a `Bool` mask.
6510 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6511 /// is always `0`. Non-differentiable.
6512 ///
6513 /// # Panics
6514 ///
6515 /// Panics if any operand belongs to a different [`Graph`] than the one this
6516 /// builder is building into. Operand identity is graph-scoped and checked by
6517 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6518 /// deliberate and replaces the hang a cross-graph handle used to produce.
6519 /// Build every operand from one graph, or use a `Result`-returning entry
6520 /// point where one exists.
6521 pub fn ge(&self, other: &NodeHandle) -> NodeHandle {
6522 self.binary_compare_op("ge", Op::Ge, other)
6523 }
6524
6525 /// Ternary select: `result[i] = if self[i] { a[i] } else { b[i] }`.
6526 /// Receiver is the `cond` mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
6527 /// must share dtype with each other and shape with `self`. Output
6528 /// dtype matches `a`/`b`. Returning a new tensor where each slot is
6529 /// picked from `a` (cond=1) or `b` (cond=0).
6530 ///
6531 /// Named `where_cond` because `where` is a Rust reserved keyword.
6532 /// Common spelling in Candle/PyTorch families.
6533 ///
6534 /// Differentiable through `a` and `b` only; gradient through the
6535 /// cond mask is `None` (registered in
6536 /// [`crate::grad::WhereRule`]).
6537 ///
6538 /// # Panics
6539 ///
6540 /// Panics if any operand belongs to a different [`Graph`] than the one this
6541 /// builder is building into. Operand identity is graph-scoped and checked by
6542 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6543 /// deliberate and replaces the hang a cross-graph handle used to produce.
6544 /// Build every operand from one graph, or use a `Result`-returning entry
6545 /// point where one exists.
6546 pub fn where_cond(&self, a: &NodeHandle, b: &NodeHandle) -> NodeHandle {
6547 assert!(
6548 Arc::ptr_eq(&self.graph, &a.graph) && Arc::ptr_eq(&self.graph, &b.graph),
6549 "where_cond: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
6550 );
6551 assert_eq!(
6552 self.dtype(),
6553 DType::Bool,
6554 "where_cond: cond must be Bool (GAP-168(c)), got {:?} — cast a numeric \
6555 mask to Bool explicitly",
6556 self.dtype(),
6557 );
6558 assert_eq!(
6559 a.dtype(),
6560 b.dtype(),
6561 "where_cond: a/b dtype mismatch: a={:?}, b={:?}",
6562 a.dtype(),
6563 b.dtype(),
6564 );
6565 assert_eq!(
6566 self.shape().dims(),
6567 a.shape().dims(),
6568 "where_cond: cond/a shape mismatch: cond={:?}, a={:?}",
6569 self.shape().dims(),
6570 a.shape().dims(),
6571 );
6572 assert_eq!(
6573 self.shape().dims(),
6574 b.shape().dims(),
6575 "where_cond: cond/b shape mismatch: cond={:?}, b={:?}",
6576 self.shape().dims(),
6577 b.shape().dims(),
6578 );
6579 let (shape, dtype) = crate::shape::primitive_shape(
6580 &Op::Where,
6581 &[self.shape(), a.shape(), b.shape()],
6582 &[self.dtype(), a.dtype(), b.dtype()],
6583 )
6584 .expect("where_cond: shapes/dtypes validated above");
6585 let id = self.graph.write().unwrap().push(Node {
6586 op: Op::Where,
6587 inputs: vec![self.id, a.id, b.id],
6588 shape,
6589 dtype,
6590 });
6591 Self {
6592 graph: self.graph.clone(),
6593 id,
6594 }
6595 }
6596
6597 // --- dtype and broadcasting ---
6598
6599 /// Append a `Cast` node converting this tensor's element type to
6600 /// `target`. Shape is preserved. An identity cast (`target` equals the
6601 /// current dtype) is a no-op that the optimizer elides (see
6602 /// `opt::optimize`'s identity-`Cast` rule) — kept here rather than
6603 /// special-cased at construction so every identity cast, however it
6604 /// arises (decompose, autograd, user), is removed in one place.
6605 pub fn cast(&self, target: DType) -> NodeHandle {
6606 let op = Op::Cast(target);
6607 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6608 .expect("cast: single input, dtype change always infers");
6609 let id = self.graph.write().unwrap().push(Node {
6610 op,
6611 inputs: vec![self.id],
6612 shape,
6613 dtype,
6614 });
6615 Self {
6616 graph: self.graph.clone(),
6617 id,
6618 }
6619 }
6620
6621 /// Append a `BroadcastTo` node that expands `self` to the given target
6622 /// shape using NumPy broadcasting rules (right-align, pad with 1s,
6623 /// expand size-1 dims). The new tensor has the target shape and the
6624 /// same dtype as `self`.
6625 pub fn broadcast_to(&self, target: impl Into<Shape>) -> NodeHandle {
6626 let target = target.into();
6627 let src_dims = self.shape();
6628 // Validate broadcast compatibility up front so users hear about
6629 // bad target shapes at build time, not realize time.
6630 check_broadcast_compatible(src_dims.dims(), target.dims());
6631 let op = Op::BroadcastTo(target);
6632 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6633 .expect("broadcast_to: compatibility validated above");
6634 let id = self.graph.write().unwrap().push(Node {
6635 op,
6636 inputs: vec![self.id],
6637 shape,
6638 dtype,
6639 });
6640 Self {
6641 graph: self.graph.clone(),
6642 id,
6643 }
6644 }
6645
6646 /// Result-returning sibling of [`Self::broadcast_to`]. Surfaces
6647 /// shape incompatibility as a typed error rather than panicking.
6648 pub fn try_broadcast_to(
6649 &self,
6650 target: impl Into<Shape>,
6651 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6652 let target = target.into();
6653 let src_dims = self.shape();
6654 try_check_broadcast_compatible(src_dims.dims(), target.dims())?;
6655 let op = Op::BroadcastTo(target);
6656 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6657 let id = self.graph.write().unwrap().push(Node {
6658 op,
6659 inputs: vec![self.id],
6660 shape,
6661 dtype,
6662 });
6663 Ok(Self {
6664 graph: self.graph.clone(),
6665 id,
6666 })
6667 }
6668
6669 /// Append an `Unsqueeze` node that inserts a size-1 dimension at
6670 /// position `dim`. `dim` must be in `0..=rank` (where `dim == rank`
6671 /// appends to the end). Pure metadata — the output shares bytes
6672 /// with `self`, with a new size-1 axis layered into the Layout
6673 /// side-table. Strictly more efficient than `reshape` for the
6674 /// size-1-insertion case because non-contiguous (e.g. transposed
6675 /// or broadcast) inputs flow through without auto-Contiguize.
6676 pub fn unsqueeze(&self, dim: usize) -> NodeHandle {
6677 let in_shape = self.shape();
6678 let rank = in_shape.dims().len();
6679 assert!(
6680 dim <= rank,
6681 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6682 );
6683 let op = Op::Unsqueeze { dim };
6684 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6685 .expect("unsqueeze: dim validated above");
6686 let id = self.graph.write().unwrap().push(Node {
6687 op,
6688 inputs: vec![self.id],
6689 shape,
6690 dtype,
6691 });
6692 Self {
6693 graph: self.graph.clone(),
6694 id,
6695 }
6696 }
6697
6698 /// Result-returning sibling of [`Self::unsqueeze`]. Surfaces
6699 /// `dim > rank` as a typed error rather than panicking.
6700 pub fn try_unsqueeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6701 let in_shape = self.shape();
6702 let rank = in_shape.dims().len();
6703 if dim > rank {
6704 return Err(fuel_ir::Error::Msg(format!(
6705 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6706 ))
6707 .bt());
6708 }
6709 let op = Op::Unsqueeze { dim };
6710 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6711 let id = self.graph.write().unwrap().push(Node {
6712 op,
6713 inputs: vec![self.id],
6714 shape,
6715 dtype,
6716 });
6717 Ok(Self {
6718 graph: self.graph.clone(),
6719 id,
6720 })
6721 }
6722
6723 /// Append a `Squeeze` node that drops the size-1 dimension at
6724 /// position `dim` (range `0..rank`). Inverse of [`Self::unsqueeze`].
6725 /// Metadata-only view: the output shares bytes with `self`, with
6726 /// the named dim pruned from the Layout side-table.
6727 ///
6728 /// **Returns `Result`** rather than panicking — production paths
6729 /// can recover from a bad `dim` instead of crashing. Bad `dim`
6730 /// (out of bounds OR `shape[dim] != 1`) surfaces as a typed error.
6731 pub fn squeeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6732 let in_shape = self.shape();
6733 let rank = in_shape.dims().len();
6734 if dim >= rank {
6735 return Err(fuel_ir::Error::Msg(format!(
6736 "squeeze: dim {dim} out of bounds for rank {rank} (must be < rank)",
6737 ))
6738 .bt());
6739 }
6740 if in_shape.dims()[dim] != 1 {
6741 return Err(fuel_ir::Error::Msg(format!(
6742 "squeeze: dim {dim} has size {}, expected 1",
6743 in_shape.dims()[dim],
6744 ))
6745 .bt());
6746 }
6747 let op = Op::Squeeze { dim };
6748 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6749 let id = self.graph.write().unwrap().push(Node {
6750 op,
6751 inputs: vec![self.id],
6752 shape,
6753 dtype,
6754 });
6755 Ok(Self {
6756 graph: self.graph.clone(),
6757 id,
6758 })
6759 }
6760
6761 /// Append an `Op::Contiguize` node that materializes a
6762 /// contiguous copy of `self`. Output shape and dtype match the
6763 /// input; only the layout changes to contiguous + zero-offset.
6764 /// Zero-copy when the input is already contiguous + zero-offset
6765 /// (the executor adopts the input Storage Arc unchanged).
6766 ///
6767 /// First-class IR node so the optimizer (Phase 2.2) can insert
6768 /// layout-fixups before kernels that don't advertise
6769 /// `crate::KernelCaps::strided_input` without overloading
6770 /// [`Self::reshape`]'s "change shape" semantics.
6771 pub fn contiguize(&self) -> NodeHandle {
6772 let shape = self.shape().clone();
6773 let dtype = self.dtype();
6774 let id = self.graph.write().unwrap().push(Node {
6775 op: Op::Contiguize,
6776 inputs: vec![self.id],
6777 shape,
6778 dtype,
6779 });
6780 Self {
6781 graph: self.graph.clone(),
6782 id,
6783 }
6784 }
6785
6786 /// Append a `Reshape` node producing `self`'s data under a new shape.
6787 /// The new shape must have the same total element count as the
6788 /// current shape.
6789 pub fn reshape(&self, target: impl Into<Shape>) -> NodeHandle {
6790 let target = target.into();
6791 assert_eq!(
6792 self.shape().elem_count(),
6793 target.elem_count(),
6794 "reshape: element count mismatch: from {} to {}",
6795 self.shape().elem_count(),
6796 target.elem_count(),
6797 );
6798 let op = Op::Reshape(target);
6799 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6800 .expect("reshape: element count validated above");
6801 let id = self.graph.write().unwrap().push(Node {
6802 op,
6803 inputs: vec![self.id],
6804 shape,
6805 dtype,
6806 });
6807 Self {
6808 graph: self.graph.clone(),
6809 id,
6810 }
6811 }
6812
6813 /// Result-returning sibling of [`Self::reshape`]. Surfaces
6814 /// element-count mismatch as a typed error rather than panicking.
6815 pub fn try_reshape(
6816 &self,
6817 target: impl Into<Shape>,
6818 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6819 let target = target.into();
6820 let from = self.shape().elem_count();
6821 let to = target.elem_count();
6822 if from != to {
6823 return Err(fuel_ir::Error::Msg(format!(
6824 "reshape: element count mismatch: from {from} to {to}",
6825 ))
6826 .bt());
6827 }
6828 let op = Op::Reshape(target);
6829 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6830 let id = self.graph.write().unwrap().push(Node {
6831 op,
6832 inputs: vec![self.id],
6833 shape,
6834 dtype,
6835 });
6836 Ok(Self {
6837 graph: self.graph.clone(),
6838 id,
6839 })
6840 }
6841
6842 /// Append a `ReduceSumTo` node that sum-reduces `self` to a smaller
6843 /// shape. The target must be reachable from `self.shape()` via
6844 /// reduction of dims (i.e. `self.shape()` could be produced from
6845 /// `target` by broadcasting).
6846 pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> NodeHandle {
6847 let target = target.into();
6848 // Symmetric check: self must be broadcast-compatible FROM the
6849 // smaller target. That is, the target must be broadcast-ready to
6850 // self.shape().
6851 check_broadcast_compatible(target.dims(), self.shape().dims());
6852 let op = Op::ReduceSumTo(target);
6853 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6854 .expect("reduce_sum_to: compatibility validated above");
6855 let id = self.graph.write().unwrap().push(Node {
6856 op,
6857 inputs: vec![self.id],
6858 shape,
6859 dtype,
6860 });
6861 Self {
6862 graph: self.graph.clone(),
6863 id,
6864 }
6865 }
6866
6867 /// Append a `ReduceMaxTo` node that max-reduces `self` to a smaller
6868 /// shape — the max-symmetric counterpart of [`Self::reduce_sum_to`].
6869 /// The target must be reachable from `self.shape()` via reduction
6870 /// of dims (i.e. `self.shape()` could be produced from `target` by
6871 /// broadcasting).
6872 pub fn reduce_max_to(&self, target: impl Into<Shape>) -> NodeHandle {
6873 let target = target.into();
6874 check_broadcast_compatible(target.dims(), self.shape().dims());
6875 let op = Op::ReduceMaxTo(target);
6876 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6877 .expect("reduce_max_to: compatibility validated above");
6878 let id = self.graph.write().unwrap().push(Node {
6879 op,
6880 inputs: vec![self.id],
6881 shape,
6882 dtype,
6883 });
6884 Self {
6885 graph: self.graph.clone(),
6886 id,
6887 }
6888 }
6889
6890 // --- reductions to a scalar ---
6891
6892 /// Append a `SumAll` node reducing every element to a scalar (rank-0).
6893 pub fn sum_all(&self) -> NodeHandle {
6894 self.scalar_reduction(Op::SumAll)
6895 }
6896
6897 /// Append a `MaxAll` node producing the max element as a scalar.
6898 pub fn max_all(&self) -> NodeHandle {
6899 self.scalar_reduction(Op::MaxAll)
6900 }
6901
6902 /// Append a `MinAll` node producing the min element as a scalar.
6903 pub fn min_all(&self) -> NodeHandle {
6904 self.scalar_reduction(Op::MinAll)
6905 }
6906
6907 /// Append a `MeanAll` node producing the arithmetic mean as a scalar.
6908 pub fn mean_all(&self) -> NodeHandle {
6909 self.scalar_reduction(Op::MeanAll)
6910 }
6911
6912 // --- reductions along one dimension ---
6913
6914 /// Append a `SumDim(dim)` node. Reduces along `dim`; output rank is
6915 /// `input rank - 1` (the reduced dim is removed).
6916 pub fn sum_dim(&self, dim: usize) -> NodeHandle {
6917 self.axis_reduction("sum_dim", Op::SumDim(dim), dim)
6918 }
6919
6920 /// Append a `MaxDim(dim)` node.
6921 pub fn max_dim(&self, dim: usize) -> NodeHandle {
6922 self.axis_reduction("max_dim", Op::MaxDim(dim), dim)
6923 }
6924
6925 /// Append a `MinDim(dim)` node.
6926 pub fn min_dim(&self, dim: usize) -> NodeHandle {
6927 self.axis_reduction("min_dim", Op::MinDim(dim), dim)
6928 }
6929
6930 /// Append a `MeanDim(dim)` node.
6931 pub fn mean_dim(&self, dim: usize) -> NodeHandle {
6932 self.axis_reduction("mean_dim", Op::MeanDim(dim), dim)
6933 }
6934
6935 /// Append an `ArgMaxDim(dim)` node. Produces a U32 tensor with the
6936 /// reduced dim removed, whose values are the index of the maximum
6937 /// along that dim. Non-differentiable — trying to run `backward()`
6938 /// through an ArgMax node will panic.
6939 pub fn argmax_dim(&self, dim: usize) -> NodeHandle {
6940 self.index_reduction("argmax_dim", Op::ArgMaxDim(dim), dim)
6941 }
6942
6943 /// Append an `ArgMinDim(dim)` node. Same semantics as `argmax_dim`
6944 /// but for the minimum.
6945 pub fn argmin_dim(&self, dim: usize) -> NodeHandle {
6946 self.index_reduction("argmin_dim", Op::ArgMinDim(dim), dim)
6947 }
6948
6949 /// Internal helper for index-producing reductions. Validates the
6950 /// dim, builds the reduced shape, and stamps the output with
6951 /// `DType::U32` regardless of the input dtype.
6952 fn index_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
6953 let in_shape = self.shape();
6954 assert!(
6955 dim < in_shape.dims().len(),
6956 "{name}: dim {dim} out of bounds for shape {:?}",
6957 in_shape.dims(),
6958 );
6959 // primitive_shape carries both the rank-reduced shape and the U32
6960 // index dtype for ArgMaxDim/ArgMinDim (the single source of truth).
6961 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6962 .expect("index_reduction: dim validated above");
6963 let id = self.graph.write().unwrap().push(Node {
6964 op,
6965 inputs: vec![self.id],
6966 shape,
6967 dtype,
6968 });
6969 Self {
6970 graph: self.graph.clone(),
6971 id,
6972 }
6973 }
6974
6975 // --- compositions ---
6976
6977 /// Append a `SoftmaxLastDim` node. Shape is preserved.
6978 ///
6979 /// Phase 7.6 step 3: emits `Op::Fused(FusedOps::SOFTMAX_LAST_DIM,
6980 /// FusedOpParams::SoftmaxLastDim)` — the registry-extended arm.
6981 /// The legacy `Op::SoftmaxLastDim` variant remains in the enum
6982 /// during the migration; step 5 drops it once nothing emits it.
6983 pub fn softmax_last_dim(&self) -> NodeHandle {
6984 assert!(
6985 !self.shape().dims().is_empty(),
6986 "softmax_last_dim: input must be rank >= 1",
6987 );
6988 self.unary_op(Op::Fused(
6989 crate::registry::FusedOps::SOFTMAX_LAST_DIM,
6990 crate::registry::FusedOpParams::SoftmaxLastDim,
6991 ))
6992 }
6993
6994 /// Append a `CausalConv1d` node — depthwise 1-D causal convolution
6995 /// + bias + optional fused SiLU. Three inputs:
6996 /// - `self` (x): `[batch, channels, seq + kernel - 1]` F32
6997 /// (caller pre-pads with `kernel - 1` zeros on the left for the
6998 /// causal mask — matches Mamba-2's prefill convention).
6999 /// - `weight`: `[channels, 1, kernel]` F32 (depthwise — one filter
7000 /// per channel; `groups == channels`).
7001 /// - `bias`: `[channels]` F32 (required — matches baracuda's
7002 /// `causal_conv1d_*_run` signature; pass zeros if you don't want
7003 /// a bias).
7004 ///
7005 /// Output: `[batch, channels, seq]` F32 where `seq = x.dims[2] -
7006 /// (kernel - 1)`.
7007 ///
7008 /// Emits `Op::Fused(FusedOps::CAUSAL_CONV1D,
7009 /// FusedOpParams::CausalConv1d { use_silu })`. See
7010 /// `fuel-graph/src/registry/causal_conv1d.rs` for the registry
7011 /// entry. No primitive decomposition exists (fuel-graph has no
7012 /// `Op::Conv1D`); backends without a native kernel fall through
7013 /// to the executor's cpu_fallback path.
7014 ///
7015 /// # Panics
7016 ///
7017 /// Panics if any operand belongs to a different [`Graph`] than the one this
7018 /// builder is building into. Operand identity is graph-scoped and checked by
7019 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7020 /// deliberate and replaces the hang a cross-graph handle used to produce.
7021 /// Build every operand from one graph, or use a `Result`-returning entry
7022 /// point where one exists.
7023 pub fn causal_conv1d(
7024 &self,
7025 weight: &NodeHandle,
7026 bias: &NodeHandle,
7027 use_silu: bool,
7028 ) -> NodeHandle {
7029 assert!(
7030 Arc::ptr_eq(&self.graph, &weight.graph) && Arc::ptr_eq(&self.graph, &bias.graph),
7031 "causal_conv1d: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7032 );
7033 let dtype = self.dtype();
7034 assert!(
7035 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7036 "causal_conv1d: x must be F32/F64/BF16/F16, got {dtype:?}",
7037 );
7038 assert_eq!(
7039 weight.dtype(),
7040 dtype,
7041 "causal_conv1d: weight dtype {:?} must match x dtype {dtype:?}",
7042 weight.dtype(),
7043 );
7044 assert_eq!(
7045 bias.dtype(),
7046 dtype,
7047 "causal_conv1d: bias dtype {:?} must match x dtype {dtype:?}",
7048 bias.dtype(),
7049 );
7050 let x_dims = self.shape();
7051 let x_dims = x_dims.dims();
7052 let w_dims = weight.shape();
7053 let w_dims = w_dims.dims();
7054 let b_dims = bias.shape();
7055 let b_dims = b_dims.dims();
7056 assert_eq!(
7057 x_dims.len(),
7058 3,
7059 "causal_conv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
7060 );
7061 assert_eq!(
7062 w_dims.len(),
7063 3,
7064 "causal_conv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
7065 );
7066 assert_eq!(
7067 b_dims.len(),
7068 1,
7069 "causal_conv1d: bias must be rank 1 [channels], got {b_dims:?}",
7070 );
7071 let batch = x_dims[0];
7072 let channels = x_dims[1];
7073 let x_seq = x_dims[2];
7074 let kernel = w_dims[2];
7075 assert_eq!(
7076 w_dims[0], channels,
7077 "causal_conv1d: weight's first dim {} must equal channels {channels}",
7078 w_dims[0],
7079 );
7080 assert_eq!(
7081 w_dims[1], 1,
7082 "causal_conv1d: weight's middle dim must be 1 (depthwise), got {}",
7083 w_dims[1],
7084 );
7085 assert_eq!(
7086 b_dims[0], channels,
7087 "causal_conv1d: bias length {} must equal channels {channels}",
7088 b_dims[0],
7089 );
7090 assert!(
7091 x_seq >= kernel - 1,
7092 "causal_conv1d: x time dim {x_seq} must be ≥ kernel - 1 = {} \
7093 (caller must pre-pad with {} zeros)",
7094 kernel - 1,
7095 kernel - 1,
7096 );
7097 let out_seq = x_seq - (kernel - 1);
7098 let id = self.graph.write().unwrap().push(Node {
7099 op: Op::Fused(
7100 crate::registry::FusedOps::CAUSAL_CONV1D,
7101 crate::registry::FusedOpParams::CausalConv1d { use_silu },
7102 ),
7103 inputs: vec![self.id, weight.id, bias.id],
7104 shape: Shape::from_dims(&[batch, channels, out_seq]),
7105 dtype,
7106 });
7107 Self {
7108 graph: self.graph.clone(),
7109 id,
7110 }
7111 }
7112
7113 /// Append an `Nf4Matmul` node — bitsandbytes-style 4-bit
7114 /// NormalFloat quantized matrix multiply. Three inputs:
7115 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7116 /// - `w_packed`: `[N, K/2]` U8 (two 4-bit codes per byte)
7117 /// - `absmax`: `[N, K/block_size]` F32 (per-output-row, per-block)
7118 ///
7119 /// Output: `[..., M, N]` matching activations' dtype.
7120 ///
7121 /// `block_size` is the NF4 quantization block size (typically 64
7122 /// in bitsandbytes). `K` must be even AND a multiple of
7123 /// `block_size`.
7124 ///
7125 /// Emits `Op::Fused(FusedOps::NF4_MATMUL, FusedOpParams::Nf4Matmul
7126 /// { block_size })`. No primitive decomposition (the dequant +
7127 /// matmul roundtrip is exactly what NF4's fused dequant-in-kernel
7128 /// design avoids); backends without a native kernel fall through
7129 /// to the executor's cpu_fallback path.
7130 ///
7131 /// # Panics
7132 ///
7133 /// Panics if any operand belongs to a different [`Graph`] than the one this
7134 /// builder is building into. Operand identity is graph-scoped and checked by
7135 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7136 /// deliberate and replaces the hang a cross-graph handle used to produce.
7137 /// Build every operand from one graph, or use a `Result`-returning entry
7138 /// point where one exists.
7139 pub fn nf4_matmul(
7140 &self,
7141 w_packed: &NodeHandle,
7142 absmax: &NodeHandle,
7143 block_size: usize,
7144 ) -> NodeHandle {
7145 assert!(
7146 Arc::ptr_eq(&self.graph, &w_packed.graph) && Arc::ptr_eq(&self.graph, &absmax.graph),
7147 "nf4_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7148 );
7149 let act_dtype = self.dtype();
7150 assert!(
7151 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7152 "nf4_matmul v1: activations must be F32/F16/BF16, got {:?}",
7153 act_dtype,
7154 );
7155 assert_eq!(
7156 w_packed.dtype(),
7157 DType::U8,
7158 "nf4_matmul: w_packed must be U8 (two 4-bit codes per byte), got {:?}",
7159 w_packed.dtype(),
7160 );
7161 assert_eq!(
7162 absmax.dtype(),
7163 DType::F32,
7164 "nf4_matmul: absmax must be F32, got {:?}",
7165 absmax.dtype(),
7166 );
7167 let a_dims = self.shape();
7168 let a_dims = a_dims.dims();
7169 let w_dims = w_packed.shape();
7170 let w_dims = w_dims.dims();
7171 let abs_dims = absmax.shape();
7172 let abs_dims = abs_dims.dims();
7173 assert!(
7174 a_dims.len() >= 2,
7175 "nf4_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7176 );
7177 assert_eq!(
7178 w_dims.len(),
7179 2,
7180 "nf4_matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
7181 );
7182 assert_eq!(
7183 abs_dims.len(),
7184 2,
7185 "nf4_matmul: absmax must be rank 2 [n, k/block_size], got {abs_dims:?}",
7186 );
7187 let _m = a_dims[a_dims.len() - 2];
7188 let k = a_dims[a_dims.len() - 1];
7189 let n = w_dims[0];
7190 assert!(
7191 k.is_multiple_of(2),
7192 "nf4_matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
7193 );
7194 assert!(
7195 block_size > 0 && k.is_multiple_of(block_size),
7196 "nf4_matmul: k={k} must be a positive multiple of block_size={block_size}",
7197 );
7198 assert_eq!(
7199 w_dims[1],
7200 k / 2,
7201 "nf4_matmul: w_packed second dim {} must equal k/2 = {}",
7202 w_dims[1],
7203 k / 2,
7204 );
7205 assert_eq!(
7206 abs_dims,
7207 &[n, k / block_size][..],
7208 "nf4_matmul: absmax {abs_dims:?} must be [n={n}, k/block_size={}]",
7209 k / block_size,
7210 );
7211 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7212 out_dims.push(n);
7213 let id = self.graph.write().unwrap().push(Node {
7214 op: Op::Fused(
7215 crate::registry::FusedOps::NF4_MATMUL,
7216 crate::registry::FusedOpParams::Nf4Matmul { block_size },
7217 ),
7218 inputs: vec![self.id, w_packed.id, absmax.id],
7219 shape: Shape::from_dims(&out_dims),
7220 dtype: act_dtype,
7221 });
7222 Self {
7223 graph: self.graph.clone(),
7224 id,
7225 }
7226 }
7227
7228 /// Append an `AwqMatmul` node — AWQ (mit-han-lab) asymmetric int4
7229 /// weight-only matrix multiply. Four inputs, the quantized three in the
7230 /// baracuda W4A16 kernel layout (OC-major; see
7231 /// [`crate::registry::awq_matmul`]):
7232 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7233 /// - `weight`: `[N, K/8]` U32 (eight int4 codes per word, sequential
7234 /// nibble order)
7235 /// - `zeros`: `[N, zeros_w]` U32 (group `g`'s zero-point is nibble
7236 /// `g % 8` of word `g / 8`), `zeros_w =`
7237 /// [`crate::registry::awq_matmul::awq_zeros_w`]`(K, group_size)`
7238 /// - `scales`: `[N, 8 * zeros_w]` F16 (entry `g` is group `g`'s scale)
7239 ///
7240 /// Output: `[..., M, N]` matching activations' dtype.
7241 ///
7242 /// `group_size` must be 64 or 128 and evenly divide `K`; `K` must be a
7243 /// multiple of 8. `split_k_iters` is a CUDA launch-tuning parameter the
7244 /// decompose path ignores.
7245 /// `fuel_quantized::awq_repack::repack_hf_awq_for_kernel` produces the
7246 /// three quantized operands from a HuggingFace `*-AWQ` checkpoint.
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 weight: &NodeHandle,
7259 zeros: &NodeHandle,
7260 scales: &NodeHandle,
7261 group_size: usize,
7262 split_k_iters: i32,
7263 ) -> NodeHandle {
7264 assert!(
7265 Arc::ptr_eq(&self.graph, &weight.graph)
7266 && Arc::ptr_eq(&self.graph, &zeros.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 weight.dtype(),
7278 DType::U32,
7279 "awq_matmul: weight must be U32 (eight 4-bit codes per word), got {:?}",
7280 weight.dtype(),
7281 );
7282 assert_eq!(
7283 zeros.dtype(),
7284 DType::U32,
7285 "awq_matmul: zeros must be U32 (eight 4-bit codes per word), got {:?}",
7286 zeros.dtype(),
7287 );
7288 assert_eq!(
7289 scales.dtype(),
7290 DType::F16,
7291 "awq_matmul: scales must be F16, got {:?}",
7292 scales.dtype(),
7293 );
7294 let a_dims = self.shape();
7295 let a_dims = a_dims.dims();
7296 let w_dims = weight.shape();
7297 let w_dims = w_dims.dims();
7298 let z_dims = zeros.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: weight must be rank 2 [N, K/8], got {w_dims:?}",
7310 );
7311 assert_eq!(
7312 z_dims.len(),
7313 2,
7314 "awq_matmul: zeros must be rank 2 [N, zeros_w], got {z_dims:?}",
7315 );
7316 assert_eq!(
7317 s_dims.len(),
7318 2,
7319 "awq_matmul: scales must be rank 2 [N, 8 * zeros_w], got {s_dims:?}",
7320 );
7321 let k = a_dims[a_dims.len() - 1];
7322 let n = w_dims[0];
7323 assert!(
7324 k.is_multiple_of(8),
7325 "awq_matmul: k={k} must be a multiple of 8 (weight packs 8 codes per word along k)",
7326 );
7327 let Some(zeros_w) = crate::registry::awq_matmul::awq_zeros_w(k, group_size) else {
7328 panic!("awq_matmul: group_size={group_size} must be 64 or 128 and divide k={k}");
7329 };
7330 assert_eq!(
7331 w_dims[1],
7332 k / 8,
7333 "awq_matmul: weight second dim {} must equal k/8 = {}",
7334 w_dims[1],
7335 k / 8,
7336 );
7337 assert_eq!(
7338 z_dims,
7339 &[n, zeros_w][..],
7340 "awq_matmul: zeros {z_dims:?} must be [n={n}, zeros_w={zeros_w}]",
7341 );
7342 assert_eq!(
7343 s_dims,
7344 &[n, 8 * zeros_w][..],
7345 "awq_matmul: scales {s_dims:?} must be [n={n}, 8 * zeros_w={}]",
7346 8 * zeros_w,
7347 );
7348 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7349 out_dims.push(n);
7350 let id = self.graph.write().unwrap().push(Node {
7351 op: Op::Fused(
7352 crate::registry::FusedOps::AWQ_MATMUL,
7353 crate::registry::FusedOpParams::AwqMatmul {
7354 group_size,
7355 split_k_iters,
7356 },
7357 ),
7358 inputs: vec![self.id, weight.id, zeros.id, scales.id],
7359 shape: Shape::from_dims(&out_dims),
7360 dtype: act_dtype,
7361 });
7362 Self {
7363 graph: self.graph.clone(),
7364 id,
7365 }
7366 }
7367
7368 /// Append an `SsdChunkScan` node — Mamba-2's State-Space
7369 /// Duality chunked scan (forward). Five inputs:
7370 /// - `self` (x): `[batch, seqlen, heads, head_dim]` F32
7371 /// - `dt`: `[batch, seqlen, heads]` F32
7372 /// - `a`: `[heads]` F32 (per-head scalar log A)
7373 /// - `b`: `[batch, seqlen, heads, state_dim]` F32
7374 /// - `c`: `[batch, seqlen, heads, state_dim]` F32
7375 ///
7376 /// Output: `y: [batch, seqlen, heads, head_dim]` F32 (same as x).
7377 ///
7378 /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
7379 /// It controls GPU parallelism granularity but the mathematical
7380 /// result is identical to a sequential scan; the CPU kernel runs
7381 /// sequential regardless. Validation: `chunk_size > 0` and
7382 /// `seqlen % chunk_size == 0`.
7383 ///
7384 /// Emits `Op::Fused(FusedOps::SSD_CHUNK_SCAN,
7385 /// FusedOpParams::SsdChunkScan { chunk_size })`. No primitive
7386 /// decomposition; backends without a native kernel fall through
7387 /// to the executor's cpu_fallback path.
7388 /// Internal: build the bundled SsdChunkScan producer node and
7389 /// return its NodeId. Callers project per-slot via
7390 /// [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7391 fn ssd_chunk_scan_producer(
7392 &self,
7393 dt: &NodeHandle,
7394 a: &NodeHandle,
7395 b: &NodeHandle,
7396 c: &NodeHandle,
7397 chunk_size: usize,
7398 ) -> NodeHandle {
7399 assert!(
7400 Arc::ptr_eq(&self.graph, &dt.graph)
7401 && Arc::ptr_eq(&self.graph, &a.graph)
7402 && Arc::ptr_eq(&self.graph, &b.graph)
7403 && Arc::ptr_eq(&self.graph, &c.graph),
7404 "ssd_chunk_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7405 );
7406 let dtype = self.dtype();
7407 assert!(
7408 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7409 "ssd_chunk_scan: x must be F32/F64/BF16/F16, got {dtype:?}",
7410 );
7411 for (name, t) in [("dt", dt), ("a", a), ("b", b), ("c", c)] {
7412 assert_eq!(
7413 t.dtype(),
7414 dtype,
7415 "ssd_chunk_scan: {name} dtype {:?} must match x dtype {dtype:?}",
7416 t.dtype(),
7417 );
7418 }
7419 let x_dims = self.shape();
7420 let x_dims = x_dims.dims();
7421 let dt_dims = dt.shape();
7422 let dt_dims = dt_dims.dims();
7423 let a_dims = a.shape();
7424 let a_dims = a_dims.dims();
7425 let b_dims = b.shape();
7426 let b_dims = b_dims.dims();
7427 let c_dims = c.shape();
7428 let c_dims = c_dims.dims();
7429 assert_eq!(
7430 x_dims.len(),
7431 4,
7432 "ssd_chunk_scan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
7433 );
7434 let batch = x_dims[0];
7435 let seqlen = x_dims[1];
7436 let heads = x_dims[2];
7437 let head_dim = x_dims[3];
7438 assert_eq!(
7439 dt_dims,
7440 &[batch, seqlen, heads][..],
7441 "ssd_chunk_scan: dt {dt_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}]",
7442 );
7443 assert_eq!(
7444 a_dims,
7445 &[heads][..],
7446 "ssd_chunk_scan: a {a_dims:?} must be [heads={heads}]",
7447 );
7448 assert_eq!(
7449 b_dims.len(),
7450 4,
7451 "ssd_chunk_scan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
7452 );
7453 let state_dim = b_dims[3];
7454 assert_eq!(
7455 b_dims,
7456 &[batch, seqlen, heads, state_dim][..],
7457 "ssd_chunk_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}, state_dim={state_dim}]",
7458 );
7459 assert_eq!(
7460 c_dims,
7461 &[batch, seqlen, heads, state_dim][..],
7462 "ssd_chunk_scan: c {c_dims:?} must match b shape",
7463 );
7464 let params = crate::registry::FusedOpParams::SsdChunkScan { chunk_size };
7465 let input_shapes = [
7466 Shape::from_dims(x_dims),
7467 Shape::from_dims(dt_dims),
7468 Shape::from_dims(a_dims),
7469 Shape::from_dims(b_dims),
7470 Shape::from_dims(c_dims),
7471 ];
7472 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7473 let entry = crate::registry::default_registry()
7474 .entry(crate::registry::FusedOps::SSD_CHUNK_SCAN)
7475 .expect("SSD_CHUNK_SCAN registered");
7476 let specs =
7477 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7478 let (_total_bytes, views) =
7479 fuel_ir::storage::compose_bundle(&specs).expect("SsdChunkScan compose_bundle");
7480 let mut g = self.graph.write().unwrap();
7481 let id = g.push(Node {
7482 op: Op::Fused(crate::registry::FusedOps::SSD_CHUNK_SCAN, params),
7483 inputs: vec![self.id, dt.id, a.id, b.id, c.id],
7484 shape: Shape::from_dims(&[batch, seqlen, heads, head_dim]),
7485 dtype,
7486 });
7487 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7488 .expect("SsdChunkScan set_output_views");
7489 drop(g);
7490 Self {
7491 graph: self.graph.clone(),
7492 id,
7493 }
7494 }
7495
7496 /// Single-output SsdChunkScan: returns the `y` slot of the
7497 /// bundled producer (View(0)). See
7498 /// [`Self::ssd_chunk_scan_bundled`] for the multi-output variant.
7499 ///
7500 /// # Panics
7501 ///
7502 /// Panics if any operand belongs to a different [`Graph`] than the one this
7503 /// builder is building into. Operand identity is graph-scoped and checked by
7504 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7505 /// deliberate and replaces the hang a cross-graph handle used to produce.
7506 /// Build every operand from one graph, or use a `Result`-returning entry
7507 /// point where one exists.
7508 pub fn ssd_chunk_scan(
7509 &self,
7510 dt: &NodeHandle,
7511 a: &NodeHandle,
7512 b: &NodeHandle,
7513 c: &NodeHandle,
7514 chunk_size: usize,
7515 ) -> NodeHandle {
7516 self.assert_same_graph(dt, "ssd_chunk_scan", "dt");
7517 self.assert_same_graph(a, "ssd_chunk_scan", "a");
7518 self.assert_same_graph(b, "ssd_chunk_scan", "b");
7519 self.assert_same_graph(c, "ssd_chunk_scan", "c");
7520 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7521 producer
7522 .view(0)
7523 .expect("SsdChunkScan view(0) must succeed (just registered slots)")
7524 }
7525
7526 /// Append a `SelectiveScan` node — Mamba-1's selective
7527 /// state-space scan (forward). Five inputs:
7528 /// - `self` (u): `[batch, seqlen, dim]` F32
7529 /// - `delta`: `[batch, seqlen, dim]` F32
7530 /// - `a`: `[dim, dstate]` F32
7531 /// - `b`: `[batch, seqlen, dstate]` F32
7532 /// - `c`: `[batch, seqlen, dstate]` F32
7533 ///
7534 /// Output: `y: [batch, seqlen, dim]` F32.
7535 ///
7536 /// `delta_softplus` toggles the softplus(delta) activation before
7537 /// use (matches baracuda's `selective_scan_*_run` flag). The v1
7538 /// op surface skips the optional `d_skip`, `z`, `delta_bias`
7539 /// inputs and the `last_state` second output — see
7540 /// `fuel-graph/src/registry/selective_scan.rs` for the rationale.
7541 ///
7542 /// Emits `Op::Fused(FusedOps::SELECTIVE_SCAN,
7543 /// FusedOpParams::SelectiveScan { delta_softplus })`. No
7544 /// primitive decomposition exists (the scan is a sequential
7545 /// recurrence); backends without a native kernel fall through to
7546 /// the executor's cpu_fallback path.
7547 /// Internal: build the bundled SelectiveScan producer node and
7548 /// return its NodeId (wrapped in a `NodeHandle`). Callers project
7549 /// per-slot via [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7550 fn selective_scan_producer(
7551 &self,
7552 delta: &NodeHandle,
7553 a: &NodeHandle,
7554 b: &NodeHandle,
7555 c: &NodeHandle,
7556 delta_softplus: bool,
7557 ) -> NodeHandle {
7558 assert!(
7559 Arc::ptr_eq(&self.graph, &delta.graph)
7560 && Arc::ptr_eq(&self.graph, &a.graph)
7561 && Arc::ptr_eq(&self.graph, &b.graph)
7562 && Arc::ptr_eq(&self.graph, &c.graph),
7563 "selective_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7564 );
7565 let dtype = self.dtype();
7566 assert!(
7567 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7568 "selective_scan: u must be F32/F64/BF16/F16, got {dtype:?}",
7569 );
7570 for (name, t) in [("delta", delta), ("a", a), ("b", b), ("c", c)] {
7571 assert_eq!(
7572 t.dtype(),
7573 dtype,
7574 "selective_scan: {name} dtype {:?} must match u dtype {dtype:?}",
7575 t.dtype(),
7576 );
7577 }
7578 let u_dims = self.shape();
7579 let u_dims = u_dims.dims();
7580 let delta_dims = delta.shape();
7581 let delta_dims = delta_dims.dims();
7582 let a_dims = a.shape();
7583 let a_dims = a_dims.dims();
7584 let b_dims = b.shape();
7585 let b_dims = b_dims.dims();
7586 let c_dims = c.shape();
7587 let c_dims = c_dims.dims();
7588 assert_eq!(
7589 u_dims.len(),
7590 3,
7591 "selective_scan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
7592 );
7593 assert_eq!(
7594 delta_dims, u_dims,
7595 "selective_scan: delta {delta_dims:?} must match u {u_dims:?}",
7596 );
7597 assert_eq!(
7598 a_dims.len(),
7599 2,
7600 "selective_scan: a must be rank 2 [dim, dstate], got {a_dims:?}",
7601 );
7602 let batch = u_dims[0];
7603 let seqlen = u_dims[1];
7604 let dim = u_dims[2];
7605 let dstate = a_dims[1];
7606 assert_eq!(
7607 a_dims[0], dim,
7608 "selective_scan: a's first dim {} must equal dim {dim}",
7609 a_dims[0],
7610 );
7611 assert_eq!(
7612 b_dims,
7613 &[batch, seqlen, dstate][..],
7614 "selective_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7615 );
7616 assert_eq!(
7617 c_dims,
7618 &[batch, seqlen, dstate][..],
7619 "selective_scan: c {c_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7620 );
7621 let params = crate::registry::FusedOpParams::SelectiveScan { delta_softplus };
7622 let input_shapes = [
7623 Shape::from_dims(u_dims),
7624 Shape::from_dims(delta_dims),
7625 Shape::from_dims(a_dims),
7626 Shape::from_dims(b_dims),
7627 Shape::from_dims(c_dims),
7628 ];
7629 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7630 let entry = crate::registry::default_registry()
7631 .entry(crate::registry::FusedOps::SELECTIVE_SCAN)
7632 .expect("SELECTIVE_SCAN registered");
7633 let specs =
7634 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7635 let (_total_bytes, views) =
7636 fuel_ir::storage::compose_bundle(&specs).expect("SelectiveScan compose_bundle");
7637 let mut g = self.graph.write().unwrap();
7638 let id = g.push(Node {
7639 op: Op::Fused(crate::registry::FusedOps::SELECTIVE_SCAN, params),
7640 inputs: vec![self.id, delta.id, a.id, b.id, c.id],
7641 shape: Shape::from_dims(&[batch, seqlen, dim]),
7642 dtype,
7643 });
7644 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7645 .expect("SelectiveScan set_output_views");
7646 drop(g);
7647 Self {
7648 graph: self.graph.clone(),
7649 id,
7650 }
7651 }
7652
7653 /// Single-output SelectiveScan: returns the `y` slot of the
7654 /// bundled producer, with the View(0) projection emitted so
7655 /// callers can downstream-realize / copy / etc. transparently.
7656 /// See [`Self::selective_scan_bundled`] for the multi-output
7657 /// variant that also exposes `last_state` for autoregressive
7658 /// resumption.
7659 ///
7660 /// # Panics
7661 ///
7662 /// Panics if any operand belongs to a different [`Graph`] than the one this
7663 /// builder is building into. Operand identity is graph-scoped and checked by
7664 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7665 /// deliberate and replaces the hang a cross-graph handle used to produce.
7666 /// Build every operand from one graph, or use a `Result`-returning entry
7667 /// point where one exists.
7668 pub fn selective_scan(
7669 &self,
7670 delta: &NodeHandle,
7671 a: &NodeHandle,
7672 b: &NodeHandle,
7673 c: &NodeHandle,
7674 delta_softplus: bool,
7675 ) -> NodeHandle {
7676 self.assert_same_graph(delta, "selective_scan", "delta");
7677 self.assert_same_graph(a, "selective_scan", "a");
7678 self.assert_same_graph(b, "selective_scan", "b");
7679 self.assert_same_graph(c, "selective_scan", "c");
7680 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7681 producer
7682 .view(0)
7683 .expect("SelectiveScan view(0) must succeed (just registered slots)")
7684 }
7685
7686 /// Multi-output variant of [`Self::selective_scan`]. Returns
7687 /// `(y, last_state)` — both Op::View tensors projected from the
7688 /// shared bundled producer. `y` matches the existing
7689 /// single-output `selective_scan` shape; `last_state` is the
7690 /// final hidden state `[batch, dim, dstate]` for autoregressive
7691 /// resumption.
7692 pub fn selective_scan_bundled(
7693 &self,
7694 delta: &NodeHandle,
7695 a: &NodeHandle,
7696 b: &NodeHandle,
7697 c: &NodeHandle,
7698 delta_softplus: bool,
7699 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7700 self.require_same_graph(delta, "selective_scan_bundled", "delta")?;
7701 self.require_same_graph(a, "selective_scan_bundled", "a")?;
7702 self.require_same_graph(b, "selective_scan_bundled", "b")?;
7703 self.require_same_graph(c, "selective_scan_bundled", "c")?;
7704 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7705 let y = producer.view(0)?;
7706 let last_state = producer.view(1)?;
7707 Ok((y, last_state))
7708 }
7709
7710 /// Multi-output variant of [`Self::ssd_chunk_scan`]. Returns
7711 /// `(y, last_state)`.
7712 pub fn ssd_chunk_scan_bundled(
7713 &self,
7714 dt: &NodeHandle,
7715 a: &NodeHandle,
7716 b: &NodeHandle,
7717 c: &NodeHandle,
7718 chunk_size: usize,
7719 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7720 self.require_same_graph(dt, "ssd_chunk_scan_bundled", "dt")?;
7721 self.require_same_graph(a, "ssd_chunk_scan_bundled", "a")?;
7722 self.require_same_graph(b, "ssd_chunk_scan_bundled", "b")?;
7723 self.require_same_graph(c, "ssd_chunk_scan_bundled", "c")?;
7724 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7725 let y = producer.view(0)?;
7726 let last_state = producer.view(1)?;
7727 Ok((y, last_state))
7728 }
7729
7730 /// Append an [`Op::NonZeroIndices`] producer node — the keystone
7731 /// primitive for **data-dependent dynamic shapes**. Returns the
7732 /// bundled producer `NodeHandle` (a `[capacity]` U32 tensor); callers
7733 /// usually want [`Self::nonzero_indices_bundled`] to also get the
7734 /// runtime count slot.
7735 ///
7736 /// `capacity = self.elem_count()` is the static worst-case bound
7737 /// (every element nonzero). `count_sym` is the [`SymId`] the executor
7738 /// binds to the realized nonzero count in the per-pass `SymEnv`; the
7739 /// caller allocates it from their `SymGen` and threads it into any
7740 /// downstream op that consumes the count as a dynamic extent /
7741 /// `DynScalar::Sym` (the KV-cache `cached_len` pattern, generalized to
7742 /// a data-determined count).
7743 pub fn nonzero_indices_producer(&self, count_sym: SymId) -> NodeHandle {
7744 let capacity = self.shape().elem_count();
7745 let indices_shape = Shape::from_dims(&[capacity]);
7746 let count_shape = Shape::from_dims(&[1]);
7747 let specs = vec![
7748 fuel_ir::storage::OutputViewSpec {
7749 dtype: DType::U32,
7750 shape: indices_shape.clone(),
7751 layout: Layout::contiguous(indices_shape.clone()),
7752 name: Some("indices"),
7753 },
7754 fuel_ir::storage::OutputViewSpec {
7755 dtype: DType::U32,
7756 shape: count_shape.clone(),
7757 layout: Layout::contiguous(count_shape),
7758 name: Some("count"),
7759 },
7760 ];
7761 let (_total_bytes, views) =
7762 fuel_ir::storage::compose_bundle(&specs).expect("NonZeroIndices compose_bundle");
7763 let mut g = self.graph.write().unwrap();
7764 let id = g.push(Node {
7765 op: Op::NonZeroIndices { count_sym },
7766 inputs: vec![self.id],
7767 shape: indices_shape,
7768 dtype: DType::U32,
7769 });
7770 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7771 .expect("NonZeroIndices set_output_views");
7772 drop(g);
7773 Self {
7774 graph: self.graph.clone(),
7775 id,
7776 }
7777 }
7778
7779 /// Multi-output [`Op::NonZeroIndices`]: returns `(indices, count)` —
7780 /// both `Op::View` projections of the shared bundled producer.
7781 /// `indices` is `[capacity]` U32 (first `count` entries valid, in
7782 /// ascending flat order); `count` is `[1]` U32, the runtime nonzero
7783 /// count. The executor also publishes `count`'s value into the
7784 /// per-pass `SymEnv` under the producer's `count_sym`.
7785 pub fn nonzero_indices_bundled(
7786 &self,
7787 count_sym: SymId,
7788 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7789 let producer = self.nonzero_indices_producer(count_sym);
7790 let indices = producer.view(0)?;
7791 let count = producer.view(1)?;
7792 Ok((indices, count))
7793 }
7794
7795 /// Append a `FusedSoftmaxCrossEntropy` node. Two inputs:
7796 /// - `self` (logits): `[..., V]` F32 / F64 / BF16 / F16
7797 /// - `targets`: `[...]` I64 (class indices; matches PyTorch /
7798 /// baracuda convention)
7799 ///
7800 /// Output dtype is always F32 (the FSCE declared dtype — losses
7801 /// accumulate in F64 and narrow to F32, matching PyTorch and the
7802 /// baracuda kernel) regardless of the logits dtype. Output shape
7803 /// depends on `reduction`:
7804 /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
7805 /// - `Reduction::None` → same as `targets.shape`
7806 ///
7807 /// `ignore_index` rows are dropped from the loss accumulator and
7808 /// the Mean denominator. The conventional sentinel is `-100`.
7809 ///
7810 /// Emits `Op::Fused(FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7811 /// FusedOpParams::FusedSoftmaxCrossEntropy { reduction, ignore_index })`.
7812 /// See `fuel-graph/src/registry/fused_softmax_cross_entropy.rs` for
7813 /// the registry entry and decompose chain.
7814 ///
7815 /// # Panics
7816 ///
7817 /// Panics if any operand belongs to a different [`Graph`] than the one this
7818 /// builder is building into. Operand identity is graph-scoped and checked by
7819 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7820 /// deliberate and replaces the hang a cross-graph handle used to produce.
7821 /// Build every operand from one graph, or use a `Result`-returning entry
7822 /// point where one exists.
7823 pub fn fused_softmax_cross_entropy(
7824 &self,
7825 targets: &NodeHandle,
7826 reduction: crate::registry::Reduction,
7827 ignore_index: i64,
7828 ) -> NodeHandle {
7829 assert!(
7830 Arc::ptr_eq(&self.graph, &targets.graph),
7831 "fused_softmax_cross_entropy: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7832 );
7833 assert!(
7834 matches!(
7835 self.dtype(),
7836 DType::F32 | DType::F64 | DType::BF16 | DType::F16,
7837 ),
7838 "fused_softmax_cross_entropy: logits must be F32/F64/BF16/F16, got {:?}",
7839 self.dtype(),
7840 );
7841 assert_eq!(
7842 targets.dtype(),
7843 DType::I64,
7844 "fused_softmax_cross_entropy: targets must be I64, got {:?}",
7845 targets.dtype(),
7846 );
7847 let logits_dims = self.shape();
7848 let logits_dims = logits_dims.dims();
7849 assert!(
7850 !logits_dims.is_empty(),
7851 "fused_softmax_cross_entropy: logits must have rank ≥ 1",
7852 );
7853 let target_dims = targets.shape();
7854 let target_dims = target_dims.dims();
7855 assert_eq!(
7856 target_dims,
7857 &logits_dims[..logits_dims.len() - 1],
7858 "fused_softmax_cross_entropy: targets shape {target_dims:?} must equal \
7859 logits shape {logits_dims:?} minus the last dim",
7860 );
7861 let out_shape = match reduction {
7862 crate::registry::Reduction::Mean | crate::registry::Reduction::Sum => {
7863 Shape::from_dims(&[])
7864 }
7865 crate::registry::Reduction::None => Shape::from_dims(target_dims),
7866 };
7867 let id = self.graph.write().unwrap().push(Node {
7868 op: Op::Fused(
7869 crate::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7870 crate::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
7871 reduction,
7872 ignore_index,
7873 },
7874 ),
7875 inputs: vec![self.id, targets.id],
7876 shape: out_shape,
7877 dtype: DType::F32,
7878 });
7879 Self {
7880 graph: self.graph.clone(),
7881 id,
7882 }
7883 }
7884
7885 /// Append a `LayerNormLastDim` node with the given epsilon. Shape is
7886 /// preserved.
7887 ///
7888 /// Phase 7.6 step 4 (continued): emits
7889 /// `Op::Fused(FusedOps::LAYER_NORM_LAST_DIM, FusedOpParams::LayerNormLastDim { eps })`
7890 /// through the registry-extended arm. The legacy
7891 /// `Op::LayerNormLastDim { eps }` variant remains in the enum
7892 /// during migration; step 5 drops it once nothing emits it.
7893 pub fn layer_norm_last_dim(&self, eps: f64) -> NodeHandle {
7894 let dims = self.shape();
7895 let d = dims.dims();
7896 assert!(
7897 !d.is_empty() && *d.last().unwrap() > 0,
7898 "layer_norm_last_dim: input must have a non-zero last dim, got {d:?}",
7899 );
7900 self.unary_op(Op::Fused(
7901 crate::registry::FusedOps::LAYER_NORM_LAST_DIM,
7902 crate::registry::FusedOpParams::LayerNormLastDim { eps },
7903 ))
7904 }
7905
7906 /// Apply rotary position embeddings (RoPE) to `self`. The input is
7907 /// expected to have shape `[..., seq, d]` where `seq` is the
7908 /// sequence length and `d` is the per-head feature dim (which must
7909 /// be even). `base` is the frequency base — 10000.0 for LLaMA.
7910 /// `start_pos` lets callers apply RoPE at a non-zero offset, which
7911 /// is what KV-cached inference does when the query for position
7912 /// `n + k` is processed against a cache that already holds
7913 /// positions `0..n+k`.
7914 ///
7915 /// Uses the half-split layout (the one LLaMA and HuggingFace use):
7916 /// pair feature `i` with feature `i + d/2`. Under that layout the
7917 /// rotation reduces to the identity `x' = x·cos + rotate_half(x)·sin`
7918 /// where `rotate_half(x)` concatenates `[-x[d/2:], x[:d/2]]` along
7919 /// the last dim.
7920 ///
7921 /// Implemented as a composition of existing graph primitives —
7922 /// `Slice`, `Neg`, `Concat`, `Reshape`, `BroadcastTo`, `Mul`, `Add`
7923 /// — plus two precomputed `Const` tensors for the cos/sin frequency
7924 /// tables. Every primitive already has a working backward rule, so
7925 /// gradients flow through RoPE without any new backward machinery.
7926 ///
7927 /// Only `f32` is supported today. Extending to other float dtypes
7928 /// is mechanical: build the frequency tables in the target dtype.
7929 pub fn rope(&self, base: f64, start_pos: usize) -> NodeHandle {
7930 let (seq, d) = {
7931 let dims = self.shape();
7932 let v = dims.dims();
7933 let rank = v.len();
7934 assert!(rank >= 2, "rope: input must have rank ≥ 2");
7935 (v[rank - 2], v[rank - 1])
7936 };
7937 let (cos, sin) = build_rope_tables(base, start_pos, seq, d);
7938 // Phase 7.5 G2: const_*_like derives the device from self's
7939 // graph internally — RoPE tables go on the same device as self.
7940 // ⚠️ GAP-003 category 2, in production: the proof EXISTS but is NOT
7941 // LOCAL -- `build_rope_tables` owns the length guarantee and its
7942 // signature `-> (Vec<f32>, Vec<f32>)` does not carry it. So the message
7943 // claims NO proof; it names where the guarantee lives. `rope` returns
7944 // `NodeHandle` and already asserts on rank, so giving it an error
7945 // channel is a signature change -- a different obligation. See #157.
7946 let cos_t = self
7947 .const_f32_like(cos, Shape::from_dims(&[seq, d]))
7948 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7949 let sin_t = self
7950 .const_f32_like(sin, Shape::from_dims(&[seq, d]))
7951 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7952 self.rope_with_tables(&cos_t, &sin_t)
7953 }
7954
7955 /// Apply RoPE using caller-supplied `cos` and `sin` tables. Each
7956 /// table has shape `[seq, head_dim]` and matches the layout
7957 /// [`build_rope_tables`] produces. This is the hot-path entry
7958 /// point: in a transformer forward pass every attention layer
7959 /// applies RoPE to Q and K with the *same* `(start_pos, seq,
7960 /// head_dim)`, so the caller can build the tables once and share
7961 /// the const nodes across all layers rather than re-duplicating
7962 /// them inside each `.rope()` call. The classic [`Self::rope`] entry
7963 /// point funnels through this after building the tables itself.
7964 ///
7965 /// # Panics
7966 ///
7967 /// Panics if any operand belongs to a different [`Graph`] than the one this
7968 /// builder is building into. Operand identity is graph-scoped and checked by
7969 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7970 /// deliberate and replaces the hang a cross-graph handle used to produce.
7971 /// Build every operand from one graph, or use a `Result`-returning entry
7972 /// point where one exists.
7973 pub fn rope_with_tables(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
7974 self.assert_same_graph(cos, "rope_with_tables", "cos");
7975 self.assert_same_graph(sin, "rope_with_tables", "sin");
7976 assert_eq!(
7977 self.dtype(),
7978 DType::F32,
7979 "rope: only f32 is supported today (cast explicitly for other dtypes)",
7980 );
7981 let in_shape = self.shape();
7982 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
7983 let rank = dims_vec.len();
7984 assert!(
7985 rank >= 2,
7986 "rope: input must have rank ≥ 2, got {dims_vec:?}"
7987 );
7988 let seq = dims_vec[rank - 2];
7989 let d = dims_vec[rank - 1];
7990 assert!(d.is_multiple_of(2), "rope: feature dim {d} must be even",);
7991 let cos_shape = cos.shape();
7992 let sin_shape = sin.shape();
7993 assert_eq!(
7994 cos_shape.dims(),
7995 &[seq, d],
7996 "rope_with_tables: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
7997 cos_shape.dims(),
7998 );
7999 assert_eq!(
8000 sin_shape.dims(),
8001 &[seq, d],
8002 "rope_with_tables: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
8003 sin_shape.dims(),
8004 );
8005 let _ = rank;
8006 // Emit a single fused Rope node. The decomposed version
8007 // (slice+neg+concat+broadcast+mul+add) produces ~72 dispatches
8008 // on GPU backends because concat-along-last-dim has a per-row
8009 // host loop. Fused path dispatches once.
8010 //
8011 // Phase 7.6 step 4 (continued): emits
8012 // `Op::Fused(FusedOps::ROPE, FusedOpParams::Rope)` through the
8013 // registry-extended arm. The legacy `Op::Rope` variant remains
8014 // in the enum during migration; step 5 drops it once nothing
8015 // emits it.
8016 let out_shape = in_shape.clone();
8017 let dtype = self.dtype();
8018 let id = self.graph.write().unwrap().push(Node {
8019 op: Op::Fused(
8020 crate::registry::FusedOps::ROPE,
8021 crate::registry::FusedOpParams::Rope,
8022 ),
8023 inputs: vec![self.id, cos.id, sin.id],
8024 shape: out_shape,
8025 dtype,
8026 });
8027 Self {
8028 graph: self.graph.clone(),
8029 id,
8030 }
8031 }
8032
8033 /// The pre-fused decomposition of `rope_with_tables`. Retained so
8034 /// backends without a native `Op::Rope` kernel can synthesize from
8035 /// primitives, and so correctness tests can cross-check the fused
8036 /// path against the primitive path.
8037 ///
8038 /// # Panics
8039 ///
8040 /// Panics if any operand belongs to a different [`Graph`] than the one this
8041 /// builder is building into. Operand identity is graph-scoped and checked by
8042 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8043 /// deliberate and replaces the hang a cross-graph handle used to produce.
8044 /// Build every operand from one graph, or use a `Result`-returning entry
8045 /// point where one exists.
8046 #[doc(hidden)]
8047 pub fn rope_with_tables_decomposed(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8048 self.assert_same_graph(cos, "rope_with_tables_decomposed", "cos");
8049 self.assert_same_graph(sin, "rope_with_tables_decomposed", "sin");
8050 let in_shape = self.shape();
8051 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8052 let rank = dims_vec.len();
8053 let seq = dims_vec[rank - 2];
8054 let d = dims_vec[rank - 1];
8055 let half = d / 2;
8056
8057 let mut broadcast_shape: Vec<usize> = vec![1_usize; rank];
8058 broadcast_shape[rank - 2] = seq;
8059 broadcast_shape[rank - 1] = d;
8060 let cos_reshaped = cos.reshape(Shape::from_dims(&broadcast_shape));
8061 let sin_reshaped = sin.reshape(Shape::from_dims(&broadcast_shape));
8062 let cos_bcast = cos_reshaped.broadcast_to(in_shape.clone());
8063 let sin_bcast = sin_reshaped.broadcast_to(in_shape);
8064
8065 let first_half = self.slice(rank - 1, 0, half);
8066 let second_half = self.slice(rank - 1, half, half);
8067 let neg_second = second_half.neg();
8068 let rotated_half = neg_second.concat(&first_half, rank - 1);
8069
8070 let left = self.mul(&cos_bcast);
8071 let right = rotated_half.mul(&sin_bcast);
8072 left.add(&right)
8073 }
8074
8075 /// Root-Mean-Square Normalization along the last dim, without
8076 /// affine parameters. `y = x / sqrt(mean(x², last) + eps)`.
8077 ///
8078 /// This is the normalization layer used by LLaMA-family models.
8079 /// Unlike LayerNorm, RmsNorm does not subtract the mean — it only
8080 /// divides by the root-mean-square, which is both cheaper and
8081 /// empirically just as effective in transformer blocks.
8082 ///
8083 /// Emits a fused RmsNormLastDim node. Backends that have a native
8084 /// implementation dispatch it as one kernel; ones that don't get a
8085 /// CPU fallback via the reference implementation.
8086 ///
8087 /// Phase 7.6 step 4 (continued): emits
8088 /// `Op::Fused(FusedOps::RMS_NORM_LAST_DIM, FusedOpParams::RmsNormLastDim { eps })`
8089 /// through the registry-extended arm. The legacy
8090 /// `Op::RmsNormLastDim { eps }` variant remains in the enum during
8091 /// migration; step 5 drops it once nothing emits it.
8092 ///
8093 /// Use [`rms_norm_last_dim_decomposed`](Self::rms_norm_last_dim_decomposed)
8094 /// instead if you need to differentiate through this op —
8095 /// backward through the fused op is not yet implemented.
8096 pub fn rms_norm_last_dim(&self, eps: f64) -> NodeHandle {
8097 let x_dims_vec: Vec<usize> = self.shape().dims().to_vec();
8098 assert!(
8099 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8100 "rms_norm_last_dim: input must have non-zero last dim, got {x_dims_vec:?}",
8101 );
8102 self.unary_op(Op::Fused(
8103 crate::registry::FusedOps::RMS_NORM_LAST_DIM,
8104 crate::registry::FusedOpParams::RmsNormLastDim { eps },
8105 ))
8106 }
8107
8108 /// Decomposed version — emits the (sqr → mean_dim → reshape →
8109 /// add_scalar → sqrt → broadcast_to → div) primitive chain. Has
8110 /// working backward rules through its primitive subgraph. Use
8111 /// this when you need to differentiate through RMSNorm; use
8112 /// [`rms_norm_last_dim`](Self::rms_norm_last_dim) for inference.
8113 pub fn rms_norm_last_dim_decomposed(&self, eps: f64) -> NodeHandle {
8114 let x_shape = self.shape();
8115 let x_dims_vec: Vec<usize> = x_shape.dims().to_vec();
8116 assert!(
8117 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8118 "rms_norm_last_dim_decomposed: input must have non-zero last dim, got {x_dims_vec:?}",
8119 );
8120 let last = x_dims_vec.len() - 1;
8121 let mean_sq = self.sqr().mean_dim(last);
8122 let mut keepdim_dims = x_dims_vec.clone();
8123 keepdim_dims[last] = 1;
8124 let mean_sq_kd = mean_sq.reshape(Shape::from_dims(&keepdim_dims));
8125 let denom = mean_sq_kd.add_scalar(eps).sqrt();
8126 let denom_bcast = denom.broadcast_to(x_shape);
8127 self.div(&denom_bcast)
8128 }
8129
8130 // --- indexing ---
8131
8132 /// Append an `IndexSelect` node that picks slices from `self` along
8133 /// `dim` using a 1-D `u32` index tensor. The output has the same
8134 /// shape as `self` except dimension `dim` is replaced by
8135 /// `indices.shape()[0]`.
8136 ///
8137 /// # Panics
8138 ///
8139 /// Panics if any operand belongs to a different [`Graph`] than the one this
8140 /// builder is building into. Operand identity is graph-scoped and checked by
8141 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8142 /// deliberate and replaces the hang a cross-graph handle used to produce.
8143 /// Build every operand from one graph, or use a `Result`-returning entry
8144 /// point where one exists.
8145 pub fn index_select(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8146 assert!(
8147 Arc::ptr_eq(&self.graph, &indices.graph),
8148 "index_select: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8149 );
8150 assert_eq!(
8151 indices.dtype(),
8152 DType::U32,
8153 "index_select: index tensor must be U32, got {:?}",
8154 indices.dtype(),
8155 );
8156 let idx_dims = indices.shape();
8157 assert_eq!(
8158 idx_dims.dims().len(),
8159 1,
8160 "index_select: index tensor must be rank 1, got {:?}",
8161 idx_dims.dims(),
8162 );
8163 let data_dims = self.shape();
8164 assert!(
8165 dim < data_dims.dims().len(),
8166 "index_select: dim {dim} out of bounds for data shape {:?}",
8167 data_dims.dims(),
8168 );
8169 let op = Op::IndexSelect { dim };
8170 let (shape, dtype) = crate::shape::primitive_shape(
8171 &op,
8172 &[data_dims, idx_dims],
8173 &[self.dtype(), indices.dtype()],
8174 )
8175 .expect("index_select: shapes/dims validated above");
8176 let id = self.graph.write().unwrap().push(Node {
8177 op,
8178 inputs: vec![self.id, indices.id],
8179 shape,
8180 dtype,
8181 });
8182 Self {
8183 graph: self.graph.clone(),
8184 id,
8185 }
8186 }
8187
8188 /// Append a `Gather` node that performs an N-dimensional gather along
8189 /// `dim`. The `indices` tensor must be `U32` with the same rank as
8190 /// `self`. Output shape equals `indices.shape()`.
8191 ///
8192 /// # Panics
8193 ///
8194 /// Panics if any operand belongs to a different [`Graph`] than the one this
8195 /// builder is building into. Operand identity is graph-scoped and checked by
8196 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8197 /// deliberate and replaces the hang a cross-graph handle used to produce.
8198 /// Build every operand from one graph, or use a `Result`-returning entry
8199 /// point where one exists.
8200 pub fn gather(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8201 assert!(
8202 Arc::ptr_eq(&self.graph, &indices.graph),
8203 "gather: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8204 );
8205 assert_eq!(
8206 indices.dtype(),
8207 DType::U32,
8208 "gather: index tensor must be U32, got {:?}",
8209 indices.dtype(),
8210 );
8211 let data_rank = self.shape().dims().len();
8212 let idx_rank = indices.shape().dims().len();
8213 assert_eq!(
8214 data_rank, idx_rank,
8215 "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
8216 );
8217 assert!(
8218 dim < data_rank,
8219 "gather: dim {dim} out of bounds for rank {data_rank}",
8220 );
8221 let op = Op::Gather { dim };
8222 let (shape, dtype) = crate::shape::primitive_shape(
8223 &op,
8224 &[self.shape(), indices.shape()],
8225 &[self.dtype(), indices.dtype()],
8226 )
8227 .expect("gather: shapes/dims validated above");
8228 let id = self.graph.write().unwrap().push(Node {
8229 op,
8230 inputs: vec![self.id, indices.id],
8231 shape,
8232 dtype,
8233 });
8234 Self {
8235 graph: self.graph.clone(),
8236 id,
8237 }
8238 }
8239
8240 /// Append a `Concat` node joining `self` and `other` along `dim`.
8241 ///
8242 /// # Panics
8243 ///
8244 /// Panics if any operand belongs to a different [`Graph`] than the one this
8245 /// builder is building into. Operand identity is graph-scoped and checked by
8246 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8247 /// deliberate and replaces the hang a cross-graph handle used to produce.
8248 /// Build every operand from one graph, or use a `Result`-returning entry
8249 /// point where one exists.
8250 pub fn concat(&self, other: &NodeHandle, dim: usize) -> NodeHandle {
8251 assert!(
8252 Arc::ptr_eq(&self.graph, &other.graph),
8253 "concat: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8254 );
8255 assert_eq!(
8256 self.dtype(),
8257 other.dtype(),
8258 "concat: dtype mismatch {:?} vs {:?}",
8259 self.dtype(),
8260 other.dtype(),
8261 );
8262 let a = self.shape();
8263 let b = other.shape();
8264 let ad = a.dims();
8265 let bd = b.dims();
8266 assert_eq!(ad.len(), bd.len(), "concat: rank mismatch");
8267 assert!(dim < ad.len(), "concat: dim out of bounds");
8268 for i in 0..ad.len() {
8269 if i != dim {
8270 assert_eq!(
8271 ad[i], bd[i],
8272 "concat: non-dim shapes must match (dim {i}: {} vs {})",
8273 ad[i], bd[i],
8274 );
8275 }
8276 }
8277 let op = Op::Concat { dim };
8278 let (shape, dtype) =
8279 crate::shape::primitive_shape(&op, &[a, b], &[self.dtype(), other.dtype()])
8280 .expect("concat: shapes/dtypes validated above");
8281 let id = self.graph.write().unwrap().push(Node {
8282 op,
8283 inputs: vec![self.id, other.id],
8284 shape,
8285 dtype,
8286 });
8287 Self {
8288 graph: self.graph.clone(),
8289 id,
8290 }
8291 }
8292
8293 /// Append a `Slice` (narrow) node taking elements `[start, start+len)`
8294 /// along `dim`. The output has the same rank; only `dim` shrinks.
8295 pub fn slice(&self, dim: usize, start: usize, len: usize) -> NodeHandle {
8296 let in_shape = self.shape();
8297 let in_dims = in_shape.dims();
8298 assert!(dim < in_dims.len(), "slice: dim out of bounds");
8299 assert!(
8300 start + len <= in_dims[dim],
8301 "slice: [start={start}, len={len}) exceeds dim size {}",
8302 in_dims[dim],
8303 );
8304 let op = Op::Slice { dim, start, len };
8305 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8306 .expect("slice: dim/start/len validated above");
8307 let id = self.graph.write().unwrap().push(Node {
8308 op,
8309 inputs: vec![self.id],
8310 shape,
8311 dtype,
8312 });
8313 Self {
8314 graph: self.graph.clone(),
8315 id,
8316 }
8317 }
8318
8319 /// Append an `AddScalar` node: `y[i] = x[i] + c`. Convenient for
8320 /// avoiding a full-shape const node when you just want to bias a
8321 /// tensor by a constant.
8322 pub fn add_scalar(&self, c: f64) -> NodeHandle {
8323 self.unary_op(Op::AddScalar(c))
8324 }
8325
8326 /// Append a `MulScalar` node: `y[i] = x[i] * c`.
8327 pub fn mul_scalar(&self, c: f64) -> NodeHandle {
8328 self.unary_op(Op::MulScalar(c))
8329 }
8330
8331 /// Append a `PowI` node raising each element to an integer power.
8332 pub fn powi(&self, n: i32) -> NodeHandle {
8333 self.unary_op(Op::PowI(n))
8334 }
8335
8336 /// Append a `Clamp` node restricting each element to `[min, max]`.
8337 pub fn clamp(&self, min: f64, max: f64) -> NodeHandle {
8338 assert!(min <= max, "clamp: min ({min}) must be <= max ({max})",);
8339 self.unary_op(Op::Clamp { min, max })
8340 }
8341
8342 /// Append a `Maximum` node `max(self, other)` element-wise. Matching
8343 /// shapes required.
8344 ///
8345 /// # Panics
8346 ///
8347 /// Panics if any operand belongs to a different [`Graph`] than the one this
8348 /// builder is building into. Operand identity is graph-scoped and checked by
8349 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8350 /// deliberate and replaces the hang a cross-graph handle used to produce.
8351 /// Build every operand from one graph, or use a `Result`-returning entry
8352 /// point where one exists.
8353 pub fn maximum(&self, other: &NodeHandle) -> NodeHandle {
8354 self.binary_op("maximum", Op::Maximum, other, self.shape())
8355 }
8356
8357 /// Append a `Minimum` node `min(self, other)` element-wise.
8358 ///
8359 /// # Panics
8360 ///
8361 /// Panics if any operand belongs to a different [`Graph`] than the one this
8362 /// builder is building into. Operand identity is graph-scoped and checked by
8363 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8364 /// deliberate and replaces the hang a cross-graph handle used to produce.
8365 /// Build every operand from one graph, or use a `Result`-returning entry
8366 /// point where one exists.
8367 pub fn minimum(&self, other: &NodeHandle) -> NodeHandle {
8368 self.binary_op("minimum", Op::Minimum, other, self.shape())
8369 }
8370
8371 /// The IEEE-754 NaN-**suppressing** maximum — the KISS-OPS §6.15-0001
8372 /// `fmax_ieee` op, DISTINCT from [`maximum`](Self::maximum) (which is
8373 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8374 /// the other; if both are NaN, returns NaN; otherwise the larger.
8375 ///
8376 /// Built by RESOLUTION through the spec-pinned §6.13 decomposition
8377 /// (KISS-OPS-6.15-0001), used VERBATIM — Fuel does not substitute `maximum`
8378 /// for it (that substitution is the §6.15 violation). Because the
8379 /// decomposition is spec-authored, its edge behaviour — including ±0 ordering
8380 /// under `cmp_ge` (`cmp_ge(-0.0, +0.0)` is true, so this returns `-0.0` for
8381 /// that pair) — is the SPEC's to define and a KISS conformance vector's to
8382 /// catch. Fuel resolves; it does not re-derive. (GAP-048.)
8383 pub fn fmax_ieee(&self, other: &NodeHandle) -> NodeHandle {
8384 // select(a != a, b, select(b != b, a, select(a >= b, a, b)))
8385 let a = self;
8386 let b = other;
8387 let plain = a.ge(b).where_cond(a, b); // a >= b ? a : b
8388 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8389 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8390 }
8391
8392 /// The IEEE-754 NaN-**suppressing** minimum — the KISS-OPS §6.15-0001
8393 /// `fmin_ieee` op, DISTINCT from [`minimum`](Self::minimum) (which is
8394 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8395 /// the other; if both are NaN, returns NaN; otherwise the smaller.
8396 ///
8397 /// Built by RESOLUTION through the spec-pinned KISS-OPS §6.13 decomposition
8398 /// (KISS-OPS-6.15-0001), used VERBATIM — the `cmp_le` mirror of
8399 /// [`fmax_ieee`](Self::fmax_ieee)'s `cmp_ge` form. Fuel resolves; it does not
8400 /// substitute `minimum` (that substitution is the §6.15 violation) and does
8401 /// not re-derive: the decomposition is KISS's, so its ±0 edge behaviour is the
8402 /// spec's to define and a KISS conformance vector's to catch. (GAP-048.)
8403 pub fn fmin_ieee(&self, other: &NodeHandle) -> NodeHandle {
8404 // select(a != a, b, select(b != b, a, select(a <= b, a, b)))
8405 let a = self;
8406 let b = other;
8407 let plain = a.le(b).where_cond(a, b); // a <= b ? a : b
8408 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8409 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8410 }
8411
8412 /// Round toward zero — the KISS-OPS §6.3 `trunc` floor op (GAP-300).
8413 ///
8414 /// ⚠️ Unlike [`fmax_ieee`](Self::fmax_ieee)/[`fmin_ieee`](Self::fmin_ieee),
8415 /// which resolve through KISS's OWN §6.13 decompositions, `trunc` is a §6.3
8416 /// *floor* op: KISS-OPS-6.3-0003 forbids the standard from carrying a
8417 /// reference decomposition for a floor op, so THIS expansion is FUEL's, blessed
8418 /// by no spec clause. It IS now checked by KISS vectors: `ops-rounding.json`
8419 /// (vendored at KISS `0af5d3b6`) carries 18 `f32` `trunc` cells (signed zero, halves
8420 /// and ties, 2^23, max finite, ±inf, subnormals), all of which pass through the lazy
8421 /// `Tensor` (`fuel-tensor/tests/kiss_nan_conformance.rs`); `f64` and NaN inputs are
8422 /// not in that file. Beyond it, correctness is Fuel's liability — see GAP-300, whose born-reds assert
8423 /// on `to_bits()` (a value compare `0.0 == -0.0` passes vacuously).
8424 ///
8425 /// `trunc(q) = if q >= 0 { floor(q) } else { ceil(q) }`. Float dtypes only;
8426 /// integer dtypes are already whole, so `trunc` is identity for them (returned
8427 /// unchanged — never a panic on a non-float operand).
8428 ///
8429 /// REJECTED-FOR-NOW alternative: `copysign(floor(abs(q)), q)` is cleaner (no
8430 /// dtype-matched zero; ±0/NaN/inf fall out of the IEEE primitives). Fuel has no
8431 /// `copysign` op today (absent from `Op` and the builder API), so it is not
8432 /// buildable — adopt it IF `copysign` ever lands.
8433 pub fn trunc(&self) -> NodeHandle {
8434 let q = self;
8435 // A scalar zero of q's dtype, broadcast to q's shape — comparisons require
8436 // matching shapes (no implicit broadcast in `binary_compare_op`).
8437 let zero = match q.dtype() {
8438 DType::F32 => q
8439 .const_f32_like(vec![0.0f32], &[1])
8440 .expect("trunc: a 1-element vec with shape [1]")
8441 .broadcast_to(q.shape()),
8442 DType::F64 => q
8443 .const_f64_like(vec![0.0f64], &[1])
8444 .expect("trunc: a 1-element vec with shape [1]")
8445 .broadcast_to(q.shape()),
8446 DType::BF16 => q
8447 .const_bf16_like(vec![half::bf16::from_f32(0.0)], &[1])
8448 .expect("trunc: a 1-element vec with shape [1]")
8449 .broadcast_to(q.shape()),
8450 DType::F16 => q
8451 .const_f16_like(vec![half::f16::from_f32(0.0)], &[1])
8452 .expect("trunc: a 1-element vec with shape [1]")
8453 .broadcast_to(q.shape()),
8454 // Integer/other dtypes are already whole: trunc is identity.
8455 _ => return q.clone(),
8456 };
8457 // q >= 0 ? floor(q) : ceil(q). Note: at ±0 BOTH branches yield the same
8458 // signed zero (`floor(-0.0) == ceil(-0.0) == -0.0`), so trunc's ±0 result
8459 // is robust to a tie-bias in `ge` — but the born-red still checks the bits.
8460 q.ge(&zero).where_cond(&q.floor(), &q.ceil())
8461 }
8462
8463 /// Truncated remainder — the KISS-OPS §6.15-0003 `rem_trunc` op, DISTINCT from
8464 /// [`rem`](Self::rem) (which is FLOORED / PyTorch, sign of the *divisor*).
8465 /// `rem_trunc` takes the sign of the *dividend* (C99 `fmod` / Rust `%`).
8466 ///
8467 /// Built by RESOLUTION through KISS's spec-pinned §6.13 decomposition
8468 /// (KISS-OPS-6.15-0003) — `a - trunc(a / b) * b` — used VERBATIM. Fuel does not
8469 /// substitute `rem` (that substitution is the §6.15 violation); the two diverge
8470 /// whenever the operands have opposite signs (e.g. `-7 rem_trunc 3 = -1`, where
8471 /// `rem` (floored) = `2`). The `trunc` leaf is Fuel's own expansion (GAP-300).
8472 pub fn rem_trunc(&self, other: &NodeHandle) -> NodeHandle {
8473 // a - trunc(a / b) * b
8474 let a = self;
8475 let b = other;
8476 let t = a.div(b).trunc();
8477 a.sub(&t.mul(b))
8478 }
8479
8480 /// Element-wise addition with automatic broadcasting. Unlike `add`,
8481 /// which requires matching shapes, `broadcast_add` computes the
8482 /// broadcast shape of the two operands, inserts explicit
8483 /// `BroadcastTo` nodes as needed, and then emits a regular `Add`.
8484 /// Useful for bias addition (`[batch, hidden] + [hidden]`) without
8485 /// the caller writing the broadcast out explicitly.
8486 ///
8487 /// # Panics
8488 ///
8489 /// Panics if any operand belongs to a different [`Graph`] than the one this
8490 /// builder is building into. Operand identity is graph-scoped and checked by
8491 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8492 /// deliberate and replaces the hang a cross-graph handle used to produce.
8493 /// Build every operand from one graph, or use a `Result`-returning entry
8494 /// point where one exists.
8495 pub fn broadcast_add(&self, other: &NodeHandle) -> NodeHandle {
8496 let (a, b) = self.auto_broadcast_pair("broadcast_add", other);
8497 a.add(&b)
8498 }
8499
8500 /// Element-wise subtraction with automatic broadcasting.
8501 ///
8502 /// # Panics
8503 ///
8504 /// Panics if any operand belongs to a different [`Graph`] than the one this
8505 /// builder is building into. Operand identity is graph-scoped and checked by
8506 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8507 /// deliberate and replaces the hang a cross-graph handle used to produce.
8508 /// Build every operand from one graph, or use a `Result`-returning entry
8509 /// point where one exists.
8510 pub fn broadcast_sub(&self, other: &NodeHandle) -> NodeHandle {
8511 let (a, b) = self.auto_broadcast_pair("broadcast_sub", other);
8512 a.sub(&b)
8513 }
8514
8515 /// Element-wise multiplication with automatic broadcasting.
8516 ///
8517 /// # Panics
8518 ///
8519 /// Panics if any operand belongs to a different [`Graph`] than the one this
8520 /// builder is building into. Operand identity is graph-scoped and checked by
8521 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8522 /// deliberate and replaces the hang a cross-graph handle used to produce.
8523 /// Build every operand from one graph, or use a `Result`-returning entry
8524 /// point where one exists.
8525 pub fn broadcast_mul(&self, other: &NodeHandle) -> NodeHandle {
8526 let (a, b) = self.auto_broadcast_pair("broadcast_mul", other);
8527 a.mul(&b)
8528 }
8529
8530 /// Element-wise division with automatic broadcasting.
8531 ///
8532 /// # Panics
8533 ///
8534 /// Panics if any operand belongs to a different [`Graph`] than the one this
8535 /// builder is building into. Operand identity is graph-scoped and checked by
8536 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8537 /// deliberate and replaces the hang a cross-graph handle used to produce.
8538 /// Build every operand from one graph, or use a `Result`-returning entry
8539 /// point where one exists.
8540 pub fn broadcast_div(&self, other: &NodeHandle) -> NodeHandle {
8541 let (a, b) = self.auto_broadcast_pair("broadcast_div", other);
8542 a.div(&b)
8543 }
8544
8545 /// Build both operands broadcast to their common shape. Used by the
8546 /// `broadcast_*` wrappers above. Inserts explicit `BroadcastTo` nodes
8547 /// on whichever side needs them — either or both may pass through
8548 /// unchanged if already at the target shape.
8549 fn auto_broadcast_pair(
8550 &self,
8551 op: &'static str,
8552 other: &NodeHandle,
8553 ) -> (NodeHandle, NodeHandle) {
8554 assert!(
8555 Arc::ptr_eq(&self.graph, &other.graph),
8556 "{op}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8557 each `from_*` constructor mints a NEW graph, so build the second operand with \
8558 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8559 self.graph_id(),
8560 other.graph_id(),
8561 );
8562 assert_eq!(
8563 self.dtype(),
8564 other.dtype(),
8565 "{op}: dtype mismatch {:?} vs {:?}",
8566 self.dtype(),
8567 other.dtype(),
8568 );
8569 let a_shape = self.shape();
8570 let b_shape = other.shape();
8571 let target_dims = compute_broadcast_shape(a_shape.dims(), b_shape.dims());
8572 let target = Shape::from_dims(&target_dims);
8573 let a = if a_shape.dims() == target.dims() {
8574 self.clone()
8575 } else {
8576 self.broadcast_to(target.clone())
8577 };
8578 let b = if b_shape.dims() == target.dims() {
8579 other.clone()
8580 } else {
8581 other.broadcast_to(target)
8582 };
8583 (a, b)
8584 }
8585
8586 /// Append an `IndexAdd` node — the functional inverse of
8587 /// `IndexSelect`. Returns `base` with `src` added at positions given
8588 /// by `indices` along `dim`.
8589 ///
8590 /// # Panics
8591 ///
8592 /// Panics if any operand belongs to a different [`Graph`] than the one this
8593 /// builder is building into. Operand identity is graph-scoped and checked by
8594 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8595 /// deliberate and replaces the hang a cross-graph handle used to produce.
8596 /// Build every operand from one graph, or use a `Result`-returning entry
8597 /// point where one exists.
8598 pub fn index_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8599 assert!(
8600 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8601 "index_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8602 );
8603 assert_eq!(indices.dtype(), DType::U32, "index_add: index must be U32");
8604 assert_eq!(
8605 self.dtype(),
8606 src.dtype(),
8607 "index_add: base and src dtypes must match"
8608 );
8609 let base_dims = self.shape();
8610 let src_dims = src.shape();
8611 assert_eq!(
8612 base_dims.dims().len(),
8613 src_dims.dims().len(),
8614 "index_add: base and src must have the same rank",
8615 );
8616 assert_eq!(
8617 indices.shape().dims().len(),
8618 1,
8619 "index_add: index must be rank 1",
8620 );
8621 assert_eq!(
8622 src_dims.dims()[dim],
8623 indices.shape().dims()[0],
8624 "index_add: src dim {dim} ({}) must match index length ({})",
8625 src_dims.dims()[dim],
8626 indices.shape().dims()[0],
8627 );
8628 let dtype = self.dtype();
8629 let out_shape = base_dims;
8630 let id = self.graph.write().unwrap().push(Node {
8631 op: Op::IndexAdd { dim },
8632 inputs: vec![self.id, indices.id, src.id],
8633 shape: out_shape,
8634 dtype,
8635 });
8636 Self {
8637 graph: self.graph.clone(),
8638 id,
8639 }
8640 }
8641
8642 /// Append a `ScatterAdd` node — the functional inverse of `Gather`.
8643 /// Returns `base` with values from `src` accumulated at positions
8644 /// given by `indices` (with `indices[p]` substituted at `dim`).
8645 ///
8646 /// # Panics
8647 ///
8648 /// Panics if any operand belongs to a different [`Graph`] than the one this
8649 /// builder is building into. Operand identity is graph-scoped and checked by
8650 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8651 /// deliberate and replaces the hang a cross-graph handle used to produce.
8652 /// Build every operand from one graph, or use a `Result`-returning entry
8653 /// point where one exists.
8654 pub fn scatter_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8655 assert!(
8656 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8657 "scatter_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8658 );
8659 assert_eq!(
8660 indices.dtype(),
8661 DType::U32,
8662 "scatter_add: index must be U32"
8663 );
8664 assert_eq!(
8665 self.dtype(),
8666 src.dtype(),
8667 "scatter_add: base and src dtypes must match"
8668 );
8669 assert_eq!(
8670 indices.shape().dims(),
8671 src.shape().dims(),
8672 "scatter_add: index and src must have the same shape",
8673 );
8674 let dtype = self.dtype();
8675 let out_shape = self.shape();
8676 let id = self.graph.write().unwrap().push(Node {
8677 op: Op::ScatterAdd { dim },
8678 inputs: vec![self.id, indices.id, src.id],
8679 shape: out_shape,
8680 dtype,
8681 });
8682 Self {
8683 graph: self.graph.clone(),
8684 id,
8685 }
8686 }
8687
8688 // --- internal helpers for the new builders ---
8689
8690 fn scalar_reduction(&self, op: Op) -> NodeHandle {
8691 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
8692 .expect("scalar_reduction: single input always infers a rank-0 shape");
8693 let id = self.graph.write().unwrap().push(Node {
8694 op,
8695 inputs: vec![self.id],
8696 shape,
8697 dtype,
8698 });
8699 Self {
8700 graph: self.graph.clone(),
8701 id,
8702 }
8703 }
8704
8705 fn axis_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
8706 let in_shape = self.shape();
8707 assert!(
8708 dim < in_shape.dims().len(),
8709 "{name}: dim {dim} out of bounds for shape {:?}",
8710 in_shape.dims(),
8711 );
8712 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8713 .expect("axis_reduction: dim validated above");
8714 let id = self.graph.write().unwrap().push(Node {
8715 op,
8716 inputs: vec![self.id],
8717 shape,
8718 dtype,
8719 });
8720 Self {
8721 graph: self.graph.clone(),
8722 id,
8723 }
8724 }
8725
8726 // Internal helpers. Both shape-validate and append.
8727
8728 /// Build-time graph-affinity check for a `Result`-returning builder.
8729 ///
8730 /// Node ids index ONE graph's arena, so an operand from a different graph
8731 /// records an id pointing at an unrelated node — a malformed dependency
8732 /// graph whose failure mode is a **realize-time hang**, not a panic or an
8733 /// error. Checking here converts a silent deadlock into a typed build-time
8734 /// error naming both graphs, per "validate at graph-build time".
8735 fn require_same_graph(
8736 &self,
8737 other: &NodeHandle,
8738 op: &str,
8739 role: &str,
8740 ) -> std::result::Result<(), fuel_ir::Error> {
8741 if !Arc::ptr_eq(&self.graph, &other.graph) {
8742 return Err(fuel_ir::Error::Msg(format!(
8743 "{op}: operands must live on the same graph — self is on graph #{}, \
8744 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8745 build the other operand with `from_*_on(self.graph(), ..)` or \
8746 `const_*_like`",
8747 self.graph_id(),
8748 other.graph_id(),
8749 ))
8750 .bt());
8751 }
8752 Ok(())
8753 }
8754
8755 /// Panicking sibling of [`Self::require_same_graph`] for the builders that
8756 /// return `NodeHandle` rather than `Result` — same convention as `matmul`,
8757 /// `qmatmul`, `conv2d` and `paged_attn`. A panic at the build site is far
8758 /// better than the hang it replaces: it names the operand and both graphs.
8759 fn assert_same_graph(&self, other: &NodeHandle, op: &str, role: &str) {
8760 assert!(
8761 Arc::ptr_eq(&self.graph, &other.graph),
8762 "{op}: operands must live on the same graph — self is on graph #{}, \
8763 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8764 build the other operand with `from_*_on(self.graph(), ..)` or \
8765 `const_*_like`",
8766 self.graph_id(),
8767 other.graph_id(),
8768 );
8769 }
8770
8771 fn binary_op(
8772 &self,
8773 name: &'static str,
8774 op: Op,
8775 other: &NodeHandle,
8776 out_shape: Shape,
8777 ) -> NodeHandle {
8778 assert!(
8779 Arc::ptr_eq(&self.graph, &other.graph),
8780 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8781 each `from_*` constructor mints a NEW graph, so build the second operand with \
8782 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8783 self.graph_id(),
8784 other.graph_id(),
8785 );
8786 assert_eq!(
8787 self.dtype(),
8788 other.dtype(),
8789 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8790 self.dtype(),
8791 other.dtype(),
8792 );
8793 assert_eq!(
8794 self.shape().dims(),
8795 other.shape().dims(),
8796 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8797 self.shape().dims(),
8798 other.shape().dims(),
8799 );
8800 let dtype = self.dtype();
8801 let id = self.graph.write().unwrap().push(Node {
8802 op,
8803 inputs: vec![self.id, other.id],
8804 shape: out_shape,
8805 dtype,
8806 });
8807 Self {
8808 graph: self.graph.clone(),
8809 id,
8810 }
8811 }
8812
8813 /// Result-returning sibling of [`Self::binary_op`]. Validates the
8814 /// graph/dtype/shape preconditions and returns `Err` rather than
8815 /// panicking — the production-correct shape new builders should
8816 /// use. Existing panicking sites are kept for back-compat; new
8817 /// ops should call this directly.
8818 fn try_binary_op(
8819 &self,
8820 name: &'static str,
8821 op: Op,
8822 other: &NodeHandle,
8823 out_shape: Shape,
8824 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
8825 if !Arc::ptr_eq(&self.graph, &other.graph) {
8826 return Err(fuel_ir::Error::Msg(format!(
8827 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8828 each `from_*` constructor mints a NEW graph, so build the second operand with \
8829 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8830 self.graph_id(),
8831 other.graph_id(),
8832 )).bt());
8833 }
8834 if self.dtype() != other.dtype() {
8835 return Err(fuel_ir::Error::Msg(format!(
8836 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8837 self.dtype(),
8838 other.dtype(),
8839 ))
8840 .bt());
8841 }
8842 if self.shape().dims() != other.shape().dims() {
8843 return Err(fuel_ir::Error::Msg(format!(
8844 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8845 self.shape().dims(),
8846 other.shape().dims(),
8847 ))
8848 .bt());
8849 }
8850 let dtype = self.dtype();
8851 let id = self.graph.write().unwrap().push(Node {
8852 op,
8853 inputs: vec![self.id, other.id],
8854 shape: out_shape,
8855 dtype,
8856 });
8857 Ok(Self {
8858 graph: self.graph.clone(),
8859 id,
8860 })
8861 }
8862
8863 fn unary_op(&self, op: Op) -> NodeHandle {
8864 let shape = self.shape();
8865 let dtype = self.dtype();
8866 let id = self.graph.write().unwrap().push(Node {
8867 op,
8868 inputs: vec![self.id],
8869 shape,
8870 dtype,
8871 });
8872 Self {
8873 graph: self.graph.clone(),
8874 id,
8875 }
8876 }
8877
8878 /// Binary builder for ops whose inputs share dtype/shape but whose
8879 /// output is a `U8` mask (`Op::Equal` and the rest of the
8880 /// comparison family). Differs from [`Self::binary_op`] only in the
8881 /// node's output dtype: always `DType::U8` regardless of input
8882 /// dtype.
8883 fn binary_compare_op(&self, name: &'static str, op: Op, other: &NodeHandle) -> NodeHandle {
8884 assert!(
8885 Arc::ptr_eq(&self.graph, &other.graph),
8886 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8887 each `from_*` constructor mints a NEW graph, so build the second operand with \
8888 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8889 self.graph_id(),
8890 other.graph_id(),
8891 );
8892 assert_eq!(
8893 self.dtype(),
8894 other.dtype(),
8895 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8896 self.dtype(),
8897 other.dtype(),
8898 );
8899 assert_eq!(
8900 self.shape().dims(),
8901 other.shape().dims(),
8902 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8903 self.shape().dims(),
8904 other.shape().dims(),
8905 );
8906 let shape = self.shape();
8907 let id = self.graph.write().unwrap().push(Node {
8908 op,
8909 inputs: vec![self.id, other.id],
8910 shape,
8911 // GAP-168(c): comparisons yield a `Bool` mask. This BUILDER path is
8912 // the one eq/ne/lt/le/gt/ge take; it must agree with the
8913 // `primitive_shape` comparison arm (fuel-graph/src/shape.rs), which
8914 // is the OTHER site that decides this dtype (reached on re-lowering).
8915 dtype: DType::Bool,
8916 });
8917 Self {
8918 graph: self.graph.clone(),
8919 id,
8920 }
8921 }
8922
8923 /// Build the backward graph from `self`, treating `self` as the output
8924 /// whose gradient drives the rest of the computation.
8925 ///
8926 /// Walks the forward graph in reverse topological order, applies the
8927 /// per-op gradient rule to each node, and emits new graph nodes for
8928 /// the gradient with respect to every node reachable from `self`. The
8929 /// returned [`GradMap`] lets you look up the gradient tensor for any
8930 /// forward tensor from the same graph.
8931 ///
8932 /// The initial upstream gradient is a ones tensor of the same shape
8933 /// and dtype as `self` — the conventional `dL/dL = 1` seed for
8934 /// backprop. For a scalar loss this is `[1.0]`; for a non-scalar
8935 /// output it is "each element of the output contributes with weight 1
8936 /// to the total derivative."
8937 ///
8938 /// ## Supported ops in the MVP
8939 ///
8940 /// `Const`, `Add`, `Mul`, `MatMul`, `Transpose`, `Sqr`, `Exp` all have
8941 /// gradient rules implemented. `Relu` panics — its gradient needs a
8942 /// `Step`/`Where`/`Sign` op that is not yet in the catalog and will
8943 /// land in a follow-up once an indicator-valued op is defined.
8944 ///
8945 /// ## Ownership and the forward graph
8946 ///
8947 /// Backward extends the same graph that held the forward pass. The
8948 /// gradient nodes live alongside the forward nodes in one arena. After
8949 /// `backward()`, realizing a gradient tensor re-executes whatever part
8950 /// of the forward pass the gradient depends on — the executor walks
8951 /// the combined graph as one.
8952 pub fn backward(&self) -> GradMap {
8953 let graph_handle = self.graph.clone();
8954
8955 // C3 pre-pass (Op::Scan Phase 2): lower every reachable Op::Scan to
8956 // primitives + decompose the SSM fused recipes BEFORE the topo order is
8957 // taken, so the reverse walk sees only differentiable primitives. On a
8958 // scan-free graph it is a near-no-op — two topo scans (Pass 1's SSM
8959 // collect + Pass 2's first iteration, which finds no scans and breaks),
8960 // no rewiring. The (possibly remapped) root replaces self.id below.
8961 let root = lower_scans_for_backward(&graph_handle, self.id);
8962
8963 // Compute topological order of reachable nodes, then reverse it
8964 // so we walk from the root (output) toward the leaves (inputs).
8965 let mut order = topo_order(&graph_handle.read().unwrap(), root);
8966 order.reverse();
8967
8968 // Initial upstream gradient for the root: ones tensor of matching
8969 // shape and dtype. For a scalar loss this is [1.0]; for vector
8970 // outputs it seeds each element with weight 1.
8971 let (root_shape, root_dtype) = {
8972 let g = graph_handle.read().unwrap();
8973 let n = g.node(root);
8974 (n.shape.clone(), n.dtype)
8975 };
8976 let ones_id = build_ones(&graph_handle, root_shape, root_dtype);
8977
8978 let mut upstream: HashMap<NodeId, NodeId> = HashMap::new();
8979 upstream.insert(root, ones_id);
8980
8981 for id in order {
8982 let up_id = match upstream.get(&id).copied() {
8983 Some(v) => v,
8984 None => continue, // unreachable from the root, no gradient to propagate
8985 };
8986 // Snapshot the op and its input IDs so we can drop the read
8987 // borrow before taking a mutable borrow to append new nodes.
8988 let (op, inputs) = {
8989 let g = graph_handle.read().unwrap();
8990 let node = g.node(id);
8991 (node.op.clone(), node.inputs.clone())
8992 };
8993
8994 // Symbolic-autograd dispatch (Phase 6d Track 2). If a
8995 // `GradientRule` is registered for this op, use it. Ops
8996 // that haven't migrated yet fall through to the legacy
8997 // inline `match` below.
8998 if let Some(grads) =
8999 crate::grad::dispatch_gradient(&graph_handle, &op, &inputs, id, up_id)
9000 {
9001 debug_assert_eq!(
9002 grads.len(),
9003 inputs.len(),
9004 "GradientRule for {:?} returned {} gradients but op has {} inputs",
9005 op.short_name(),
9006 grads.len(),
9007 inputs.len(),
9008 );
9009 for (input_id, grad) in inputs.iter().zip(grads.iter()) {
9010 if let Some(g) = grad {
9011 accumulate_grad(&mut upstream, *input_id, *g, &graph_handle);
9012 }
9013 }
9014 continue;
9015 }
9016
9017 match op {
9018 Op::Const => {
9019 // Leaf. The upstream value has already been stored and
9020 // is what `GradMap::get` will return for this input.
9021 }
9022 Op::Iota { .. } => {
9023 // Leaf, non-differentiable: a constant position
9024 // generator with no inputs — no gradient to propagate.
9025 }
9026 Op::NonZeroIndices { .. } => {
9027 // Produces discrete indices + a runtime count; both
9028 // are integer/non-differentiable. No gradient flows to
9029 // the input. (A differentiated graph that reaches this
9030 // op surfaces as a usage error in the grad-emitting
9031 // pass, matching the ArgMaxDim/ArgMinDim precedent.)
9032 }
9033 Op::Add => {
9034 // d(a + b)/da = 1, d(a + b)/db = 1.
9035 // Upstream flows unchanged into both inputs.
9036 accumulate_grad(&mut upstream, inputs[0], up_id, &graph_handle);
9037 accumulate_grad(&mut upstream, inputs[1], up_id, &graph_handle);
9038 }
9039 Op::Mul => {
9040 // d(a * b)/da = b, d(a * b)/db = a.
9041 // Upstream * b goes to a; upstream * a goes to b.
9042 let a = inputs[0];
9043 let b = inputs[1];
9044 let a_shape = node_shape(&graph_handle, a);
9045 let b_shape = node_shape(&graph_handle, b);
9046 let dtype = node_dtype(&graph_handle, a);
9047 let grad_a = push_node(&graph_handle, Op::Mul, vec![up_id, b], a_shape, dtype);
9048 let grad_b = push_node(&graph_handle, Op::Mul, vec![up_id, a], b_shape, dtype);
9049 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9050 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9051 }
9052 Op::MatMul => {
9053 // Forward: Y = A @ B, A: [m, k], B: [k, n], Y: [m, n]
9054 // Backward: dA = dY @ B^T, dB = A^T @ dY.
9055 let a = inputs[0];
9056 let b = inputs[1];
9057 let a_shape = node_shape(&graph_handle, a);
9058 let b_shape = node_shape(&graph_handle, b);
9059 let dtype = node_dtype(&graph_handle, a);
9060 // B^T: shape [n, k]
9061 let b_t_shape = transposed_shape(&b_shape);
9062 let b_t = push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
9063 // dA = upstream @ B^T, shape [m, k] = a_shape
9064 let grad_a = push_node(
9065 &graph_handle,
9066 Op::MatMul,
9067 vec![up_id, b_t],
9068 a_shape.clone(),
9069 dtype,
9070 );
9071 // A^T: shape [k, m]
9072 let a_t_shape = transposed_shape(&a_shape);
9073 let a_t = push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
9074 // dB = A^T @ upstream, shape [k, n] = b_shape
9075 let grad_b =
9076 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
9077 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9078 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9079 }
9080 Op::Transpose => {
9081 // d(x^T)/dx is a transpose on the way back.
9082 let x = inputs[0];
9083 let x_shape = node_shape(&graph_handle, x);
9084 let dtype = node_dtype(&graph_handle, x);
9085 let grad_x =
9086 push_node(&graph_handle, Op::Transpose, vec![up_id], x_shape, dtype);
9087 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9088 }
9089 Op::Permute(ref axes) => {
9090 // Backward: apply the inverse permutation to upstream.
9091 // If forward permutes with `axes` (out[i] = in[axes[i]]),
9092 // the inverse `inv` satisfies `inv[axes[i]] = i`.
9093 let x = inputs[0];
9094 let x_shape = node_shape(&graph_handle, x);
9095 let dtype = node_dtype(&graph_handle, x);
9096 let mut inv = vec![0_usize; axes.len()];
9097 for (i, &ax) in axes.iter().enumerate() {
9098 inv[ax] = i;
9099 }
9100 let grad_x =
9101 push_node(&graph_handle, Op::Permute(inv), vec![up_id], x_shape, dtype);
9102 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9103 }
9104 Op::Sqr => {
9105 // d(x^2)/dx = 2x. Expressed as `x + x` to avoid
9106 // needing a scalar constant broadcast — both sums
9107 // have the same shape as x, the existing Add op
9108 // handles them natively.
9109 let x = inputs[0];
9110 let x_shape = node_shape(&graph_handle, x);
9111 let dtype = node_dtype(&graph_handle, x);
9112 let two_x =
9113 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
9114 let grad_x =
9115 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
9116 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9117 }
9118 Op::Exp => {
9119 // d(e^x)/dx = e^x, which is the forward output — i.e.
9120 // this node `id`. Reuse it directly instead of
9121 // recomputing.
9122 let x = inputs[0];
9123 let out_shape = node_shape(&graph_handle, id);
9124 let dtype = node_dtype(&graph_handle, id);
9125 let grad_x =
9126 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
9127 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9128 }
9129 Op::Sub => {
9130 // d(a - b)/da = 1, d(a - b)/db = -1.
9131 let a = inputs[0];
9132 let b = inputs[1];
9133 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9134 let b_shape = node_shape(&graph_handle, b);
9135 let dtype = node_dtype(&graph_handle, b);
9136 let neg_up = push_node(&graph_handle, Op::Neg, vec![up_id], b_shape, dtype);
9137 accumulate_grad(&mut upstream, b, neg_up, &graph_handle);
9138 }
9139 Op::Div => {
9140 // y = a / b
9141 // dy/da = 1/b → grad_a = upstream / b
9142 // dy/db = -a/b² → grad_b = -(upstream * a / (b*b))
9143 let a = inputs[0];
9144 let b = inputs[1];
9145 let a_shape = node_shape(&graph_handle, a);
9146 let b_shape = node_shape(&graph_handle, b);
9147 let dtype = node_dtype(&graph_handle, a);
9148 // grad_a
9149 let grad_a = push_node(
9150 &graph_handle,
9151 Op::Div,
9152 vec![up_id, b],
9153 a_shape.clone(),
9154 dtype,
9155 );
9156 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9157 // grad_b: -(upstream * a / (b*b))
9158 let b_sq = push_node(&graph_handle, Op::Sqr, vec![b], b_shape.clone(), dtype);
9159 let up_times_a =
9160 push_node(&graph_handle, Op::Mul, vec![up_id, a], a_shape, dtype);
9161 let quotient = push_node(
9162 &graph_handle,
9163 Op::Div,
9164 vec![up_times_a, b_sq],
9165 b_shape.clone(),
9166 dtype,
9167 );
9168 let grad_b = push_node(&graph_handle, Op::Neg, vec![quotient], b_shape, dtype);
9169 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9170 }
9171 Op::Neg => {
9172 // d(-x)/dx = -1. grad_x = -upstream.
9173 let x = inputs[0];
9174 let x_shape = node_shape(&graph_handle, x);
9175 let dtype = node_dtype(&graph_handle, x);
9176 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
9177 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9178 }
9179 Op::Sqrt => {
9180 // y = sqrt(x), dy/dx = 1/(2*sqrt(x)) = 1/(2y).
9181 // grad_x = upstream / (y + y). Reuse the forward node.
9182 let x = inputs[0];
9183 let x_shape = node_shape(&graph_handle, x);
9184 let dtype = node_dtype(&graph_handle, x);
9185 let two_y =
9186 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
9187 let grad_x =
9188 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
9189 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9190 }
9191 Op::Log => {
9192 // d(ln(x))/dx = 1/x. grad_x = upstream / x.
9193 let x = inputs[0];
9194 let x_shape = node_shape(&graph_handle, x);
9195 let dtype = node_dtype(&graph_handle, x);
9196 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
9197 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9198 }
9199 Op::Sin => {
9200 // d(sin(x))/dx = cos(x). grad_x = upstream * cos(x).
9201 let x = inputs[0];
9202 let x_shape = node_shape(&graph_handle, x);
9203 let dtype = node_dtype(&graph_handle, x);
9204 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
9205 let grad_x =
9206 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
9207 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9208 }
9209 Op::Cos => {
9210 // d(cos(x))/dx = -sin(x). grad_x = -(upstream * sin(x)).
9211 let x = inputs[0];
9212 let x_shape = node_shape(&graph_handle, x);
9213 let dtype = node_dtype(&graph_handle, x);
9214 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
9215 let up_sin = push_node(
9216 &graph_handle,
9217 Op::Mul,
9218 vec![up_id, sin_x],
9219 x_shape.clone(),
9220 dtype,
9221 );
9222 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
9223 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9224 }
9225 Op::Tanh => {
9226 // y = tanh(x), dy/dx = 1 - y². grad_x = upstream * (1 - y*y).
9227 // Build: ones_of_y_shape - y*y, then multiply by upstream.
9228 let x = inputs[0];
9229 let y_shape = node_shape(&graph_handle, id);
9230 let dtype = node_dtype(&graph_handle, id);
9231 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
9232 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9233 let one_minus_sq = push_node(
9234 &graph_handle,
9235 Op::Sub,
9236 vec![ones, y_sq],
9237 y_shape.clone(),
9238 dtype,
9239 );
9240 let grad_x = push_node(
9241 &graph_handle,
9242 Op::Mul,
9243 vec![up_id, one_minus_sq],
9244 y_shape,
9245 dtype,
9246 );
9247 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9248 }
9249 Op::Sigmoid => {
9250 // y = sigmoid(x), dy/dx = y * (1 - y).
9251 // grad_x = upstream * y * (1 - y).
9252 let x = inputs[0];
9253 let y_shape = node_shape(&graph_handle, id);
9254 let dtype = node_dtype(&graph_handle, id);
9255 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9256 let one_minus_y = push_node(
9257 &graph_handle,
9258 Op::Sub,
9259 vec![ones, id],
9260 y_shape.clone(),
9261 dtype,
9262 );
9263 let y_times_1my = push_node(
9264 &graph_handle,
9265 Op::Mul,
9266 vec![id, one_minus_y],
9267 y_shape.clone(),
9268 dtype,
9269 );
9270 let grad_x = push_node(
9271 &graph_handle,
9272 Op::Mul,
9273 vec![up_id, y_times_1my],
9274 y_shape,
9275 dtype,
9276 );
9277 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9278 }
9279 Op::Silu => {
9280 // y = x * sigmoid(x)
9281 // dy/dx = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
9282 // = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
9283 //
9284 // Simpler: let s = sigmoid(x). dy/dx = s + y * (1 - s),
9285 // where y = x * s is the forward output (this node).
9286 // grad_x = upstream * (s + y * (1 - s)).
9287 let x = inputs[0];
9288 let x_shape = node_shape(&graph_handle, x);
9289 let dtype = node_dtype(&graph_handle, x);
9290 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
9291 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
9292 let one_minus_s = push_node(
9293 &graph_handle,
9294 Op::Sub,
9295 vec![ones, s],
9296 x_shape.clone(),
9297 dtype,
9298 );
9299 let y_times_1ms = push_node(
9300 &graph_handle,
9301 Op::Mul,
9302 vec![id, one_minus_s],
9303 x_shape.clone(),
9304 dtype,
9305 );
9306 let inner = push_node(
9307 &graph_handle,
9308 Op::Add,
9309 vec![s, y_times_1ms],
9310 x_shape.clone(),
9311 dtype,
9312 );
9313 let grad_x =
9314 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
9315 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9316 }
9317 Op::GeluTanh => {
9318 let x = inputs[0];
9319 let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
9320 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9321 }
9322 Op::Relu => {
9323 // d(relu(x))/dx = step(x). grad_x = upstream * step(x).
9324 let x = inputs[0];
9325 let x_shape = node_shape(&graph_handle, x);
9326 let dtype = node_dtype(&graph_handle, x);
9327 let step_x =
9328 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
9329 let grad_x =
9330 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
9331 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9332 }
9333 Op::Step => {
9334 // d(step(x))/dx is 0 almost everywhere (and a Dirac
9335 // delta at 0 which has no finite representation). The
9336 // standard move is to treat the derivative as 0 and
9337 // stop propagation — Step's backward is silently a
9338 // no-op. Callers that need a smooth surrogate should
9339 // use Sigmoid or Tanh instead.
9340 }
9341 Op::Recip => {
9342 // y = 1/x, dy/dx = -1/x² = -y².
9343 // grad_x = -upstream * y * y. Reuse forward output (id)
9344 // so we don't recompute the reciprocal.
9345 let x = inputs[0];
9346 let x_shape = node_shape(&graph_handle, x);
9347 let dtype = node_dtype(&graph_handle, x);
9348 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9349 let up_y_sq = push_node(
9350 &graph_handle,
9351 Op::Mul,
9352 vec![up_id, y_sq],
9353 x_shape.clone(),
9354 dtype,
9355 );
9356 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
9357 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9358 }
9359 Op::Abs => {
9360 // y = |x|, dy/dx = sign(x), with sign(0)=0 by
9361 // subgradient convention. Simplified to a direct
9362 // `Op::Sign` use after Op::Sign landed in PR B2;
9363 // the previous form synthesized `step(x) - step(-x)`
9364 // (5 backward nodes) but Sign expresses the same
9365 // function in 1 node, so the chain shrinks to
9366 // `Mul(upstream, Sign(x))` — 2 nodes total.
9367 let x = inputs[0];
9368 let x_shape = node_shape(&graph_handle, x);
9369 let dtype = node_dtype(&graph_handle, x);
9370 let sign_x =
9371 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
9372 let grad_x =
9373 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
9374 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9375 }
9376 Op::Where => {
9377 // Handled by `WhereRule` via `dispatch_gradient`;
9378 // this arm only exists for exhaustiveness.
9379 }
9380 Op::Floor | Op::Ceil | Op::Round | Op::Sign => {
9381 // d(floor(x))/dx, d(ceil(x))/dx, d(round(x))/dx,
9382 // d(sign(x))/dx are all 0 almost everywhere (with
9383 // a Dirac train at integer / half-integer / zero
9384 // that has no finite representation). Treat the
9385 // derivative as 0 and stop propagation — mirrors
9386 // `Op::Step`'s backward.
9387 }
9388 Op::Erf => {
9389 // y = erf(x). dy/dx = (2/√π) * exp(-x²).
9390 // grad_x = upstream * (2/√π) * exp(-x²).
9391 // Decomposes to: Sqr(x) → Neg → Exp → MulScalar(2/√π)
9392 // → Mul(upstream, .).
9393 // 2/√π = 1.1283791670955125738961589031...
9394 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
9395 let x = inputs[0];
9396 let x_shape = node_shape(&graph_handle, x);
9397 let dtype = node_dtype(&graph_handle, x);
9398 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9399 let neg_x_sq =
9400 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
9401 let exp_neg_x_sq = push_node(
9402 &graph_handle,
9403 Op::Exp,
9404 vec![neg_x_sq],
9405 x_shape.clone(),
9406 dtype,
9407 );
9408 let scaled = push_node(
9409 &graph_handle,
9410 Op::MulScalar(TWO_OVER_SQRT_PI),
9411 vec![exp_neg_x_sq],
9412 x_shape.clone(),
9413 dtype,
9414 );
9415 let grad_x =
9416 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9417 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9418 }
9419 Op::Flip { dim } => {
9420 // y = flip(x, dim). Backward is another Flip on
9421 // the same dim — Flip is its own inverse
9422 // (involutive). One backward node, exact gradient.
9423 let x = inputs[0];
9424 let x_shape = node_shape(&graph_handle, x);
9425 let dtype = node_dtype(&graph_handle, x);
9426 let grad_x =
9427 push_node(&graph_handle, Op::Flip { dim }, vec![up_id], x_shape, dtype);
9428 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9429 }
9430 Op::Pad {
9431 padding,
9432 mode,
9433 value: _,
9434 } => {
9435 // Backward delegates to Op::PadBackward — a single
9436 // node that handles all three modes uniformly via
9437 // its kernel. Constant: slice the unpadded region.
9438 // Reflect/Replicate: accumulate gradient at the
9439 // mirrored / replicated positions.
9440 let padding = padding.clone();
9441 let x = inputs[0];
9442 let x_shape = node_shape(&graph_handle, x);
9443 let dtype = node_dtype(&graph_handle, x);
9444 let grad_x = push_node(
9445 &graph_handle,
9446 Op::PadBackward {
9447 in_shape: x_shape.clone(),
9448 padding,
9449 mode,
9450 },
9451 vec![up_id],
9452 x_shape,
9453 dtype,
9454 );
9455 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9456 }
9457 Op::PadBackward { .. } => {
9458 // Backward helper — typically a leaf in autograd
9459 // (the upstream gradient itself never gets a
9460 // higher-order backward in v1). No-op arm for
9461 // exhaustiveness; if higher-order autograd needs
9462 // PadBackward's backward, that's its own scope.
9463 }
9464 Op::CumSum { dim } => {
9465 // y[..., i, ...] = sum_{k=0..=i} x[..., k, ...]
9466 // dL/dx[..., i, ...] = sum_{k=i..n} dL/dy[..., k, ...]
9467 // i.e. reverse cumsum. Express via Flip → CumSum → Flip.
9468 let x = inputs[0];
9469 let x_shape = node_shape(&graph_handle, x);
9470 let dtype = node_dtype(&graph_handle, x);
9471 let flip1 = push_node(
9472 &graph_handle,
9473 Op::Flip { dim },
9474 vec![up_id],
9475 x_shape.clone(),
9476 dtype,
9477 );
9478 let cs = push_node(
9479 &graph_handle,
9480 Op::CumSum { dim },
9481 vec![flip1],
9482 x_shape.clone(),
9483 dtype,
9484 );
9485 let grad_x =
9486 push_node(&graph_handle, Op::Flip { dim }, vec![cs], x_shape, dtype);
9487 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9488 }
9489 Op::Roll { dim, shift } => {
9490 // y = roll(x, dim, shift). Backward is the opposite
9491 // shift along the same dim. One backward node.
9492 let x = inputs[0];
9493 let x_shape = node_shape(&graph_handle, x);
9494 let dtype = node_dtype(&graph_handle, x);
9495 let grad_x = push_node(
9496 &graph_handle,
9497 Op::Roll { dim, shift: -shift },
9498 vec![up_id],
9499 x_shape,
9500 dtype,
9501 );
9502 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9503 }
9504 Op::Triu { diagonal } => {
9505 // y = triu(x, diagonal). Mask is a binary indicator
9506 // — gradient passes through kept positions and is
9507 // zero on the masked half. Same op on the upstream.
9508 let x = inputs[0];
9509 let x_shape = node_shape(&graph_handle, x);
9510 let dtype = node_dtype(&graph_handle, x);
9511 let grad_x = push_node(
9512 &graph_handle,
9513 Op::Triu { diagonal },
9514 vec![up_id],
9515 x_shape,
9516 dtype,
9517 );
9518 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9519 }
9520 Op::Tril { diagonal } => {
9521 // Mirror of Op::Triu — same mask gradient.
9522 let x = inputs[0];
9523 let x_shape = node_shape(&graph_handle, x);
9524 let dtype = node_dtype(&graph_handle, x);
9525 let grad_x = push_node(
9526 &graph_handle,
9527 Op::Tril { diagonal },
9528 vec![up_id],
9529 x_shape,
9530 dtype,
9531 );
9532 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9533 }
9534 Op::LogSoftmaxLastDim => {
9535 // grad_x = upstream - exp(y) * sum(upstream, last_dim, keepdim).
9536 // Folded into Op::LogSoftmaxLastDimBackward — takes
9537 // (forward_output, upstream), avoids re-evaluating
9538 // the softmax outside the kernel.
9539 let x = inputs[0];
9540 let x_shape = node_shape(&graph_handle, x);
9541 let dtype = node_dtype(&graph_handle, x);
9542 let grad_x = push_node(
9543 &graph_handle,
9544 Op::LogSoftmaxLastDimBackward,
9545 vec![id, up_id],
9546 x_shape,
9547 dtype,
9548 );
9549 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9550 }
9551 Op::LogSoftmaxLastDimBackward => {
9552 // Backward helper — no higher-order autograd in v1.
9553 }
9554 Op::MaskedFill { value: _ } => {
9555 // y = mask ? value : x. dy/dx = (mask == 0).
9556 // grad_x = MaskedFill(upstream, mask, value=0_of_dtype).
9557 // The mask is integer-only; no gradient flows to it.
9558 let x = inputs[0];
9559 let mask = inputs[1];
9560 let x_shape = node_shape(&graph_handle, x);
9561 let dtype = node_dtype(&graph_handle, x);
9562 let zero = match fuel_ir::Scalar::zero(dtype) {
9563 Ok(z) => z,
9564 Err(_) => {
9565 // A packed/scale dtype has no zero scalar. MaskedFill
9566 // on such a dtype is a build-time bug (a future D5
9567 // graph-build guard forbids it), so this is
9568 // unreachable in a well-formed graph. debug_assert
9569 // catches it in debug; release skips this gradient
9570 // rather than panicking (never-panic invariant).
9571 debug_assert!(false, "MaskedFill backward on non-real dtype {dtype:?}");
9572 continue;
9573 }
9574 };
9575 let grad_x = push_node(
9576 &graph_handle,
9577 Op::MaskedFill { value: zero },
9578 vec![up_id, mask],
9579 x_shape,
9580 dtype,
9581 );
9582 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9583 // No gradient to mask: it's discrete.
9584 }
9585 Op::Rem => {
9586 // y = a - floor(a/b) * b (PyTorch convention).
9587 // d/da = 1 (the floor term is treated as a constant
9588 // w.r.t. a almost everywhere; the actual
9589 // derivative has a Dirac component at
9590 // integer a/b ratios that we drop, matching
9591 // PyTorch's autograd convention).
9592 // d/db = -floor(a/b)
9593 // grad_a = upstream
9594 // grad_b = upstream * (-floor(a/b))
9595 let a = inputs[0];
9596 let b = inputs[1];
9597 let a_shape = node_shape(&graph_handle, a);
9598 let dtype = node_dtype(&graph_handle, a);
9599 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9600 let div_ab =
9601 push_node(&graph_handle, Op::Div, vec![a, b], a_shape.clone(), dtype);
9602 let floor_div = push_node(
9603 &graph_handle,
9604 Op::Floor,
9605 vec![div_ab],
9606 a_shape.clone(),
9607 dtype,
9608 );
9609 let neg_floor = push_node(
9610 &graph_handle,
9611 Op::Neg,
9612 vec![floor_div],
9613 a_shape.clone(),
9614 dtype,
9615 );
9616 let grad_b = push_node(
9617 &graph_handle,
9618 Op::Mul,
9619 vec![up_id, neg_floor],
9620 a_shape,
9621 dtype,
9622 );
9623 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9624 }
9625 Op::Rsqrt => {
9626 // y = x^(-1/2). dy/dx = -0.5 * x^(-3/2).
9627 // Identity: y² = 1/x, so x^(-3/2) = y/x = y * y² = y³.
9628 // grad_x = -0.5 * upstream * y³.
9629 // Reuses the forward output id for y; never touches
9630 // x directly (avoids the divide-by-zero singularity
9631 // that the obvious `-0.5 * upstream * y / x` form
9632 // would have).
9633 let x = inputs[0];
9634 let x_shape = node_shape(&graph_handle, x);
9635 let dtype = node_dtype(&graph_handle, x);
9636 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9637 let y_cu = push_node(
9638 &graph_handle,
9639 Op::Mul,
9640 vec![id, y_sq],
9641 x_shape.clone(),
9642 dtype,
9643 );
9644 let scaled = push_node(
9645 &graph_handle,
9646 Op::MulScalar(-0.5),
9647 vec![y_cu],
9648 x_shape.clone(),
9649 dtype,
9650 );
9651 let grad_x =
9652 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9653 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9654 }
9655 Op::Pow => {
9656 // y = pow(a, b).
9657 // d/da = b * pow(a, b-1)
9658 // d/db = y * ln(a)
9659 // grad_a = upstream * b * pow(a, b-1)
9660 // grad_b = upstream * y * ln(a)
9661 // The forward output `id` IS y; we reuse it.
9662 let a = inputs[0];
9663 let b = inputs[1];
9664 let a_shape = node_shape(&graph_handle, a);
9665 let dtype = node_dtype(&graph_handle, a);
9666 // d/da branch: pow(a, b - 1)
9667 let b_minus_one = push_node(
9668 &graph_handle,
9669 Op::AddScalar(-1.0),
9670 vec![b],
9671 a_shape.clone(),
9672 dtype,
9673 );
9674 let pow_a_bm1 = push_node(
9675 &graph_handle,
9676 Op::Pow,
9677 vec![a, b_minus_one],
9678 a_shape.clone(),
9679 dtype,
9680 );
9681 let b_times_pow = push_node(
9682 &graph_handle,
9683 Op::Mul,
9684 vec![b, pow_a_bm1],
9685 a_shape.clone(),
9686 dtype,
9687 );
9688 let grad_a = push_node(
9689 &graph_handle,
9690 Op::Mul,
9691 vec![up_id, b_times_pow],
9692 a_shape.clone(),
9693 dtype,
9694 );
9695 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9696 // d/db branch: y * ln(a)
9697 let log_a = push_node(&graph_handle, Op::Log, vec![a], a_shape.clone(), dtype);
9698 let y_log_a = push_node(
9699 &graph_handle,
9700 Op::Mul,
9701 vec![id, log_a],
9702 a_shape.clone(),
9703 dtype,
9704 );
9705 let grad_b =
9706 push_node(&graph_handle, Op::Mul, vec![up_id, y_log_a], a_shape, dtype);
9707 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9708 }
9709 Op::Gelu => {
9710 // y = 0.5 * x * (1 + erf(x/√2)).
9711 // dy/dx = Φ(x) + x · φ(x)
9712 // = 0.5 * (1 + erf(x/√2))
9713 // + x * (1/√(2π)) * exp(-x²/2)
9714 // where Φ is the standard-normal CDF (= y/x for x≠0;
9715 // we recompute it explicitly so the backward stays
9716 // safe at x=0) and φ is the PDF.
9717 //
9718 // Chain (12 nodes):
9719 // x_over_sqrt2 = MulScalar(1/√2)(x)
9720 // erf_arg = Erf(x_over_sqrt2)
9721 // plus_one = AddScalar(1.0)(erf_arg)
9722 // cdf_term = MulScalar(0.5)(plus_one)
9723 // x_sq = Sqr(x)
9724 // half_x_sq = MulScalar(0.5)(x_sq)
9725 // neg_half_x_sq= Neg(half_x_sq)
9726 // exp_term = Exp(neg_half_x_sq)
9727 // phi = MulScalar(1/√(2π))(exp_term)
9728 // pdf_term = Mul(x, phi)
9729 // d_gelu = Add(cdf_term, pdf_term)
9730 // grad_x = Mul(upstream, d_gelu)
9731 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
9732 // 1/√(2π) = 0.39894228040143267793994605993...
9733 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
9734 let x = inputs[0];
9735 let x_shape = node_shape(&graph_handle, x);
9736 let dtype = node_dtype(&graph_handle, x);
9737 // CDF half: 0.5 * (1 + erf(x/√2)).
9738 let x_over_sqrt2 = push_node(
9739 &graph_handle,
9740 Op::MulScalar(INV_SQRT_2),
9741 vec![x],
9742 x_shape.clone(),
9743 dtype,
9744 );
9745 let erf_arg = push_node(
9746 &graph_handle,
9747 Op::Erf,
9748 vec![x_over_sqrt2],
9749 x_shape.clone(),
9750 dtype,
9751 );
9752 let plus_one = push_node(
9753 &graph_handle,
9754 Op::AddScalar(1.0),
9755 vec![erf_arg],
9756 x_shape.clone(),
9757 dtype,
9758 );
9759 let cdf_term = push_node(
9760 &graph_handle,
9761 Op::MulScalar(0.5),
9762 vec![plus_one],
9763 x_shape.clone(),
9764 dtype,
9765 );
9766 // PDF half: x * (1/√(2π)) * exp(-x²/2).
9767 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9768 let half_x_sq = push_node(
9769 &graph_handle,
9770 Op::MulScalar(0.5),
9771 vec![x_sq],
9772 x_shape.clone(),
9773 dtype,
9774 );
9775 let neg_half_x_sq = push_node(
9776 &graph_handle,
9777 Op::Neg,
9778 vec![half_x_sq],
9779 x_shape.clone(),
9780 dtype,
9781 );
9782 let exp_term = push_node(
9783 &graph_handle,
9784 Op::Exp,
9785 vec![neg_half_x_sq],
9786 x_shape.clone(),
9787 dtype,
9788 );
9789 let phi = push_node(
9790 &graph_handle,
9791 Op::MulScalar(INV_SQRT_2PI),
9792 vec![exp_term],
9793 x_shape.clone(),
9794 dtype,
9795 );
9796 let pdf_term =
9797 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
9798 // Sum the two halves and apply upstream.
9799 let d_gelu = push_node(
9800 &graph_handle,
9801 Op::Add,
9802 vec![cdf_term, pdf_term],
9803 x_shape.clone(),
9804 dtype,
9805 );
9806 let grad_x =
9807 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
9808 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9809 }
9810 Op::Equal | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => {
9811 // Comparison family: handled by `NoGradientBinaryRule`
9812 // via `dispatch_gradient`. The `if let Some(grads) =
9813 // dispatch_gradient(...) { continue; }` block above
9814 // intercepts before we get here. This arm exists only
9815 // for exhaustiveness; it should be unreachable in
9816 // practice. Keeping it as a no-op rather than
9817 // `unreachable!()` defends against a future hand-edit
9818 // that removes the dispatcher arm by mistake — the
9819 // graph still terminates traversal cleanly.
9820 }
9821 Op::Cast(_) => {
9822 // Forward: y = cast(x, target_dtype).
9823 // Backward: dL/dx = cast(upstream, source_dtype).
9824 let x = inputs[0];
9825 let x_dtype = node_dtype(&graph_handle, x);
9826 let x_shape = node_shape(&graph_handle, x);
9827 let grad_x = push_node(
9828 &graph_handle,
9829 Op::Cast(x_dtype),
9830 vec![up_id],
9831 x_shape,
9832 x_dtype,
9833 );
9834 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9835 }
9836 Op::SumAll => {
9837 // Forward: y = sum(x), scalar.
9838 // Backward: dL/dx = broadcast_to(upstream, x.shape).
9839 let x = inputs[0];
9840 let x_shape = node_shape(&graph_handle, x);
9841 let dtype = node_dtype(&graph_handle, x);
9842 let grad_x = push_node(
9843 &graph_handle,
9844 Op::BroadcastTo(x_shape.clone()),
9845 vec![up_id],
9846 x_shape,
9847 dtype,
9848 );
9849 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9850 }
9851 Op::MeanAll => {
9852 // Forward: y = mean(x) = sum(x) / n, scalar.
9853 // Backward: dL/dx = broadcast_to(upstream / n, x.shape).
9854 // We build `ones / n` as a constant of shape x.shape
9855 // and multiply by broadcast_to(upstream, x.shape).
9856 // Simpler: broadcast upstream, then divide by an n-const.
9857 let x = inputs[0];
9858 let x_shape = node_shape(&graph_handle, x);
9859 let dtype = node_dtype(&graph_handle, x);
9860 let n_elem = x_shape.elem_count();
9861 let broadcast_up = push_node(
9862 &graph_handle,
9863 Op::BroadcastTo(x_shape.clone()),
9864 vec![up_id],
9865 x_shape.clone(),
9866 dtype,
9867 );
9868 let n_const =
9869 build_filled_const(&graph_handle, x_shape.clone(), dtype, n_elem as f64);
9870 let grad_x = push_node(
9871 &graph_handle,
9872 Op::Div,
9873 vec![broadcast_up, n_const],
9874 x_shape,
9875 dtype,
9876 );
9877 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9878 }
9879 Op::BroadcastTo(_) => {
9880 // Forward: y = broadcast_to(x, target).
9881 // Backward: dL/dx = reduce_sum_to(upstream, x.shape) —
9882 // sum away every dim that was expanded or newly added.
9883 let x = inputs[0];
9884 let x_shape = node_shape(&graph_handle, x);
9885 let dtype = node_dtype(&graph_handle, x);
9886 let grad_x = push_node(
9887 &graph_handle,
9888 Op::ReduceSumTo(x_shape.clone()),
9889 vec![up_id],
9890 x_shape,
9891 dtype,
9892 );
9893 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9894 }
9895 Op::Reshape(_) => {
9896 // Forward: y = reshape(x, target). Data unchanged.
9897 // Backward: reshape upstream back to x.shape.
9898 let x = inputs[0];
9899 let x_shape = node_shape(&graph_handle, x);
9900 let dtype = node_dtype(&graph_handle, x);
9901 let grad_x = push_node(
9902 &graph_handle,
9903 Op::Reshape(x_shape.clone()),
9904 vec![up_id],
9905 x_shape,
9906 dtype,
9907 );
9908 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9909 }
9910 Op::Contiguize => {
9911 // Forward: y = contiguize(x). Identity at the
9912 // value level; only the layout differs. Backward:
9913 // pass upstream through unchanged. The
9914 // downstream `accumulate_grad` will sum this
9915 // into x's gradient regardless of x's own layout.
9916 let x = inputs[0];
9917 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
9918 }
9919 Op::Unsqueeze { dim: _ } => {
9920 // Forward: y = unsqueeze(x, dim) — inserts a size-1
9921 // axis without touching bytes. Backward: drop that
9922 // axis. Bytes are unchanged either direction; a
9923 // Reshape to x.shape is the simplest expression of
9924 // "same bytes, different rank" that the executor
9925 // handles natively.
9926 let x = inputs[0];
9927 let x_shape = node_shape(&graph_handle, x);
9928 let dtype = node_dtype(&graph_handle, x);
9929 let grad_x = push_node(
9930 &graph_handle,
9931 Op::Reshape(x_shape.clone()),
9932 vec![up_id],
9933 x_shape,
9934 dtype,
9935 );
9936 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9937 }
9938 Op::Squeeze { dim } => {
9939 // Forward: y = squeeze(x, dim) — drops a size-1 axis,
9940 // metadata-only. Backward: re-insert the axis at the
9941 // same position via Unsqueeze. Both directions are
9942 // metadata-only views (no bytes touched).
9943 let x = inputs[0];
9944 let x_shape = node_shape(&graph_handle, x);
9945 let dtype = node_dtype(&graph_handle, x);
9946 let grad_x = push_node(
9947 &graph_handle,
9948 Op::Unsqueeze { dim },
9949 vec![up_id],
9950 x_shape,
9951 dtype,
9952 );
9953 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9954 }
9955 Op::ReduceSumTo(_) => {
9956 // Forward: y = reduce_sum_to(x, target).
9957 // Backward: broadcast upstream back to x.shape.
9958 let x = inputs[0];
9959 let x_shape = node_shape(&graph_handle, x);
9960 let dtype = node_dtype(&graph_handle, x);
9961 let grad_x = push_node(
9962 &graph_handle,
9963 Op::BroadcastTo(x_shape.clone()),
9964 vec![up_id],
9965 x_shape,
9966 dtype,
9967 );
9968 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9969 }
9970 Op::MaxAll | Op::MinAll => {
9971 // For y = max(x) (or min), the gradient is an
9972 // indicator at the argmax positions, distributed
9973 // across ties. Expressed without a dedicated argmax
9974 // op using the Step trick:
9975 //
9976 // broadcasted_y = broadcast_to(y, x.shape)
9977 // diff = broadcasted_y - x (for Max)
9978 // | x - broadcasted_y (for Min)
9979 // indicator = ones - step(diff)
9980 // grad_x = broadcast_to(upstream, x.shape) * indicator
9981 //
9982 // At argmax positions `diff == 0`, `step(0) == 0`, so
9983 // the indicator is 1. Elsewhere `diff > 0` so step is
9984 // 1 and the indicator is 0. Ties share the gradient.
9985 let x = inputs[0];
9986 let x_shape = node_shape(&graph_handle, x);
9987 let dtype = node_dtype(&graph_handle, x);
9988 let is_max = matches!(op, Op::MaxAll);
9989 let broadcasted_y = push_node(
9990 &graph_handle,
9991 Op::BroadcastTo(x_shape.clone()),
9992 vec![id],
9993 x_shape.clone(),
9994 dtype,
9995 );
9996 let diff = if is_max {
9997 push_node(
9998 &graph_handle,
9999 Op::Sub,
10000 vec![broadcasted_y, x],
10001 x_shape.clone(),
10002 dtype,
10003 )
10004 } else {
10005 push_node(
10006 &graph_handle,
10007 Op::Sub,
10008 vec![x, broadcasted_y],
10009 x_shape.clone(),
10010 dtype,
10011 )
10012 };
10013 let step_diff =
10014 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10015 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10016 let indicator = push_node(
10017 &graph_handle,
10018 Op::Sub,
10019 vec![ones, step_diff],
10020 x_shape.clone(),
10021 dtype,
10022 );
10023 let broadcast_up = push_node(
10024 &graph_handle,
10025 Op::BroadcastTo(x_shape.clone()),
10026 vec![up_id],
10027 x_shape.clone(),
10028 dtype,
10029 );
10030 let grad_x = push_node(
10031 &graph_handle,
10032 Op::Mul,
10033 vec![broadcast_up, indicator],
10034 x_shape,
10035 dtype,
10036 );
10037 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10038 }
10039 Op::SumDim(dim) => {
10040 // Insert a size-1 at `dim` via reshape, then broadcast
10041 // back to x.shape.
10042 let x = inputs[0];
10043 let x_shape = node_shape(&graph_handle, x);
10044 let dtype = node_dtype(&graph_handle, x);
10045 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10046 let reshaped = push_node(
10047 &graph_handle,
10048 Op::Reshape(keepdim_shape.clone()),
10049 vec![up_id],
10050 keepdim_shape,
10051 dtype,
10052 );
10053 let grad_x = push_node(
10054 &graph_handle,
10055 Op::BroadcastTo(x_shape.clone()),
10056 vec![reshaped],
10057 x_shape,
10058 dtype,
10059 );
10060 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10061 }
10062 Op::MeanDim(dim) => {
10063 // SumDim-style backward, then divide by the reduced dim size.
10064 let x = inputs[0];
10065 let x_shape = node_shape(&graph_handle, x);
10066 let dtype = node_dtype(&graph_handle, x);
10067 let reduced_size = x_shape.dims()[dim];
10068 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10069 let reshaped = push_node(
10070 &graph_handle,
10071 Op::Reshape(keepdim_shape.clone()),
10072 vec![up_id],
10073 keepdim_shape,
10074 dtype,
10075 );
10076 let broadcast = push_node(
10077 &graph_handle,
10078 Op::BroadcastTo(x_shape.clone()),
10079 vec![reshaped],
10080 x_shape.clone(),
10081 dtype,
10082 );
10083 let n_const = build_filled_const(
10084 &graph_handle,
10085 x_shape.clone(),
10086 dtype,
10087 reduced_size as f64,
10088 );
10089 let grad_x = push_node(
10090 &graph_handle,
10091 Op::Div,
10092 vec![broadcast, n_const],
10093 x_shape,
10094 dtype,
10095 );
10096 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10097 }
10098 Op::MaxDim(dim) | Op::MinDim(dim) => {
10099 // Same indicator trick as MaxAll/MinAll, but apply the
10100 // "reshape to keepdim then broadcast" pattern to both
10101 // the forward output and upstream before multiplying.
10102 let x = inputs[0];
10103 let x_shape = node_shape(&graph_handle, x);
10104 let dtype = node_dtype(&graph_handle, x);
10105 let is_max = matches!(op, Op::MaxDim(_));
10106 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10107 let y_keepdim = push_node(
10108 &graph_handle,
10109 Op::Reshape(keepdim_shape.clone()),
10110 vec![id],
10111 keepdim_shape.clone(),
10112 dtype,
10113 );
10114 let broadcasted_y = push_node(
10115 &graph_handle,
10116 Op::BroadcastTo(x_shape.clone()),
10117 vec![y_keepdim],
10118 x_shape.clone(),
10119 dtype,
10120 );
10121 let diff = if is_max {
10122 push_node(
10123 &graph_handle,
10124 Op::Sub,
10125 vec![broadcasted_y, x],
10126 x_shape.clone(),
10127 dtype,
10128 )
10129 } else {
10130 push_node(
10131 &graph_handle,
10132 Op::Sub,
10133 vec![x, broadcasted_y],
10134 x_shape.clone(),
10135 dtype,
10136 )
10137 };
10138 let step_diff =
10139 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10140 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10141 let indicator = push_node(
10142 &graph_handle,
10143 Op::Sub,
10144 vec![ones, step_diff],
10145 x_shape.clone(),
10146 dtype,
10147 );
10148 let up_keepdim = push_node(
10149 &graph_handle,
10150 Op::Reshape(keepdim_shape.clone()),
10151 vec![up_id],
10152 keepdim_shape,
10153 dtype,
10154 );
10155 let broadcast_up = push_node(
10156 &graph_handle,
10157 Op::BroadcastTo(x_shape.clone()),
10158 vec![up_keepdim],
10159 x_shape.clone(),
10160 dtype,
10161 );
10162 let grad_x = push_node(
10163 &graph_handle,
10164 Op::Mul,
10165 vec![broadcast_up, indicator],
10166 x_shape,
10167 dtype,
10168 );
10169 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10170 }
10171 // Phase 7.6 step 5 (2026-05-11): the legacy
10172 // `Op::SoftmaxLastDim` / `Op::LayerNormLastDim` /
10173 // `Op::RmsNormLastDim` / `Op::Rope` /
10174 // `Op::Conv2D` / `Op::FusedLinear` arms have been
10175 // dropped together with the variants themselves; the
10176 // `Op::Fused(fid, _)` arm below dispatches per id and
10177 // is the single source of truth for migrated forward
10178 // ops' backward.
10179 Op::ArgMaxDim(_) | Op::ArgMinDim(_) => {
10180 // Argmax/argmin produce integer indices, which are
10181 // non-differentiable. Panic rather than silently
10182 // zero-propagating — if the user has one of these in
10183 // their differentiated graph, they've almost
10184 // certainly made a mistake.
10185 panic!(
10186 "backward: ArgMaxDim/ArgMinDim produce integer \
10187 indices and cannot be differentiated through. \
10188 Use MaxDim/MinDim if you want a differentiable \
10189 selection."
10190 );
10191 }
10192 Op::ReduceMaxTo(_) => {
10193 // Forward: y = reduce_max_to(x, target).
10194 // Backward: route upstream to position(s) where
10195 // x equals its per-window max via the fused
10196 // backward helper Op::Fused(REDUCE_MAX_TO_BACKWARD,
10197 // _) (takes (x, upstream) and emits grad_x of
10198 // x.shape). Tied maxes share the gradient equally
10199 // (fair-share subgradient). Note this is the
10200 // backward of a *primitive* (Op::ReduceMaxTo),
10201 // not a fused forward — no BackwardKind::Fused
10202 // edge in the registry drives this; the explicit
10203 // emission is the source of truth.
10204 let x = inputs[0];
10205 let x_shape = node_shape(&graph_handle, x);
10206 let dtype = node_dtype(&graph_handle, x);
10207 let grad_x = push_node(
10208 &graph_handle,
10209 Op::Fused(
10210 crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD,
10211 crate::registry::FusedOpParams::ReduceMaxToBackward,
10212 ),
10213 vec![x, up_id],
10214 x_shape,
10215 dtype,
10216 );
10217 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10218 }
10219 // Phase 7.6 step 5 (final, 2026-05-11): legacy
10220 // `Op::QMatMul` arm dropped with the variant; QMatMul
10221 // backward panics via the Op::Fused arm below.
10222 // Phase 7.6 step 5 (2026-05-11): the legacy
10223 // `Op::SoftmaxLastDimBackward | Op::LayerNormLastDimBackward |
10224 // Op::RmsNormLastDimBackward | Op::ReduceMaxToBackward`
10225 // higher-order panic arm has been dropped together
10226 // with the variants themselves. The Op::Fused arm
10227 // below panics for those four ids.
10228 Op::IndexSelect { dim } => {
10229 // Forward: out = index_select(data, dim, indices).
10230 // Backward: grad_data = index_add(zeros_like(data), dim, indices, upstream).
10231 let data = inputs[0];
10232 let idx = inputs[1];
10233 let data_shape = node_shape(&graph_handle, data);
10234 let dtype = node_dtype(&graph_handle, data);
10235 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10236 let grad_data = push_node(
10237 &graph_handle,
10238 Op::IndexAdd { dim },
10239 vec![zeros, idx, up_id],
10240 data_shape,
10241 dtype,
10242 );
10243 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10244 // Index tensor is itself non-differentiable (integer dtype).
10245 }
10246 Op::Gather { dim } => {
10247 // Forward: out = gather(data, dim, indices).
10248 // Backward: grad_data = scatter_add(zeros_like(data), dim, indices, upstream).
10249 let data = inputs[0];
10250 let idx = inputs[1];
10251 let data_shape = node_shape(&graph_handle, data);
10252 let dtype = node_dtype(&graph_handle, data);
10253 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10254 let grad_data = push_node(
10255 &graph_handle,
10256 Op::ScatterAdd { dim },
10257 vec![zeros, idx, up_id],
10258 data_shape,
10259 dtype,
10260 );
10261 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10262 }
10263 Op::IndexAdd { dim } => {
10264 // Forward: out = index_add(base, dim, indices, src).
10265 // Backward:
10266 // grad_base = upstream (pass-through — base flows
10267 // through the non-indexed positions and
10268 // the accumulated positions don't zero
10269 // it out, they add to it)
10270 // grad_src = index_select(upstream, dim, indices)
10271 // (the pieces of upstream that came from
10272 // src in the forward).
10273 let base = inputs[0];
10274 let idx = inputs[1];
10275 let src = inputs[2];
10276 let src_shape = node_shape(&graph_handle, src);
10277 let dtype = node_dtype(&graph_handle, src);
10278 // grad_base: upstream passes through.
10279 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10280 // grad_src: select from upstream at the indices.
10281 let grad_src = push_node(
10282 &graph_handle,
10283 Op::IndexSelect { dim },
10284 vec![up_id, idx],
10285 src_shape,
10286 dtype,
10287 );
10288 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10289 }
10290 Op::Concat { dim } => {
10291 // Forward: out = concat(inputs.., dim).
10292 // Backward: split upstream along `dim` into one slice per
10293 // input at the cumulative offset, routing each slice to its
10294 // input. N-ary (unroll_scan stacks N per-step ys into a
10295 // single Concat; the SSM/Hopfield BPTT unroll relies on
10296 // this). Duplicate inputs accumulate via accumulate_grad.
10297 let mut start = 0usize;
10298 for &inp in &inputs {
10299 let in_shape = node_shape(&graph_handle, inp);
10300 let dtype = node_dtype(&graph_handle, inp);
10301 let len = in_shape.dims()[dim];
10302 let grad_in = push_node(
10303 &graph_handle,
10304 Op::Slice { dim, start, len },
10305 vec![up_id],
10306 in_shape,
10307 dtype,
10308 );
10309 accumulate_grad(&mut upstream, inp, grad_in, &graph_handle);
10310 start += len;
10311 }
10312 }
10313 Op::Slice { dim, start, len: _ } => {
10314 // Forward: out = slice(x, dim, start, len).
10315 // Backward: build a zeros tensor of x.shape, then
10316 // scatter the upstream into the slice range. We use
10317 // a concat of three pieces: left zeros, upstream,
10318 // right zeros (along `dim`).
10319 let x = inputs[0];
10320 let x_shape = node_shape(&graph_handle, x);
10321 let dtype = node_dtype(&graph_handle, x);
10322 let x_dims = x_shape.dims();
10323 let dim_size = x_dims[dim];
10324 let up_len = x_dims[dim].min(node_shape(&graph_handle, up_id).dims()[dim]);
10325 let left_len = start;
10326 let right_len = dim_size - start - up_len;
10327 // Build left zero pad if needed.
10328 let mut pieces: Vec<NodeId> = Vec::new();
10329 if left_len > 0 {
10330 let mut left_dims: Vec<usize> = x_dims.to_vec();
10331 left_dims[dim] = left_len;
10332 let left_shape = Shape::from_dims(&left_dims);
10333 pieces.push(build_filled_const(&graph_handle, left_shape, dtype, 0.0));
10334 }
10335 pieces.push(up_id);
10336 if right_len > 0 {
10337 let mut right_dims: Vec<usize> = x_dims.to_vec();
10338 right_dims[dim] = right_len;
10339 let right_shape = Shape::from_dims(&right_dims);
10340 pieces.push(build_filled_const(&graph_handle, right_shape, dtype, 0.0));
10341 }
10342 // Fold concat-left-to-right.
10343 let mut current = pieces[0];
10344 let mut current_dims: Vec<usize> = {
10345 let n = graph_handle.read().unwrap();
10346 n.node(current).shape.dims().to_vec()
10347 };
10348 for &next in &pieces[1..] {
10349 let next_dims: Vec<usize> = {
10350 let n = graph_handle.read().unwrap();
10351 n.node(next).shape.dims().to_vec()
10352 };
10353 let mut combined = current_dims.clone();
10354 combined[dim] = current_dims[dim] + next_dims[dim];
10355 let combined_shape = Shape::from_dims(&combined);
10356 current = push_node(
10357 &graph_handle,
10358 Op::Concat { dim },
10359 vec![current, next],
10360 combined_shape,
10361 dtype,
10362 );
10363 current_dims = combined;
10364 }
10365 accumulate_grad(&mut upstream, x, current, &graph_handle);
10366 }
10367 Op::AddScalar(_) => {
10368 // y = x + c, dy/dx = 1. Upstream passes through.
10369 let x = inputs[0];
10370 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10371 }
10372 Op::MulScalar(c) => {
10373 // y = x * c, dy/dx = c. Multiply upstream by c via
10374 // another MulScalar node.
10375 let x = inputs[0];
10376 let x_shape = node_shape(&graph_handle, x);
10377 let dtype = node_dtype(&graph_handle, x);
10378 let grad_x =
10379 push_node(&graph_handle, Op::MulScalar(c), vec![up_id], x_shape, dtype);
10380 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10381 }
10382 Op::PowI(n) => {
10383 // y = x^n, dy/dx = n * x^(n-1).
10384 // grad_x = upstream * n * x^(n-1). Emitted as a
10385 // single fused PowIBackward node; the executor
10386 // routes it to baracuda's `unary_powi_backward_*`
10387 // kernel (alpha.31) on CUDA, or falls back to the
10388 // primitive decomposition (PowI(n-1) → MulScalar →
10389 // Mul) on backends that haven't registered the
10390 // fused kernel.
10391 let x = inputs[0];
10392 let x_shape = node_shape(&graph_handle, x);
10393 let dtype = node_dtype(&graph_handle, x);
10394 let grad_x = push_node(
10395 &graph_handle,
10396 Op::Fused(
10397 crate::registry::FusedOps::POWI_BACKWARD,
10398 crate::registry::FusedOpParams::PowIBackward { exp: n },
10399 ),
10400 vec![x, up_id],
10401 x_shape,
10402 dtype,
10403 );
10404 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10405 }
10406 Op::Clamp { min, max } => {
10407 // Subgradient: 1 where min <= x <= max, 0 elsewhere.
10408 // Expressed via (step(x - min) - step(x - max))
10409 // which is 1 in the interior (x > min and x <= max...
10410 // actually step(0) = 0, so the right end is a bit
10411 // tricky). For a reference implementation the
10412 // simplest approach is a dedicated "clamp backward"
10413 // indicator. We build it out of the existing ops:
10414 //
10415 // lower_ok = step(x - min) // 1 where x > min
10416 // upper_ok = step(max - x) // 1 where x < max
10417 // indicator = lower_ok * upper_ok
10418 // grad_x = upstream * indicator
10419 //
10420 // This underestimates the gradient on the exact
10421 // boundary by a measure-zero amount — standard.
10422 let x = inputs[0];
10423 let x_shape = node_shape(&graph_handle, x);
10424 let dtype = node_dtype(&graph_handle, x);
10425 let min_shifted = push_node(
10426 &graph_handle,
10427 Op::AddScalar(-min),
10428 vec![x],
10429 x_shape.clone(),
10430 dtype,
10431 );
10432 let lower_ok = push_node(
10433 &graph_handle,
10434 Op::Step,
10435 vec![min_shifted],
10436 x_shape.clone(),
10437 dtype,
10438 );
10439 let max_minus_x = push_node(
10440 &graph_handle,
10441 Op::MulScalar(-1.0),
10442 vec![x],
10443 x_shape.clone(),
10444 dtype,
10445 );
10446 let max_minus_x = push_node(
10447 &graph_handle,
10448 Op::AddScalar(max),
10449 vec![max_minus_x],
10450 x_shape.clone(),
10451 dtype,
10452 );
10453 let upper_ok = push_node(
10454 &graph_handle,
10455 Op::Step,
10456 vec![max_minus_x],
10457 x_shape.clone(),
10458 dtype,
10459 );
10460 let indicator = push_node(
10461 &graph_handle,
10462 Op::Mul,
10463 vec![lower_ok, upper_ok],
10464 x_shape.clone(),
10465 dtype,
10466 );
10467 let grad_x = push_node(
10468 &graph_handle,
10469 Op::Mul,
10470 vec![up_id, indicator],
10471 x_shape,
10472 dtype,
10473 );
10474 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10475 }
10476 Op::Maximum => {
10477 // y_i = max(a_i, b_i). Gradient flows to whichever
10478 // input was the max at that position:
10479 // mask_a = step(a - b) (1 where a > b, else 0)
10480 // mask_b = 1 - mask_a (approximately — at ties
10481 // gradient goes to b due to
10482 // step(0) = 0)
10483 // grad_a = upstream * mask_a
10484 // grad_b = upstream * mask_b
10485 let a = inputs[0];
10486 let b = inputs[1];
10487 let shape = node_shape(&graph_handle, a);
10488 let dtype = node_dtype(&graph_handle, a);
10489 let diff = push_node(&graph_handle, Op::Sub, vec![a, b], shape.clone(), dtype);
10490 let mask_a =
10491 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10492 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10493 let mask_b = push_node(
10494 &graph_handle,
10495 Op::Sub,
10496 vec![ones, mask_a],
10497 shape.clone(),
10498 dtype,
10499 );
10500 let grad_a = push_node(
10501 &graph_handle,
10502 Op::Mul,
10503 vec![up_id, mask_a],
10504 shape.clone(),
10505 dtype,
10506 );
10507 let grad_b =
10508 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10509 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10510 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10511 }
10512 Op::Minimum => {
10513 // Symmetric to Maximum. mask_a = step(b - a).
10514 let a = inputs[0];
10515 let b = inputs[1];
10516 let shape = node_shape(&graph_handle, a);
10517 let dtype = node_dtype(&graph_handle, a);
10518 let diff = push_node(&graph_handle, Op::Sub, vec![b, a], shape.clone(), dtype);
10519 let mask_a =
10520 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10521 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10522 let mask_b = push_node(
10523 &graph_handle,
10524 Op::Sub,
10525 vec![ones, mask_a],
10526 shape.clone(),
10527 dtype,
10528 );
10529 let grad_a = push_node(
10530 &graph_handle,
10531 Op::Mul,
10532 vec![up_id, mask_a],
10533 shape.clone(),
10534 dtype,
10535 );
10536 let grad_b =
10537 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10538 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10539 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10540 }
10541 Op::ScatterAdd { dim } => {
10542 // Forward: out = scatter_add(base, dim, indices, src).
10543 // Backward:
10544 // grad_base = upstream (pass-through)
10545 // grad_src = gather(upstream, dim, indices)
10546 let base = inputs[0];
10547 let idx = inputs[1];
10548 let src = inputs[2];
10549 let src_shape = node_shape(&graph_handle, src);
10550 let dtype = node_dtype(&graph_handle, src);
10551 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10552 let grad_src = push_node(
10553 &graph_handle,
10554 Op::Gather { dim },
10555 vec![up_id, idx],
10556 src_shape,
10557 dtype,
10558 );
10559 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10560 }
10561 Op::Copy { .. } => {
10562 // Forward: out = copy(x, target). Backward: the
10563 // gradient flows back to `x`'s original device, so
10564 // the reverse would be another Copy. The source
10565 // device is x's residency — we don't have the typed
10566 // "where was x?" here without tracking it, so we
10567 // fall back to the graph's placement hint on x (if
10568 // any) or trust the scheduler to re-insert the
10569 // correct copy during Phase 4. For Phase 3 we
10570 // assume inference-only use and pass upstream through.
10571 let x = inputs[0];
10572 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10573 }
10574 Op::Release => {
10575 // Release has no data output and no gradient to
10576 // propagate. Input is destroyed; any downstream
10577 // node that needs gradient through the original
10578 // tensor must get it from a sibling Copy's backward
10579 // path, not this one.
10580 }
10581 Op::Move { .. } => {
10582 // Move is Copy + destroy-source. For backward,
10583 // treat it the same as Copy — gradient flows back
10584 // through the move. The Phase 3-style assumption
10585 // still applies: we pass upstream through and rely
10586 // on the scheduler to re-insert the correct reverse
10587 // transfer in a training pass. For inference-only
10588 // use (the current case), this is a no-op.
10589 let x = inputs[0];
10590 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10591 }
10592 Op::WriteSlice { .. } => {
10593 // KV-cache writes are forward-only — the slab being
10594 // written *into* gets mutated in place, and the
10595 // source slab is read non-destructively. There is
10596 // no meaningful gradient through a mutating write
10597 // in fuel's tape-based autograd model. If a use
10598 // case needs differentiable scatter, the gradient
10599 // path is a `Gather` (read the slab back) plus an
10600 // accumulating `IndexAdd` on the destination —
10601 // express that explicitly in forward.
10602 panic!(
10603 "NodeHandle::backward: Op::WriteSlice is non-differentiable. \
10604 Use Gather + IndexAdd if you need a differentiable scatter."
10605 );
10606 }
10607 Op::WriteSliceRotating { .. } => {
10608 // Same forward-only contract as WriteSlice — the
10609 // ring buffer's bytes are mutated in place at a
10610 // dynamic offset. Sliding-window KV caches don't
10611 // need a gradient path; a differentiable scatter
10612 // is expressible as Gather + IndexAdd in forward.
10613 panic!(
10614 "NodeHandle::backward: Op::WriteSliceRotating is non-differentiable. \
10615 Use Gather + IndexAdd if you need a differentiable scatter."
10616 );
10617 }
10618 Op::WriteSliceDoff { .. } => {
10619 // Forward-only, like WriteSlice/WriteSliceRotating —
10620 // the KV-cache buffer is mutated in place at a
10621 // device-resident offset. Decode-time append; no
10622 // gradient path.
10623 panic!(
10624 "NodeHandle::backward: Op::WriteSliceDoff is non-differentiable. \
10625 Use Gather + IndexAdd if you need a differentiable scatter."
10626 );
10627 }
10628 // Phase 7.6 step 5 (2026-05-11): the legacy
10629 // `Op::Conv2D { stride, padding, groups }` backward
10630 // arm has been dropped together with the variant;
10631 // `Op::Fused(CONV2D, _)` below carries the full
10632 // backward logic (including the inner dW Conv2D
10633 // emission, which itself goes through Op::Fused).
10634 // Phase 7.6 step 4 (final): the builders for
10635 // ConvTranspose2D, FlashAttn, and PagedAttn now emit
10636 // `Op::Fused(<id>, _)`; these legacy backward arms
10637 // still fire for direct legacy-variant constructions
10638 // Phase 7.6 step 5 (final, 2026-05-11): the legacy
10639 // `Op::ConvTranspose2D` / `Op::FlashAttn` /
10640 // `Op::PagedAttn` / `Op::FusedLinear` backward arms
10641 // have all been dropped together with the variants;
10642 // `Op::Fused(<id>, _)` below panics for each id.
10643 Op::Fused(fid, params) => {
10644 // Per-id backward dispatch. Each migrated fused op
10645 // gets a branch here that emits the appropriate
10646 // gradient subgraph.
10647 if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM {
10648 // grad_x = softmax_last_dim_backward(y, upstream).
10649 // Phase 7.6 step 4 (backward-helper batch):
10650 // emits Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, _)
10651 // — the architecturally-correct registry form,
10652 // matching the BackwardKind::Fused edge on
10653 // SOFTMAX_LAST_DIM's entry.
10654 let x = inputs[0];
10655 let y_shape = node_shape(&graph_handle, id);
10656 let dtype = node_dtype(&graph_handle, id);
10657 let grad_x = push_node(
10658 &graph_handle,
10659 Op::Fused(
10660 crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
10661 crate::registry::FusedOpParams::SoftmaxLastDimBackward,
10662 ),
10663 vec![id, up_id],
10664 y_shape,
10665 dtype,
10666 );
10667 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10668 } else if fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM {
10669 // grad_x = layer_norm_last_dim_backward(x, upstream, eps).
10670 // Phase 7.6 step 4 (backward-helper batch): emits
10671 // registry form Op::Fused(LAYER_NORM_LAST_DIM_BACKWARD, _).
10672 let eps = match params {
10673 crate::registry::FusedOpParams::LayerNormLastDim { eps } => eps,
10674 _ => panic!(
10675 "NodeHandle::backward: Op::Fused(LAYER_NORM_LAST_DIM, _) \
10676 expected FusedOpParams::LayerNormLastDim, got {params:?}",
10677 ),
10678 };
10679 let x = inputs[0];
10680 let x_shape = node_shape(&graph_handle, x);
10681 let dtype = node_dtype(&graph_handle, x);
10682 let grad_x = push_node(
10683 &graph_handle,
10684 Op::Fused(
10685 crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
10686 crate::registry::FusedOpParams::LayerNormLastDimBackward { eps },
10687 ),
10688 vec![x, up_id],
10689 x_shape,
10690 dtype,
10691 );
10692 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10693 } else if fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM {
10694 // grad_x = rms_norm_last_dim_backward(x, upstream, eps).
10695 // Phase 7.6 step 4 (backward-helper batch): emits
10696 // registry form Op::Fused(RMS_NORM_LAST_DIM_BACKWARD, _).
10697 let eps = match params {
10698 crate::registry::FusedOpParams::RmsNormLastDim { eps } => eps,
10699 _ => panic!(
10700 "NodeHandle::backward: Op::Fused(RMS_NORM_LAST_DIM, _) \
10701 expected FusedOpParams::RmsNormLastDim, got {params:?}",
10702 ),
10703 };
10704 let x = inputs[0];
10705 let x_shape = node_shape(&graph_handle, x);
10706 let dtype = node_dtype(&graph_handle, x);
10707 let grad_x = push_node(
10708 &graph_handle,
10709 Op::Fused(
10710 crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
10711 crate::registry::FusedOpParams::RmsNormLastDimBackward { eps },
10712 ),
10713 vec![x, up_id],
10714 x_shape,
10715 dtype,
10716 );
10717 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10718 } else if fid == crate::registry::FusedOps::ROPE {
10719 // grad_x = rope(upstream, cos, -sin) — same
10720 // formula as the legacy Op::Rope arm above.
10721 // Emit the registry form for the backward
10722 // Rope node so the gradient subgraph routes
10723 // through the same Op::Fused dispatch as the
10724 // forward.
10725 let x = inputs[0];
10726 let cos = inputs[1];
10727 let sin = inputs[2];
10728 let x_shape = node_shape(&graph_handle, x);
10729 let sin_shape = node_shape(&graph_handle, sin);
10730 let dtype = node_dtype(&graph_handle, x);
10731 let neg_sin =
10732 push_node(&graph_handle, Op::Neg, vec![sin], sin_shape, dtype);
10733 let grad_x = push_node(
10734 &graph_handle,
10735 Op::Fused(
10736 crate::registry::FusedOps::ROPE,
10737 crate::registry::FusedOpParams::Rope,
10738 ),
10739 vec![up_id, cos, neg_sin],
10740 x_shape,
10741 dtype,
10742 );
10743 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10744 } else if fid == crate::registry::FusedOps::FUSED_LINEAR {
10745 // (a @ b) + bias backward — same three-grad
10746 // decomposition as the legacy Op::FusedLinear
10747 // arm above. We reuse MatMul backward (no
10748 // intermediate matmul output is cached, so the
10749 // grad computes from upstream + a, b directly).
10750 let a = inputs[0];
10751 let b = inputs[1];
10752 let bias = inputs[2];
10753 let a_shape = node_shape(&graph_handle, a);
10754 let b_shape = node_shape(&graph_handle, b);
10755 let bias_shape = node_shape(&graph_handle, bias);
10756 let dtype = node_dtype(&graph_handle, a);
10757 let b_t_shape = transposed_shape(&b_shape);
10758 let b_t =
10759 push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
10760 let grad_a = push_node(
10761 &graph_handle,
10762 Op::MatMul,
10763 vec![up_id, b_t],
10764 a_shape.clone(),
10765 dtype,
10766 );
10767 let a_t_shape = transposed_shape(&a_shape);
10768 let a_t =
10769 push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
10770 let grad_b =
10771 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
10772 let grad_bias = push_node(
10773 &graph_handle,
10774 Op::ReduceSumTo(bias_shape.clone()),
10775 vec![up_id],
10776 bias_shape,
10777 dtype,
10778 );
10779 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10780 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10781 accumulate_grad(&mut upstream, bias, grad_bias, &graph_handle);
10782 } else if fid == crate::registry::FusedOps::CONV2D {
10783 // Same backward formulation as the legacy
10784 // Op::Conv2D arm above. The inner Conv2D node
10785 // emitted for grad_w also goes through the
10786 // registry (Op::Fused(CONV2D, _)) so the
10787 // gradient subgraph routes consistently. The
10788 // ConvTranspose2D node stays as a primitive
10789 // variant until that op migrates in its own
10790 // step-4 commit.
10791 let (stride, padding, groups) = match params {
10792 crate::registry::FusedOpParams::Conv2D {
10793 stride,
10794 padding,
10795 groups,
10796 } => (stride, padding, groups),
10797 _ => panic!(
10798 "NodeHandle::backward: Op::Fused(CONV2D, _) \
10799 expected FusedOpParams::Conv2D, got {params:?}",
10800 ),
10801 };
10802 let x = inputs[0];
10803 let weight = inputs[1];
10804 let x_shape = node_shape(&graph_handle, x);
10805 let w_shape = node_shape(&graph_handle, weight);
10806 let dtype = node_dtype(&graph_handle, x);
10807
10808 // dX via transposed conv (see legacy arm for derivation).
10809 let x_dims = x_shape.dims();
10810 let w_dims = w_shape.dims();
10811 let dy_dims = node_shape(&graph_handle, id).dims().to_vec();
10812 let (sh, sw) = stride;
10813 let (ph, pw) = padding;
10814 let (kh, kw) = (w_dims[2], w_dims[3]);
10815 let (h_in, w_in) = (x_dims[2], x_dims[3]);
10816 let (dy_h, dy_w) = (dy_dims[2], dy_dims[3]);
10817 let base_h = (dy_h - 1) * sh + (kh - 1) + 1;
10818 let base_w = (dy_w - 1) * sw + (kw - 1) + 1;
10819 let want_h = h_in + 2 * ph;
10820 let want_w = w_in + 2 * pw;
10821 let out_pad_h = want_h.saturating_sub(base_h);
10822 let out_pad_w = want_w.saturating_sub(base_w);
10823 if groups != 1 {
10824 panic!(
10825 "NodeHandle::backward: Op::Fused(CONV2D) groups>1 \
10826 backward not yet implemented (got groups={groups}). \
10827 The stride/padding/groups=1 case is wired; grouped \
10828 backward needs a per-group weight reshape.",
10829 );
10830 }
10831 let perm_01 = vec![1usize, 0, 2, 3];
10832 // Phase 7.6 step 4 (final): emit registry form
10833 // for the inner dX node so the gradient subgraph
10834 // routes consistently through Op::Fused dispatch.
10835 let grad_x = push_node(
10836 &graph_handle,
10837 Op::Fused(
10838 crate::registry::FusedOps::CONV_TRANSPOSE2D,
10839 crate::registry::FusedOpParams::ConvTranspose2D {
10840 stride,
10841 padding,
10842 output_padding: (out_pad_h, out_pad_w),
10843 dilation: (1, 1),
10844 groups,
10845 },
10846 ),
10847 vec![up_id, weight],
10848 x_shape.clone(),
10849 dtype,
10850 );
10851 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10852
10853 // dW via correlation expressed as a conv2d.
10854 if sh != 1 || sw != 1 {
10855 panic!(
10856 "NodeHandle::backward: Op::Fused(CONV2D) stride>1 \
10857 backward not yet implemented (got stride={stride:?}). \
10858 Conv2D needs a `dilation` field to express this \
10859 without composing extra ops.",
10860 );
10861 }
10862 let x_swapped_shape = {
10863 let d = x_dims;
10864 Shape::from_dims(&[d[1], d[0], d[2], d[3]])
10865 };
10866 let x_swapped = push_node(
10867 &graph_handle,
10868 Op::Permute(perm_01.clone()),
10869 vec![x],
10870 x_swapped_shape,
10871 dtype,
10872 );
10873 let dy_swapped_shape =
10874 Shape::from_dims(&[dy_dims[1], dy_dims[0], dy_dims[2], dy_dims[3]]);
10875 let dy_swapped = push_node(
10876 &graph_handle,
10877 Op::Permute(perm_01.clone()),
10878 vec![up_id],
10879 dy_swapped_shape,
10880 dtype,
10881 );
10882 let conv_out_shape =
10883 Shape::from_dims(&[w_dims[1], w_dims[0], w_dims[2], w_dims[3]]);
10884 let grad_w_pre_transpose = push_node(
10885 &graph_handle,
10886 Op::Fused(
10887 crate::registry::FusedOps::CONV2D,
10888 crate::registry::FusedOpParams::Conv2D {
10889 stride: (1, 1),
10890 padding,
10891 groups: 1,
10892 },
10893 ),
10894 vec![x_swapped, dy_swapped],
10895 conv_out_shape,
10896 dtype,
10897 );
10898 let grad_w = push_node(
10899 &graph_handle,
10900 Op::Permute(perm_01),
10901 vec![grad_w_pre_transpose],
10902 w_shape,
10903 dtype,
10904 );
10905 accumulate_grad(&mut upstream, weight, grad_w, &graph_handle);
10906
10907 // Bias (if present): sum dY over N, H, W via
10908 // ReduceSumTo([1, Cout, 1, 1]) then reshape to
10909 // [Cout]. Same path as the legacy arm.
10910 if inputs.len() >= 3 {
10911 let bias = inputs[2];
10912 let bias_shape = node_shape(&graph_handle, bias);
10913 let cout_4d = Shape::from_dims(&[1, dy_dims[1], 1, 1]);
10914 let reduced = push_node(
10915 &graph_handle,
10916 Op::ReduceSumTo(cout_4d.clone()),
10917 vec![up_id],
10918 cout_4d,
10919 dtype,
10920 );
10921 let grad_b = push_node(
10922 &graph_handle,
10923 Op::Reshape(bias_shape.clone()),
10924 vec![reduced],
10925 bias_shape,
10926 dtype,
10927 );
10928 accumulate_grad(&mut upstream, bias, grad_b, &graph_handle);
10929 }
10930 } else if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD
10931 || fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD
10932 || fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
10933 || fid == crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD
10934 {
10935 // Higher-order gradients through backward
10936 // helpers panic.
10937 panic!(
10938 "backward: higher-order gradients through \
10939 softmax/layer_norm/rms_norm/reduce_max_to backward \
10940 helpers are not yet supported in the MVP."
10941 );
10942 } else if fid == crate::registry::FusedOps::CONV_TRANSPOSE2D {
10943 // Higher-order grad of the transposed conv
10944 // isn't needed for Conv2D's backward (which
10945 // only consumes the forward output). Adding
10946 // it requires the same dilation-as-stride
10947 // trick as Conv2D's dW. Punt until a real
10948 // consumer asks for it.
10949 panic!(
10950 "NodeHandle::backward: ConvTranspose2D does \
10951 not yet have its own gradient rule \
10952 (only used in the forward path of \
10953 Conv2D's backward).",
10954 );
10955 } else if fid == crate::registry::FusedOps::FLASH_ATTN {
10956 // Emit three backward nodes: dQ via
10957 // FLASH_ATTN_BACKWARD_Q, dK via _K, dV via _V.
10958 // Each takes (q, k, v, dO, [alibi]) and
10959 // recomputes the softmax state independently
10960 // in CPU's math-definition path. GPU kernels
10961 // (when they ship) can fuse the recompute.
10962 let q = inputs[0];
10963 let k = inputs[1];
10964 let v = inputs[2];
10965 let alibi = inputs.get(3).copied();
10966 let q_shape = node_shape(&graph_handle, q);
10967 let k_shape = node_shape(&graph_handle, k);
10968 let v_shape = node_shape(&graph_handle, v);
10969 let dtype = node_dtype(&graph_handle, q);
10970 let (scale, causal, wl, wr, sc) = match params {
10971 crate::registry::FusedOpParams::FlashAttn {
10972 softmax_scale,
10973 causal,
10974 window_size_left,
10975 window_size_right,
10976 softcap,
10977 // Backward over the static (full-K) flash
10978 // only; the runtime-k_len capacity form is
10979 // forward-only (decode). k_len is ignored
10980 // here.
10981 k_len: _,
10982 } => (
10983 softmax_scale,
10984 causal,
10985 window_size_left,
10986 window_size_right,
10987 softcap,
10988 ),
10989 other => panic!(
10990 "NodeHandle::backward: FlashAttn node carries \
10991 unexpected params {other:?}",
10992 ),
10993 };
10994 let bw_params = crate::registry::FusedOpParams::FlashAttnBackward {
10995 softmax_scale: scale,
10996 causal,
10997 window_size_left: wl,
10998 window_size_right: wr,
10999 softcap: sc,
11000 };
11001 let mut bw_inputs = vec![q, k, v, up_id];
11002 if let Some(a) = alibi {
11003 bw_inputs.push(a);
11004 }
11005 let grad_q = push_node(
11006 &graph_handle,
11007 Op::Fused(
11008 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_Q,
11009 bw_params.clone(),
11010 ),
11011 bw_inputs.clone(),
11012 q_shape,
11013 dtype,
11014 );
11015 let grad_k = push_node(
11016 &graph_handle,
11017 Op::Fused(
11018 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_K,
11019 bw_params.clone(),
11020 ),
11021 bw_inputs.clone(),
11022 k_shape,
11023 dtype,
11024 );
11025 let grad_v = push_node(
11026 &graph_handle,
11027 Op::Fused(crate::registry::FusedOps::FLASH_ATTN_BACKWARD_V, bw_params),
11028 bw_inputs,
11029 v_shape,
11030 dtype,
11031 );
11032 accumulate_grad(&mut upstream, q, grad_q, &graph_handle);
11033 accumulate_grad(&mut upstream, k, grad_k, &graph_handle);
11034 accumulate_grad(&mut upstream, v, grad_v, &graph_handle);
11035 } else if fid == crate::registry::FusedOps::PAGED_ATTN {
11036 // Paged attention is decode-side only by
11037 // construction (variable-length KV cache, no
11038 // training pass writes through it). No
11039 // gradient rule.
11040 panic!(
11041 "NodeHandle::backward: PagedAttn is \
11042 decode-only; no gradient rule exists.",
11043 );
11044 } else if fid == crate::registry::FusedOps::QMATMUL {
11045 // Quantized matmul: weights are frozen
11046 // bytes; activation gradient isn't
11047 // implemented today. Dequantize-then-matmul
11048 // is the workaround if differentiable
11049 // quantized inference is needed.
11050 panic!(
11051 "backward: QMatMul is not differentiable \
11052 (quantized weights are frozen). Use a \
11053 dequantize + standard matmul if you \
11054 need gradients through this input."
11055 );
11056 } else {
11057 panic!(
11058 "NodeHandle::backward: Op::Fused id {fid:?} has no \
11059 backward arm wired yet. This is a programming \
11060 bug — extend the match when the op migrates \
11061 to the registry.",
11062 );
11063 }
11064 }
11065 Op::Alloc { .. } => {
11066 // Op::Alloc is a source op (zero inputs) that
11067 // produces a fresh zero-init buffer. No upstream
11068 // gradient to propagate — the alloc's "input" is
11069 // the abstract notion of fresh memory, which has
11070 // no derivative. Mirrors Op::Const's treatment.
11071 // (Phase 3a of bridge-retirement; see
11072 // `WorkItemKind::Alloc` in fuel-storage.)
11073 }
11074 Op::ZeroFill => {
11075 // Op::ZeroFill writes deterministic constants
11076 // (zeros) to its input's bytes. The output is
11077 // a constant tensor; gradient w.r.t. it is
11078 // meaningless. Like Op::Const / Op::Alloc, no
11079 // gradient propagates back.
11080 }
11081 Op::ScatterIntoSlot { .. } => {
11082 // Item 4 IR-only scaffold — the backward graph
11083 // emits this op as the producer's gradient
11084 // assembler, but `ScatterIntoSlot` itself has no
11085 // backward (it's a structural op composing
11086 // already-differentiated slot gradients). No
11087 // gradient propagates back; matches the
11088 // Op::Const / Op::Alloc / Op::ZeroFill treatment.
11089 }
11090 Op::Branch { .. } => {
11091 // PR-A0 inert scaffold. `Op::Branch` is the
11092 // multi-path phi/merge node; it is never constructed
11093 // in A0, so this arm is unreachable today. When the
11094 // PR-A1 builders land, gradient flow through a Branch
11095 // routes via its arms (each an `inputs[i]` route exit)
11096 // and reconverges at `reconverge_at` — not through the
11097 // merge node itself. `backward` is infallible
11098 // (`-> GradMap`), so the no-panic inert handling is to
11099 // drop the gradient at the structural node, matching
11100 // the Op::Const / Op::ScatterIntoSlot treatment above.
11101 // The real per-arm routing lands with the builders.
11102 }
11103 Op::Scan { .. } => {
11104 // Defensive `panic!` — `backward() -> GradMap` is infallible
11105 // (no Err channel), so this is an internal-error guard in the
11106 // same infallible walk that already panics for QMatMul /
11107 // PagedAttn, NOT a recoverable typed error. It is unreachable
11108 // via the public builders: the C3 pre-pass
11109 // (lower_scans_for_backward) unrolls every Op::Scan to
11110 // primitives before the topo order is taken, and the builders
11111 // always emit the View consumers the pre-pass's remap +
11112 // never-hang guard lower away. Reaching here means the
11113 // pre-pass did not run (an internal bug).
11114 panic!(
11115 "NodeHandle::backward: Op::Scan reached the reverse walk un-lowered — \
11116 the C3 lower_scans_for_backward pre-pass did not run (internal bug)."
11117 );
11118 }
11119 Op::ScanPlaceholder { .. } => {
11120 // Inert body-hole leaf (no inputs) — never a real
11121 // differentiation target. Drop gradient like Op::Const /
11122 // Op::Iota; a live backward never reaches it (the body is
11123 // materialized by unroll_scan before any realize).
11124 }
11125 Op::View { slot } | Op::ViewOwned { slot } => {
11126 // Multi-output projection — item 4 backward
11127 // composition (Option C, 2026-06-01).
11128 //
11129 // Forward (Op::View): shares the producer's
11130 // bundled Storage Arc and exposes one slot's
11131 // typed window. Forward (Op::ViewOwned): memcpys
11132 // the slot's bytes into a fresh Storage.
11133 //
11134 // Backward: scatter the upstream gradient into
11135 // the slot's byte range of a fresh zero-bundle of
11136 // the producer's primary shape, then accumulate
11137 // that partial-bundle gradient as the producer's
11138 // input gradient. Multiple View consumers of the
11139 // same producer accumulate via the standard
11140 // sum-of-partials path:
11141 // bundle_grad =
11142 // ScatterIntoSlot{0}(0, g_y) +
11143 // ScatterIntoSlot{1}(0, g_state) + ...
11144 //
11145 // **Status (item 4)**: IR-level wiring only —
11146 // emits the scatter chain in the backward graph,
11147 // but no Op::ScatterIntoSlot kernel is registered.
11148 // The production multi-output producers
11149 // (SelectiveScan, SsdChunkScan) are
11150 // `BackwardKind::NotDifferentiable`, so autograd
11151 // panics at the producer before this scatter is
11152 // realized. When a differentiable multi-output op
11153 // materializes (Mamba training, FSCE loss+grad
11154 // fused), it lights up the ScatterIntoSlot CPU
11155 // kernel + tests alongside its own backward.
11156 let producer = inputs[0];
11157 let producer_shape = node_shape(&graph_handle, producer);
11158 let producer_dtype = node_dtype(&graph_handle, producer);
11159 let zero = build_filled_const(
11160 &graph_handle,
11161 producer_shape.clone(),
11162 producer_dtype,
11163 0.0,
11164 );
11165 let scattered = push_node(
11166 &graph_handle,
11167 Op::ScatterIntoSlot { slot },
11168 vec![zero, up_id],
11169 producer_shape,
11170 producer_dtype,
11171 );
11172 accumulate_grad(&mut upstream, producer, scattered, &graph_handle);
11173 }
11174 Op::ReluInplace => {
11175 // Same backward as Op::Relu — d(relu(x))/dx = step(x).
11176 // The view-aware `derive_ordering` (Phase 4a) pins
11177 // `Op::Step(x)` to run BEFORE Op::ReluInplace, so the
11178 // step kernel sees x's original bytes.
11179 let x = inputs[0];
11180 let x_shape = node_shape(&graph_handle, x);
11181 let dtype = node_dtype(&graph_handle, x);
11182 let step_x =
11183 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
11184 let grad_x =
11185 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
11186 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11187 }
11188 Op::SiluInplace => {
11189 // Same backward as Op::Silu — grad_x = upstream * (s + y*(1-s))
11190 // where s = sigmoid(x) and y = silu(x) = this in-place node's
11191 // output. The post-mutation bytes at `id` ARE silu(x) (the
11192 // in-place op runs after the Sigmoid(x) read because of the
11193 // alias-aware ordering pass). `Op::Sigmoid(x)` reads x's
11194 // pre-mutation bytes; `Op::Mul(id, ...)` reads post-mutation
11195 // bytes — both correct.
11196 let x = inputs[0];
11197 let x_shape = node_shape(&graph_handle, x);
11198 let dtype = node_dtype(&graph_handle, x);
11199 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
11200 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
11201 let one_minus_s = push_node(
11202 &graph_handle,
11203 Op::Sub,
11204 vec![ones, s],
11205 x_shape.clone(),
11206 dtype,
11207 );
11208 let y_times_1ms = push_node(
11209 &graph_handle,
11210 Op::Mul,
11211 vec![id, one_minus_s],
11212 x_shape.clone(),
11213 dtype,
11214 );
11215 let inner = push_node(
11216 &graph_handle,
11217 Op::Add,
11218 vec![s, y_times_1ms],
11219 x_shape.clone(),
11220 dtype,
11221 );
11222 let grad_x =
11223 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
11224 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11225 }
11226 Op::TanhInplace => {
11227 // Same backward as Op::Tanh — grad_x = upstream * (1 - y²)
11228 // where y = tanh(x) = this in-place node's output. `Op::Sqr(id)`
11229 // reads post-mutation bytes (= tanh(x) by definition of the
11230 // in-place op); no need to reference x at all.
11231 let x = inputs[0];
11232 let y_shape = node_shape(&graph_handle, id);
11233 let dtype = node_dtype(&graph_handle, id);
11234 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
11235 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11236 let one_minus_sq = push_node(
11237 &graph_handle,
11238 Op::Sub,
11239 vec![ones, y_sq],
11240 y_shape.clone(),
11241 dtype,
11242 );
11243 let grad_x = push_node(
11244 &graph_handle,
11245 Op::Mul,
11246 vec![up_id, one_minus_sq],
11247 y_shape,
11248 dtype,
11249 );
11250 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11251 }
11252 Op::SigmoidInplace => {
11253 // Same backward as Op::Sigmoid — grad_x = upstream * y * (1 - y)
11254 // where y = sigmoid(x) = this in-place node's output.
11255 let x = inputs[0];
11256 let y_shape = node_shape(&graph_handle, id);
11257 let dtype = node_dtype(&graph_handle, id);
11258 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11259 let one_minus_y = push_node(
11260 &graph_handle,
11261 Op::Sub,
11262 vec![ones, id],
11263 y_shape.clone(),
11264 dtype,
11265 );
11266 let y_times_1my = push_node(
11267 &graph_handle,
11268 Op::Mul,
11269 vec![id, one_minus_y],
11270 y_shape.clone(),
11271 dtype,
11272 );
11273 let grad_x = push_node(
11274 &graph_handle,
11275 Op::Mul,
11276 vec![up_id, y_times_1my],
11277 y_shape,
11278 dtype,
11279 );
11280 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11281 }
11282 Op::GeluTanhInplace => {
11283 // Same backward as Op::GeluTanh. The formula reads only the
11284 // pre-mutation input `x` (like SiluInplace's Sigmoid(x) read),
11285 // which the alias-aware ordering pass keeps ahead of the
11286 // in-place write.
11287 let x = inputs[0];
11288 let grad_x = build_gelu_tanh_grad(&graph_handle, x, up_id);
11289 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11290 }
11291 Op::NegInplace => {
11292 // Same backward as Op::Neg — grad_x = -upstream. No
11293 // dependency on x or y; Phase 4a ordering not needed.
11294 let x = inputs[0];
11295 let x_shape = node_shape(&graph_handle, x);
11296 let dtype = node_dtype(&graph_handle, x);
11297 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
11298 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11299 }
11300 Op::AbsInplace => {
11301 // Same backward as Op::Abs — grad_x = sign(x) * upstream.
11302 // `Op::Sign(x)` reads x's pre-mutation bytes (Phase 4a
11303 // pins the in-place op after the Sign read).
11304 let x = inputs[0];
11305 let x_shape = node_shape(&graph_handle, x);
11306 let dtype = node_dtype(&graph_handle, x);
11307 let sign_x =
11308 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
11309 let grad_x =
11310 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
11311 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11312 }
11313 Op::SqrInplace => {
11314 // Same backward as Op::Sqr — grad_x = 2x * upstream,
11315 // expressed as `x + x` to avoid a scalar broadcast.
11316 // `x + x` reads pre-mutation bytes (Phase 4a).
11317 let x = inputs[0];
11318 let x_shape = node_shape(&graph_handle, x);
11319 let dtype = node_dtype(&graph_handle, x);
11320 let two_x =
11321 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
11322 let grad_x =
11323 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
11324 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11325 }
11326 Op::SqrtInplace => {
11327 // Same backward as Op::Sqrt — y = √x, grad_x = upstream/(2y).
11328 // Reads only the forward output `id`, which is post-mutation =
11329 // √x by definition; no pre-mutation x access needed.
11330 let x = inputs[0];
11331 let x_shape = node_shape(&graph_handle, x);
11332 let dtype = node_dtype(&graph_handle, x);
11333 let two_y =
11334 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
11335 let grad_x =
11336 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
11337 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11338 }
11339 Op::RsqrtInplace => {
11340 // Same backward as Op::Rsqrt — y = x^(-1/2),
11341 // grad_x = -0.5 * upstream * y³. Reads forward output (id)
11342 // only — post-mutation = y by definition.
11343 let x = inputs[0];
11344 let x_shape = node_shape(&graph_handle, x);
11345 let dtype = node_dtype(&graph_handle, x);
11346 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11347 let y_cu = push_node(
11348 &graph_handle,
11349 Op::Mul,
11350 vec![id, y_sq],
11351 x_shape.clone(),
11352 dtype,
11353 );
11354 let scaled = push_node(
11355 &graph_handle,
11356 Op::MulScalar(-0.5),
11357 vec![y_cu],
11358 x_shape.clone(),
11359 dtype,
11360 );
11361 let grad_x =
11362 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11363 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11364 }
11365 Op::RecipInplace => {
11366 // Same backward as Op::Recip — y = 1/x, grad_x = -upstream * y².
11367 // Reads forward output (id) only — post-mutation = 1/x.
11368 let x = inputs[0];
11369 let x_shape = node_shape(&graph_handle, x);
11370 let dtype = node_dtype(&graph_handle, x);
11371 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11372 let up_y_sq = push_node(
11373 &graph_handle,
11374 Op::Mul,
11375 vec![up_id, y_sq],
11376 x_shape.clone(),
11377 dtype,
11378 );
11379 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
11380 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11381 }
11382 Op::ExpInplace => {
11383 // Same backward as Op::Exp — d(exp(x))/dx = exp(x) = y = id.
11384 // grad_x = upstream * y. Reads forward output (id) only.
11385 let x = inputs[0];
11386 let out_shape = node_shape(&graph_handle, id);
11387 let dtype = node_dtype(&graph_handle, id);
11388 let grad_x =
11389 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
11390 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11391 }
11392 Op::LogInplace => {
11393 // Same backward as Op::Log — grad_x = upstream / x.
11394 // `Op::Div(up, x)` reads pre-mutation bytes of x (Phase 4a).
11395 let x = inputs[0];
11396 let x_shape = node_shape(&graph_handle, x);
11397 let dtype = node_dtype(&graph_handle, x);
11398 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
11399 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11400 }
11401 Op::SinInplace => {
11402 // Same backward as Op::Sin — grad_x = upstream * cos(x).
11403 // `Op::Cos(x)` reads pre-mutation x via Phase 4a ordering.
11404 let x = inputs[0];
11405 let x_shape = node_shape(&graph_handle, x);
11406 let dtype = node_dtype(&graph_handle, x);
11407 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
11408 let grad_x =
11409 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
11410 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11411 }
11412 Op::CosInplace => {
11413 // Same backward as Op::Cos — grad_x = -(upstream * sin(x)).
11414 let x = inputs[0];
11415 let x_shape = node_shape(&graph_handle, x);
11416 let dtype = node_dtype(&graph_handle, x);
11417 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
11418 let up_sin = push_node(
11419 &graph_handle,
11420 Op::Mul,
11421 vec![up_id, sin_x],
11422 x_shape.clone(),
11423 dtype,
11424 );
11425 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
11426 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11427 }
11428 Op::SignInplace | Op::FloorInplace | Op::CeilInplace | Op::RoundInplace => {
11429 // Same backward as Op::{Sign, Floor, Ceil, Round} —
11430 // derivative is 0 almost everywhere; drop gradient
11431 // (no accumulation, mirroring Op::Step's pattern).
11432 }
11433 Op::ErfInplace => {
11434 // Same backward as Op::Erf — grad_x = upstream * (2/√π) * exp(-x²).
11435 // `Op::Sqr(x)` reads pre-mutation x via Phase 4a ordering.
11436 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
11437 let x = inputs[0];
11438 let x_shape = node_shape(&graph_handle, x);
11439 let dtype = node_dtype(&graph_handle, x);
11440 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11441 let neg_x_sq =
11442 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
11443 let exp_neg = push_node(
11444 &graph_handle,
11445 Op::Exp,
11446 vec![neg_x_sq],
11447 x_shape.clone(),
11448 dtype,
11449 );
11450 let scaled = push_node(
11451 &graph_handle,
11452 Op::MulScalar(TWO_OVER_SQRT_PI),
11453 vec![exp_neg],
11454 x_shape.clone(),
11455 dtype,
11456 );
11457 let grad_x =
11458 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11459 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11460 }
11461 Op::ClampInplace { min, max } => {
11462 // Same backward as Op::Clamp — indicator is 1 where
11463 // min ≤ x ≤ max, 0 elsewhere. Reads pre-mutation x via
11464 // Phase 4a ordering.
11465 let x = inputs[0];
11466 let x_shape = node_shape(&graph_handle, x);
11467 let dtype = node_dtype(&graph_handle, x);
11468 let min_shifted = push_node(
11469 &graph_handle,
11470 Op::AddScalar(-min),
11471 vec![x],
11472 x_shape.clone(),
11473 dtype,
11474 );
11475 let lower_ok = push_node(
11476 &graph_handle,
11477 Op::Step,
11478 vec![min_shifted],
11479 x_shape.clone(),
11480 dtype,
11481 );
11482 let neg_x = push_node(
11483 &graph_handle,
11484 Op::MulScalar(-1.0),
11485 vec![x],
11486 x_shape.clone(),
11487 dtype,
11488 );
11489 let max_minus_x = push_node(
11490 &graph_handle,
11491 Op::AddScalar(max),
11492 vec![neg_x],
11493 x_shape.clone(),
11494 dtype,
11495 );
11496 let upper_ok = push_node(
11497 &graph_handle,
11498 Op::Step,
11499 vec![max_minus_x],
11500 x_shape.clone(),
11501 dtype,
11502 );
11503 let indicator = push_node(
11504 &graph_handle,
11505 Op::Mul,
11506 vec![lower_ok, upper_ok],
11507 x_shape.clone(),
11508 dtype,
11509 );
11510 let grad_x = push_node(
11511 &graph_handle,
11512 Op::Mul,
11513 vec![up_id, indicator],
11514 x_shape,
11515 dtype,
11516 );
11517 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11518 }
11519 Op::PowIInplace(n) => {
11520 // Same backward as Op::PowI — single fused
11521 // POWI_BACKWARD node `(x, upstream) → exp · x^(exp-1) ·
11522 // upstream`. Reads pre-mutation x via Phase 4a ordering.
11523 let x = inputs[0];
11524 let x_shape = node_shape(&graph_handle, x);
11525 let dtype = node_dtype(&graph_handle, x);
11526 let grad_x = push_node(
11527 &graph_handle,
11528 Op::Fused(
11529 crate::registry::FusedOps::POWI_BACKWARD,
11530 crate::registry::FusedOpParams::PowIBackward { exp: n },
11531 ),
11532 vec![x, up_id],
11533 x_shape,
11534 dtype,
11535 );
11536 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11537 }
11538 Op::GeluInplace => {
11539 // Same backward as Op::Gelu — exact-GELU derivative
11540 // is Φ(x) + x·φ(x). Both halves read pre-mutation x via
11541 // Phase 4a ordering. Identical 12-node chain to Op::Gelu.
11542 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
11543 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
11544 let x = inputs[0];
11545 let x_shape = node_shape(&graph_handle, x);
11546 let dtype = node_dtype(&graph_handle, x);
11547 let x_over_sqrt2 = push_node(
11548 &graph_handle,
11549 Op::MulScalar(INV_SQRT_2),
11550 vec![x],
11551 x_shape.clone(),
11552 dtype,
11553 );
11554 let erf_arg = push_node(
11555 &graph_handle,
11556 Op::Erf,
11557 vec![x_over_sqrt2],
11558 x_shape.clone(),
11559 dtype,
11560 );
11561 let plus_one = push_node(
11562 &graph_handle,
11563 Op::AddScalar(1.0),
11564 vec![erf_arg],
11565 x_shape.clone(),
11566 dtype,
11567 );
11568 let cdf_term = push_node(
11569 &graph_handle,
11570 Op::MulScalar(0.5),
11571 vec![plus_one],
11572 x_shape.clone(),
11573 dtype,
11574 );
11575 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11576 let half_x_sq = push_node(
11577 &graph_handle,
11578 Op::MulScalar(0.5),
11579 vec![x_sq],
11580 x_shape.clone(),
11581 dtype,
11582 );
11583 let neg_half = push_node(
11584 &graph_handle,
11585 Op::Neg,
11586 vec![half_x_sq],
11587 x_shape.clone(),
11588 dtype,
11589 );
11590 let exp_term = push_node(
11591 &graph_handle,
11592 Op::Exp,
11593 vec![neg_half],
11594 x_shape.clone(),
11595 dtype,
11596 );
11597 let phi = push_node(
11598 &graph_handle,
11599 Op::MulScalar(INV_SQRT_2PI),
11600 vec![exp_term],
11601 x_shape.clone(),
11602 dtype,
11603 );
11604 let pdf_term =
11605 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
11606 let d_gelu = push_node(
11607 &graph_handle,
11608 Op::Add,
11609 vec![cdf_term, pdf_term],
11610 x_shape.clone(),
11611 dtype,
11612 );
11613 let grad_x =
11614 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
11615 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11616 }
11617 }
11618 }
11619
11620 GradMap {
11621 graph: graph_handle,
11622 forward_to_grad: upstream,
11623 }
11624 }
11625}
11626
11627/// Map from forward-graph node IDs to the IDs of their accumulated
11628/// backward-graph gradient nodes, returned by [`NodeHandle::backward`].
11629///
11630/// All gradient nodes live on the same graph as the forward nodes. Getting
11631/// a gradient by calling [`GradMap::get`] returns a new [`NodeHandle`] handle
11632/// pointing at the gradient node so callers can realize it, plug it into
11633/// further computation, or back-propagate through it again.
11634pub struct GradMap {
11635 graph: SharedGraph,
11636 forward_to_grad: HashMap<NodeId, NodeId>,
11637}
11638
11639impl GradMap {
11640 /// Get the gradient tensor for a forward tensor from the same graph.
11641 ///
11642 /// Returns `None` if the forward tensor was not reachable from the
11643 /// root passed to `backward` (i.e. not part of the computation being
11644 /// differentiated).
11645 ///
11646 /// # Panics
11647 ///
11648 /// Panics if any operand belongs to a different [`Graph`] than the one this
11649 /// builder is building into. Operand identity is graph-scoped and checked by
11650 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
11651 /// deliberate and replaces the hang a cross-graph handle used to produce.
11652 /// Build every operand from one graph, or use a `Result`-returning entry
11653 /// point where one exists.
11654 pub fn get(&self, forward: &NodeHandle) -> Option<NodeHandle> {
11655 assert!(
11656 Arc::ptr_eq(&self.graph, &forward.graph),
11657 "GradMap::get: tensor is from a different graph",
11658 );
11659 let &grad_id = self.forward_to_grad.get(&forward.id)?;
11660 Some(NodeHandle {
11661 graph: self.graph.clone(),
11662 id: grad_id,
11663 })
11664 }
11665
11666 /// Number of forward nodes that have a recorded gradient.
11667 pub fn len(&self) -> usize {
11668 self.forward_to_grad.len()
11669 }
11670
11671 /// Whether this map has no gradients (e.g. a backward over a lone const).
11672 pub fn is_empty(&self) -> bool {
11673 self.forward_to_grad.is_empty()
11674 }
11675}
11676
11677// -------- internal helpers shared by the backward pass --------------------
11678
11679/// Does the registry declare this fused op's backward to be "lower it via its
11680/// total `decompose`, then differentiate the primitives"?
11681fn lowers_for_backward(fid: crate::registry::FusedOpId) -> bool {
11682 crate::registry::default_registry()
11683 .entry(fid)
11684 .is_some_and(|e| e.backward == crate::registry::BackwardKind::Decompose)
11685}
11686
11687/// The generic decompose-backward hook (Op::Scan Phase 2, C3): before the
11688/// reverse walk takes its topo order, lower every reachable `Op::Scan` to
11689/// `bound` primitives and decompose the two SSM `Op::Fused` recipes into their
11690/// `Op::Scan` form, rewiring consumers so the walk sees only differentiable
11691/// primitives. BPTT differentiates the static-`bound` unroll (the runtime
11692/// early-exit predicate is a forward-only optimization, ignored here — spec C3
11693/// static-horizon note). Operates in place on the shared graph (a `backward()`
11694/// caller is a training step that wants the unrolled activations anyway).
11695/// Returns the (possibly remapped) root NodeId to walk from.
11696fn lower_scans_for_backward(graph: &SharedGraph, root: NodeId) -> NodeId {
11697 use std::collections::HashMap;
11698 let mut root = root;
11699 // helper: apply a remap to every consumer's inputs + the root, in place.
11700 fn apply_remap(graph: &SharedGraph, remap: &HashMap<NodeId, NodeId>, root: &mut NodeId) {
11701 if remap.is_empty() {
11702 return;
11703 }
11704 let mut g = graph.write().unwrap();
11705 let n = g.len();
11706 for nid in 0..n {
11707 let ilen = g.node(NodeId(nid)).inputs.len();
11708 for i in 0..ilen {
11709 let cur = g.node(NodeId(nid)).inputs[i];
11710 if let Some(&new) = remap.get(&cur) {
11711 g.rewrite_input(NodeId(nid), cur, new);
11712 }
11713 }
11714 }
11715 if let Some(&new) = remap.get(root) {
11716 *root = new;
11717 }
11718 }
11719
11720 // --- Pass 1: decompose every reachable Op::Fused whose registry entry declares
11721 // `BackwardKind::Decompose` (the SSM recipes into Op::Scan, which pass 2 then
11722 // unrolls; single-output recipes such as NF4/AWQ matmul and causal conv1d
11723 // straight to primitives). The registry is the source of truth: an id with
11724 // a hand-written backward arm in the reverse walk is `Fused(..)` or
11725 // `NotDifferentiable` there, never `Decompose`.
11726 {
11727 let targets: Vec<(
11728 NodeId,
11729 crate::registry::FusedOpId,
11730 crate::registry::FusedOpParams,
11731 )> = {
11732 let g = graph.read().unwrap();
11733 crate::topo_order(&g, root)
11734 .into_iter()
11735 .filter_map(|id| match &g.node(id).op {
11736 Op::Fused(fid, params) if lowers_for_backward(*fid) => {
11737 Some((id, *fid, params.clone()))
11738 }
11739 _ => None,
11740 })
11741 .collect()
11742 };
11743 let mut remap = HashMap::new();
11744 for (id, fid, params) in targets {
11745 if let Some(entry) = crate::registry::default_registry().entry(fid) {
11746 let y = {
11747 let mut g = graph.write().unwrap();
11748 (entry.decompose)(&mut g, id, ¶ms)
11749 };
11750 if y != id {
11751 remap.insert(id, y);
11752 // Collapse the fused node's slot-0 View consumers DIRECTLY to
11753 // the decompose output. Slot 0 is the primary value (the
11754 // multi-output authoring contract: Node.shape == slot-0
11755 // shape), and the SSM decompose re-presents its primary AS
11756 // slot 0, so `View{0}(y) == y`. Without this collapse the
11757 // outer View{0} survives into the reverse walk and emits an
11758 // `Op::ScatterIntoSlot` (which has no CPU realize kernel),
11759 // so realizing the gradient would fail. Slot-1 (last_state)
11760 // consumers keep their `View{1}(y)` re-projection via the
11761 // default input rewrite (remap[id] = y) and are not
11762 // differentiated on this path.
11763 let g = graph.read().unwrap();
11764 for nid in 0..g.len() {
11765 let node = g.node(NodeId(nid));
11766 if let Op::View { slot: 0 } | Op::ViewOwned { slot: 0 } = node.op
11767 && node.inputs.first() == Some(&id)
11768 {
11769 remap.insert(NodeId(nid), y);
11770 }
11771 }
11772 }
11773 }
11774 }
11775 apply_remap(graph, &remap, &mut root);
11776 }
11777
11778 // --- Pass 2: unroll every reachable Op::Scan to `bound` primitives.
11779 loop {
11780 let scans: Vec<(NodeId, usize, ScanEmit)> = {
11781 let g = graph.read().unwrap();
11782 crate::topo_order(&g, root)
11783 .into_iter()
11784 .filter_map(|id| match &g.node(id).op {
11785 Op::Scan { bound, emit, .. } => Some((id, *bound, *emit)),
11786 _ => None,
11787 })
11788 .collect()
11789 };
11790 if scans.is_empty() {
11791 break;
11792 }
11793 let mut remap = HashMap::new();
11794 for (scan_id, bound, emit) in scans {
11795 let (a, b) = {
11796 let mut g = graph.write().unwrap();
11797 match crate::scan::unroll_scan(&mut g, scan_id, bound) {
11798 Ok(pair) => pair,
11799 Err(_) => continue, // malformed scan: leave it; the C4 guard describes it.
11800 }
11801 };
11802 // Normalize to (slot 0 = stacked_ys, slots 1.. = final carries).
11803 //
11804 // GAP-303: `unroll_scan` now returns (selected, complementary) as
11805 // VECS. The `ys` side is always exactly one node; the carry side is
11806 // `n_carries` wide. At `n_carries == 1` this is byte-for-byte the old
11807 // behaviour -- one ys, one carry, slot 1 the only carry slot.
11808 let (ys_v, carries) = match emit {
11809 ScanEmit::All => (a, b),
11810 ScanEmit::Final => (b, a),
11811 };
11812 let Some(&slot0) = ys_v.first() else {
11813 continue; // malformed: no stacked ys; the C4 guard describes it.
11814 };
11815 // Remap the scan's View{slot}/ViewOwned{slot} consumers to the unroll outputs.
11816 let g = graph.read().unwrap();
11817 for nid in 0..g.len() {
11818 let node = g.node(NodeId(nid));
11819 if let Op::View { slot } | Op::ViewOwned { slot } = node.op
11820 && node.inputs.first() == Some(&scan_id)
11821 {
11822 // ⚠️ Slot 0 is `ys`; slot k>=1 is carry k-1. The old form was
11823 // `if slot == 0 { slot0 } else { slot1 }`, which folded EVERY
11824 // slot above 0 onto the single carry -- a fifth site of the
11825 // 2-slot assumption. Out-of-range slots are LEFT UNMAPPED for
11826 // the C4 guard rather than indexed (never-panic).
11827 let target = if slot == 0 {
11828 Some(slot0)
11829 } else {
11830 carries.get(slot as usize - 1).copied()
11831 };
11832 if let Some(t) = target {
11833 remap.insert(NodeId(nid), t);
11834 }
11835 }
11836 }
11837 }
11838 // Defensive never-hang guard: if a full pass lowered no scan to a
11839 // consumer remap (e.g. a malformed scan that unroll rejects, or a raw
11840 // scan producer with no View consumers), stop rather than re-scanning
11841 // the same unchanged graph forever. Any residual Op::Scan then reaches
11842 // the C4 defensive `panic!` guard (backward is infallible, so it cannot
11843 // return an error) — an internal-bug signal, never an infinite loop.
11844 if remap.is_empty() {
11845 break;
11846 }
11847 apply_remap(graph, &remap, &mut root);
11848 // Unrolled graphs contain no Op::Scan, so a well-formed graph terminates
11849 // in <= 2 iterations (the loop re-scans in case a decomposed body itself
11850 // contained a scan; the current SSM decompose does not).
11851 }
11852 root
11853}
11854
11855/// Read a node's shape without holding the borrow past the call site.
11856fn node_shape(graph: &SharedGraph, id: NodeId) -> Shape {
11857 graph.read().unwrap().node(id).shape.clone()
11858}
11859
11860/// Read a node's dtype without holding the borrow past the call site.
11861fn node_dtype(graph: &SharedGraph, id: NodeId) -> DType {
11862 graph.read().unwrap().node(id).dtype
11863}
11864
11865/// Shape with its last two dims swapped. Used by MatMul's backward rule
11866/// to construct transpose-node output shapes for any rank ≥ 2.
11867fn transposed_shape(shape: &Shape) -> Shape {
11868 let d = shape.dims();
11869 assert!(
11870 d.len() >= 2,
11871 "transposed_shape: expected rank ≥ 2, got {d:?}",
11872 );
11873 let rank = d.len();
11874 let mut out: Vec<usize> = d.to_vec();
11875 out.swap(rank - 2, rank - 1);
11876 Shape::from_dims(&out)
11877}
11878
11879/// Given a full tensor shape and a dim that was reduced away, produce the
11880/// keepdim shape — i.e. the full shape with size 1 at `dim`. Used by
11881/// axis-reduction backward rules to reshape the reduced upstream back to
11882/// a shape that broadcasts against the original input.
11883fn reshape_to_keepdim(full_dims: &[usize], dim: usize) -> Shape {
11884 assert!(
11885 dim < full_dims.len(),
11886 "reshape_to_keepdim: dim {dim} out of bounds for {full_dims:?}",
11887 );
11888 let mut out: Vec<usize> = full_dims.to_vec();
11889 out[dim] = 1;
11890 Shape::from_dims(&out)
11891}
11892
11893/// Validate that `src` can be broadcast to `dst` using NumPy rules:
11894/// right-align, pad the shorter shape with 1s on the left, and for each
11895/// aligned dimension the src size must equal the dst size or be 1.
11896fn check_broadcast_compatible(src: &[usize], dst: &[usize]) {
11897 assert!(
11898 src.len() <= dst.len(),
11899 "broadcast_to: source rank {} exceeds target rank {}",
11900 src.len(),
11901 dst.len(),
11902 );
11903 let pad = dst.len() - src.len();
11904 for (i, &s) in src.iter().enumerate() {
11905 let d = dst[pad + i];
11906 assert!(
11907 s == d || s == 1,
11908 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11909 pad + i,
11910 );
11911 }
11912}
11913
11914/// Result-returning sibling of [`check_broadcast_compatible`].
11915fn try_check_broadcast_compatible(
11916 src: &[usize],
11917 dst: &[usize],
11918) -> std::result::Result<(), fuel_ir::Error> {
11919 if src.len() > dst.len() {
11920 return Err(fuel_ir::Error::Msg(format!(
11921 "broadcast_to: source rank {} exceeds target rank {}",
11922 src.len(),
11923 dst.len(),
11924 ))
11925 .bt());
11926 }
11927 let pad = dst.len() - src.len();
11928 for (i, &s) in src.iter().enumerate() {
11929 let d = dst[pad + i];
11930 if s != d && s != 1 {
11931 return Err(fuel_ir::Error::Msg(format!(
11932 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11933 pad + i,
11934 ))
11935 .bt());
11936 }
11937 }
11938 Ok(())
11939}
11940
11941/// Compute the NumPy broadcast shape of two input shapes. Right-align,
11942/// pad the shorter with leading 1s, and take the element-wise max at
11943/// each position. Panics if the shapes are incompatible (neither can
11944/// expand to match the other at some dim).
11945fn compute_broadcast_shape(a: &[usize], b: &[usize]) -> Vec<usize> {
11946 let n = a.len().max(b.len());
11947 let a_pad = n - a.len();
11948 let b_pad = n - b.len();
11949 let mut out = Vec::with_capacity(n);
11950 for i in 0..n {
11951 let ai = if i < a_pad { 1 } else { a[i - a_pad] };
11952 let bi = if i < b_pad { 1 } else { b[i - b_pad] };
11953 let oi = if ai == bi {
11954 ai
11955 } else if ai == 1 {
11956 bi
11957 } else if bi == 1 {
11958 ai
11959 } else {
11960 panic!(
11961 "compute_broadcast_shape: incompatible shapes {a:?} vs {b:?} at axis {i}: {ai} vs {bi}",
11962 );
11963 };
11964 out.push(oi);
11965 }
11966 out
11967}
11968
11969/// Push a node to the graph and return its ID. Used by backward to append
11970/// gradient-computing nodes without going through the public builders,
11971/// which would re-validate shapes the backward pass has already derived.
11972fn push_node(
11973 graph: &SharedGraph,
11974 op: Op,
11975 inputs: Vec<NodeId>,
11976 shape: Shape,
11977 dtype: DType,
11978) -> NodeId {
11979 graph.write().unwrap().push(Node {
11980 op,
11981 inputs,
11982 shape,
11983 dtype,
11984 })
11985}
11986
11987/// Build a ones tensor of the given shape and dtype as a `Const` node.
11988/// Used to seed the initial upstream gradient at the root of the backward
11989/// pass (`dL/dL = 1`).
11990/// Backward of the tanh-approximation GELU, `y = 0.5 x (1 + tanh(u))` with
11991/// `u = c (x + k x^3)`, `c = sqrt(2/pi)`, `k = 0.044715`:
11992///
11993/// `dy/dx = 0.5 (1 + t) + 0.5 x (1 - t^2) c (1 + 3 k x^2)`, `t = tanh(u)`.
11994///
11995/// Returns `upstream * dy/dx` as a new node. Built from existing primitives
11996/// (no new Op); `t` is recomputed from `x` so the rule is safe at `x = 0`.
11997fn build_gelu_tanh_grad(graph: &SharedGraph, x: NodeId, upstream: NodeId) -> NodeId {
11998 // sqrt(2/pi), the constant the forward kernels use.
11999 const C: f64 = 0.797_884_560_802_865_4;
12000 const K: f64 = 0.044_715;
12001 let shape = node_shape(graph, x);
12002 let dtype = node_dtype(graph, x);
12003 let un = |op: Op, input: NodeId| push_node(graph, op, vec![input], shape.clone(), dtype);
12004 let x_sq = un(Op::Sqr, x);
12005 let x_cu = push_node(graph, Op::Mul, vec![x_sq, x], shape.clone(), dtype);
12006 let k_x_cu = un(Op::MulScalar(K), x_cu);
12007 let inner = push_node(graph, Op::Add, vec![x, k_x_cu], shape.clone(), dtype);
12008 let u = un(Op::MulScalar(C), inner);
12009 let t = un(Op::Tanh, u);
12010 // 0.5 (1 + t)
12011 let t_plus_one = un(Op::AddScalar(1.0), t);
12012 let half_one_plus_t = un(Op::MulScalar(0.5), t_plus_one);
12013 // 1 - t^2
12014 let t_sq = un(Op::Sqr, t);
12015 let ones = build_ones(graph, shape.clone(), dtype);
12016 let one_minus_t_sq = push_node(graph, Op::Sub, vec![ones, t_sq], shape.clone(), dtype);
12017 // du/dx = c + 3 c k x^2
12018 let scaled_x_sq = un(Op::MulScalar(3.0 * C * K), x_sq);
12019 let du = un(Op::AddScalar(C), scaled_x_sq);
12020 // 0.5 x (1 - t^2) du/dx
12021 let dt = push_node(
12022 graph,
12023 Op::Mul,
12024 vec![one_minus_t_sq, du],
12025 shape.clone(),
12026 dtype,
12027 );
12028 let x_dt = push_node(graph, Op::Mul, vec![x, dt], shape.clone(), dtype);
12029 let half_x_dt = un(Op::MulScalar(0.5), x_dt);
12030 let d_gelu = push_node(
12031 graph,
12032 Op::Add,
12033 vec![half_one_plus_t, half_x_dt],
12034 shape.clone(),
12035 dtype,
12036 );
12037 push_node(graph, Op::Mul, vec![upstream, d_gelu], shape, dtype)
12038}
12039
12040fn build_ones(graph: &SharedGraph, shape: Shape, dtype: DType) -> NodeId {
12041 build_filled_const(graph, shape, dtype, 1.0)
12042}
12043
12044/// Build a constant tensor of the given shape and dtype filled with
12045/// `value` (expressed as `f64` and converted to the target dtype). Used
12046/// by backward rules that need a scalar-valued broadcast, for example
12047/// `MeanAll`'s `1/n` factor expressed as "divide by an n-filled const."
12048///
12049/// Build RoPE cos/sin tables for a given `(base, start_pos, seq,
12050/// head_dim)`. Each returned `Vec<f32>` has shape `[seq, head_dim]`
12051/// (row-major) in the half-split layout [`NodeHandle::rope_with_tables`]
12052/// expects: positions `[:, :half]` and `[:, half:]` hold the same
12053/// value for the same `(p, i)`, so a single elementwise multiply with
12054/// `self` does the right thing alongside `rotate_half(self) * sin`.
12055///
12056/// Exposed as a free function so callers can share the tables across
12057/// many RoPE applications (e.g. every attention layer in a transformer
12058/// forward pass).
12059pub fn build_rope_tables(
12060 base: f64,
12061 start_pos: usize,
12062 seq: usize,
12063 head_dim: usize,
12064) -> (Vec<f32>, Vec<f32>) {
12065 assert!(
12066 head_dim.is_multiple_of(2),
12067 "build_rope_tables: head_dim {head_dim} must be even",
12068 );
12069 let half = head_dim / 2;
12070 let inv_freq: Vec<f64> = (0..half)
12071 .map(|i| base.powf(-2.0 * (i as f64) / (head_dim as f64)))
12072 .collect();
12073 build_rope_tables_with_inv_freq(&inv_freq, start_pos, seq, head_dim)
12074}
12075
12076/// [`build_rope_tables`] with the inverse frequencies supplied directly rather
12077/// than derived from a single `base`.
12078///
12079/// Every RoPE variant Fuel supports differs from the default in **exactly** this
12080/// vector: LLaMA-3.1's long-context scaling is a per-dimension transform of the
12081/// same `head_dim / 2` values, and the position loop below is bit-identical
12082/// either way. Splitting the frequency choice out is what lets a scaled model
12083/// reuse the whole decode path — the KV-cache forward, the held-graph persistent
12084/// forward, and their per-token rebinds — instead of needing a parallel copy of
12085/// each.
12086///
12087/// `inv_freq.len()` must be `head_dim / 2`.
12088pub fn build_rope_tables_with_inv_freq(
12089 inv_freq: &[f64],
12090 start_pos: usize,
12091 seq: usize,
12092 head_dim: usize,
12093) -> (Vec<f32>, Vec<f32>) {
12094 assert!(
12095 head_dim.is_multiple_of(2),
12096 "build_rope_tables_with_inv_freq: head_dim {head_dim} must be even",
12097 );
12098 let half = head_dim / 2;
12099 assert_eq!(
12100 inv_freq.len(),
12101 half,
12102 "build_rope_tables_with_inv_freq: inv_freq len {} != head_dim/2 {half}",
12103 inv_freq.len(),
12104 );
12105 let mut cos_data = vec![0.0_f32; seq * head_dim];
12106 let mut sin_data = vec![0.0_f32; seq * head_dim];
12107 for p in 0..seq {
12108 let pos = (start_pos + p) as f64;
12109 for (i, &freq) in inv_freq.iter().enumerate() {
12110 let theta = pos * freq;
12111 let c = theta.cos() as f32;
12112 let s = theta.sin() as f32;
12113 cos_data[p * head_dim + i] = c;
12114 cos_data[p * head_dim + i + half] = c;
12115 sin_data[p * head_dim + i] = s;
12116 sin_data[p * head_dim + i + half] = s;
12117 }
12118 }
12119 (cos_data, sin_data)
12120}
12121
12122/// Only float dtypes are supported here — integer/index tensors never
12123/// appear as gradients, so a `U32` call indicates a bug in a backward
12124/// rule rather than a missing feature.
12125///
12126/// Phase 7.5 G2: gradient consts are slot-populating Op::Const
12127/// nodes. Device is picked from any existing slot (the forward pass
12128/// always populated at least one slot-bearing leaf by the time
12129/// backward runs). For a CPU-rooted graph the device's
12130/// `storage_from_host_buffer_owned_dyn` is a zero-copy wrap; for
12131/// GPU-rooted, an H2D upload (matching today's eval_const path on
12132/// first realize).
12133fn build_filled_const(graph: &SharedGraph, shape: Shape, dtype: DType, value: f64) -> NodeId {
12134 let n = shape.elem_count();
12135 let buf = match dtype {
12136 DType::F32 => fuel_ir::HostBuffer::F32(vec![value as f32; n]),
12137 DType::F64 => fuel_ir::HostBuffer::F64(vec![value; n]),
12138 DType::BF16 => fuel_ir::HostBuffer::BF16(vec![fuel_ir::round::bf16_from_f64(value); n]),
12139 DType::F16 => fuel_ir::HostBuffer::F16(vec![fuel_ir::round::f16_from_f64(value); n]),
12140 other => panic!(
12141 "backward: build_filled_const: unsupported dtype {other:?} \
12142 (gradients are always floats — this would indicate a bug in \
12143 a backward rule that tried to differentiate through an \
12144 integer tensor)",
12145 ),
12146 };
12147 let device = pick_device_from_graph(graph);
12148 let backend_storage = device
12149 .storage_from_host_buffer_owned_dyn(buf)
12150 .expect("build_filled_const: storage_from_host_buffer_owned_dyn failed");
12151 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
12152 let id = push_node(graph, Op::Const, vec![], shape, dtype);
12153 graph.write().unwrap().set_storage(id, storage_arc);
12154 id
12155}
12156
12157/// G2 helper: walk the graph for any populated slot and return its
12158/// device. Used by gradient builders that don't have an explicit
12159/// device parameter — the graph always has at least one slot-bearing
12160/// Const leaf by the time backward() runs (the forward pass's inputs
12161/// are slot-rooted Const leaves), so this can be relied on.
12162fn pick_device_from_graph(graph: &SharedGraph) -> Arc<dyn fuel_backend_contract::DynBackendDevice> {
12163 let g = graph.read().unwrap();
12164 for i in 0..g.len() {
12165 if let Some(slot_arc) = g.storage_for(NodeId(i)) {
12166 return slot_arc.read().unwrap().device();
12167 }
12168 }
12169 panic!(
12170 "build_filled_const: graph has no populated storage slots; backward \
12171 requires at least one slot-bearing Const leaf to pick a gradient \
12172 device from. Was the forward pass built with G2-migrated \
12173 constructors (from_f32/etc. with explicit &Device)?"
12174 )
12175}
12176
12177/// Accumulate a new gradient contribution into the upstream map.
12178///
12179/// If `forward_id` already has an upstream gradient, emit an `Add` node to
12180/// sum the two contributions. If not, record the new one as-is. This is
12181/// the multi-variable chain rule in its operational form: when a forward
12182/// node has multiple downstream consumers, the gradients from each must
12183/// be summed.
12184fn accumulate_grad(
12185 upstream: &mut HashMap<NodeId, NodeId>,
12186 forward_id: NodeId,
12187 new_grad_id: NodeId,
12188 graph: &SharedGraph,
12189) {
12190 match upstream.get(&forward_id).copied() {
12191 None => {
12192 upstream.insert(forward_id, new_grad_id);
12193 }
12194 Some(existing_id) => {
12195 let shape = node_shape(graph, forward_id);
12196 let dtype = node_dtype(graph, forward_id);
12197 let combined = push_node(graph, Op::Add, vec![existing_id, new_grad_id], shape, dtype);
12198 upstream.insert(forward_id, combined);
12199 }
12200 }
12201}
12202
12203#[cfg(test)]
12204mod tests {
12205 use super::*;
12206
12207 /// Phase 7.5 G2: tests need a real device to allocate slot
12208 /// storage through the new constructor API. `cpu_dev()` returns a
12209 /// stable singleton CpuBackendDevice handle so every call site can
12210 /// just pass `cpu_dev()` without per-test boilerplate.
12211 fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
12212 static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
12213 std::sync::OnceLock::new();
12214 D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
12215 }
12216
12217 /// Operands for a `[2, 64]` activation, `N = 8`, `group_size = 64`
12218 /// (`zeros_w = 2`): weight `[8, 8]` U32, zeros `[8, 2]` U32, scales
12219 /// `[8, 16]` of `scale_dtype`-compatible data.
12220 fn awq_builder_operands(
12221 act: &NodeHandle,
12222 weight_f32: bool,
12223 ) -> (NodeHandle, NodeHandle, NodeHandle) {
12224 let weight = if weight_f32 {
12225 act.const_f32_like(vec![0.0_f32; 64], Shape::from_dims(&[8, 8]))
12226 .unwrap()
12227 } else {
12228 act.const_u32_like(vec![0u32; 64], Shape::from_dims(&[8, 8]))
12229 .unwrap()
12230 };
12231 let zeros = act
12232 .const_u32_like(vec![0u32; 16], Shape::from_dims(&[8, 2]))
12233 .unwrap();
12234 let scales = act
12235 .const_f16_like(vec![f16::ONE; 128], Shape::from_dims(&[8, 16]))
12236 .unwrap();
12237 (weight, zeros, scales)
12238 }
12239
12240 /// `Tensor::awq_matmul`'s public builder end-to-end: a well-formed call
12241 /// produces a `Fused(AWQ_MATMUL, ..)` node with the right output
12242 /// shape/dtype. The decompose MATH is tested at the registry level
12243 /// (`registry::awq_matmul::tests`); this just confirms the builder's
12244 /// own validation + node construction work from the public API.
12245 #[test]
12246 fn awq_matmul_builder_produces_expected_node() {
12247 let act =
12248 NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12249 .unwrap();
12250 let (weight, zeros, scales) = awq_builder_operands(&act, false);
12251 let out = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12252 assert_eq!(out.shape().dims(), &[2, 8]);
12253 assert_eq!(out.dtype(), DType::F32);
12254 assert!(matches!(
12255 out.graph.read().unwrap().node(out.id).op,
12256 Op::Fused(id, _) if id == crate::registry::FusedOps::AWQ_MATMUL
12257 ));
12258 }
12259
12260 /// Born-red: a non-U32 `weight` must panic with a clear message, not
12261 /// silently misinterpret bytes.
12262 #[test]
12263 #[should_panic(expected = "weight must be U32")]
12264 fn awq_matmul_builder_panics_on_wrong_weight_dtype() {
12265 let act =
12266 NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12267 .unwrap();
12268 let (weight, zeros, scales) = awq_builder_operands(&act, true);
12269 let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12270 }
12271
12272 /// Born-red: F32 `scales` (the previous layout) must be refused, since the
12273 /// kernel reads F16.
12274 #[test]
12275 #[should_panic(expected = "scales must be F16")]
12276 fn awq_matmul_builder_panics_on_f32_scales() {
12277 let act =
12278 NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12279 .unwrap();
12280 let (weight, zeros, _) = awq_builder_operands(&act, false);
12281 let scales = act
12282 .const_f32_like(vec![1.0_f32; 128], Shape::from_dims(&[8, 16]))
12283 .unwrap();
12284 let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12285 }
12286
12287 /// Born-red: `zeros` at the un-padded width (`ceil(groups / 8) = 1`, the
12288 /// kernel pads to 2) must be refused.
12289 #[test]
12290 #[should_panic(expected = "zeros [8, 1] must be")]
12291 fn awq_matmul_builder_panics_on_unpadded_zeros() {
12292 let act =
12293 NodeHandle::from_f32(vec![0.0_f32; 2 * 64], Shape::from_dims(&[2, 64]), cpu_dev())
12294 .unwrap();
12295 let (weight, _, scales) = awq_builder_operands(&act, false);
12296 let zeros = act
12297 .const_u32_like(vec![0u32; 8], Shape::from_dims(&[8, 1]))
12298 .unwrap();
12299 let _ = act.awq_matmul(&weight, &zeros, &scales, 64, 8);
12300 }
12301
12302 #[test]
12303 fn builders_agree_with_primitive_shape() {
12304 // No-drift guard (Convergence A, Task 6): every routed builder's output
12305 // shape/dtype must equal primitive_shape's answer for the same Op. If a
12306 // builder's inline math ever diverged from primitive_shape, this fails.
12307 let x = NodeHandle::from_f32(
12308 vec![0.0_f32; 2 * 3 * 4],
12309 Shape::from_dims(&[2, 3, 4]),
12310 cpu_dev(),
12311 )
12312 .unwrap();
12313 let checks: Vec<(NodeHandle, Op)> = vec![
12314 (
12315 x.slice(1, 0, 2),
12316 Op::Slice {
12317 dim: 1,
12318 start: 0,
12319 len: 2,
12320 },
12321 ),
12322 (x.mean_dim(2), Op::MeanDim(2)),
12323 (
12324 x.try_permute(&[2, 0, 1]).unwrap(),
12325 Op::Permute(vec![2, 0, 1]),
12326 ),
12327 (x.cast(DType::F16), Op::Cast(DType::F16)),
12328 ];
12329 for (t, op) in checks {
12330 let (ps_shape, ps_dtype) =
12331 crate::shape::primitive_shape(&op, &[x.shape()], &[x.dtype()]).unwrap();
12332 assert_eq!(t.shape(), ps_shape, "shape drift for {op:?}");
12333 assert_eq!(t.dtype(), ps_dtype, "dtype drift for {op:?}");
12334 }
12335 }
12336
12337 #[test]
12338 fn destructive_input_release_is_some_zero() {
12339 assert_eq!(Op::Release.destructive_input(), Some(0));
12340 }
12341
12342 /// Phase 7.5 storage-unification B2: target_backend side-table
12343 /// is sparse — empty by default, set explicitly per node.
12344 #[test]
12345 fn target_backend_side_table_starts_empty() {
12346 let mut g = Graph::new();
12347 let id = g.push(Node {
12348 op: Op::Const,
12349 inputs: vec![],
12350 shape: Shape::from_dims(&[1]),
12351 dtype: DType::F32,
12352 });
12353 assert_eq!(g.target_backend(id), None);
12354 assert_eq!(g.target_backend_count(), 0);
12355 }
12356
12357 /// set_target_backend then read returns the same value.
12358 #[test]
12359 fn target_backend_set_and_read() {
12360 let mut g = Graph::new();
12361 let id = g.push(Node {
12362 op: Op::Const,
12363 inputs: vec![],
12364 shape: Shape::from_dims(&[1]),
12365 dtype: DType::F32,
12366 });
12367 g.set_target_backend(id, BackendId::Cpu);
12368 assert_eq!(g.target_backend(id), Some(BackendId::Cpu));
12369 assert_eq!(g.target_backend_count(), 1);
12370 }
12371
12372 /// set_target_backend overwrites prior value.
12373 #[test]
12374 fn target_backend_overwrite() {
12375 let mut g = Graph::new();
12376 let id = g.push(Node {
12377 op: Op::Const,
12378 inputs: vec![],
12379 shape: Shape::from_dims(&[1]),
12380 dtype: DType::F32,
12381 });
12382 g.set_target_backend(id, BackendId::Cpu);
12383 g.set_target_backend(id, BackendId::Cuda);
12384 assert_eq!(g.target_backend(id), Some(BackendId::Cuda));
12385 assert_eq!(g.target_backend_count(), 1);
12386 }
12387
12388 /// Layouts side-table: default fallback returns
12389 /// `Layout::contiguous(node.shape)` for any node without an
12390 /// explicit entry.
12391 #[test]
12392 fn layout_default_is_contiguous_over_node_shape() {
12393 let mut g = Graph::new();
12394 let id = g.push(Node {
12395 op: Op::Const,
12396 inputs: vec![],
12397 shape: Shape::from_dims(&[2, 3]),
12398 dtype: DType::F32,
12399 });
12400 assert!(!g.has_explicit_layout(id));
12401 assert_eq!(g.explicit_layout_count(), 0);
12402 let l = g.layout(id);
12403 assert_eq!(l.shape().dims(), &[2, 3]);
12404 assert!(l.is_contiguous());
12405 assert_eq!(l.start_offset(), 0);
12406 }
12407
12408 /// set_layout records a strided Layout (e.g. for a transpose
12409 /// view). Subsequent reads return the explicit entry.
12410 #[test]
12411 fn layout_explicit_strided_is_remembered() {
12412 let mut g = Graph::new();
12413 let id = g.push(Node {
12414 op: Op::Transpose,
12415 inputs: vec![],
12416 shape: Shape::from_dims(&[3, 2]),
12417 dtype: DType::F32,
12418 });
12419 // Strided view: shape stays [3, 2] (the post-transpose view),
12420 // strides are [1, 3] (row-of-output is column-of-source).
12421 let l = Layout::new(
12422 Shape::from_dims(&[3, 2]),
12423 fuel_ir::StrideVec::from_slice(&[1_isize, 3]),
12424 0,
12425 );
12426 g.set_layout(id, l);
12427 assert!(g.has_explicit_layout(id));
12428 assert_eq!(g.explicit_layout_count(), 1);
12429 assert_eq!(g.layout(id).stride(), &[1, 3]);
12430 assert!(!g.layout(id).is_contiguous());
12431 }
12432
12433 /// set_layout twice with different layouts overwrites.
12434 #[test]
12435 fn layout_set_overwrites() {
12436 use fuel_ir::StrideVec;
12437 let mut g = Graph::new();
12438 let id = g.push(Node {
12439 op: Op::Transpose,
12440 inputs: vec![],
12441 shape: Shape::from_dims(&[2]),
12442 dtype: DType::F32,
12443 });
12444 g.set_layout(id, Layout::contiguous(Shape::from_dims(&[2])));
12445 g.set_layout(
12446 id,
12447 Layout::new(Shape::from_dims(&[2]), StrideVec::from_slice(&[3_isize]), 1),
12448 );
12449 assert_eq!(g.layout(id).start_offset(), 1);
12450 assert_eq!(g.explicit_layout_count(), 1);
12451 }
12452
12453 /// Phase 7.5 work item G — empty-map invariants. End-to-end
12454 /// tests of the storage map (with real `Storage` values) live in
12455 /// fuel-core's `tensor::node_handle_tests`, since constructing a
12456 /// real `Storage` requires a `DynBackendStorage` implementation
12457 /// from a backend crate, and fuel-graph deliberately depends only
12458 /// on fuel-core-types.
12459 #[test]
12460 fn graph_storage_map_starts_empty() {
12461 let g = Graph::new();
12462 assert_eq!(g.storage_len(), 0);
12463 assert!(!g.has_storage(NodeId(0)));
12464 assert!(g.storage_for(NodeId(0)).is_none());
12465 }
12466
12467 #[test]
12468 fn conv2d_builder_emits_conv2d_node_with_right_shape() {
12469 // k=3 s=1 p=1 keeps H and W.
12470 let x = NodeHandle::from_f32(
12471 vec![0.0_f32; 2 * 4 * 4],
12472 Shape::from_dims(&[1, 2, 4, 4]),
12473 cpu_dev(),
12474 )
12475 .unwrap();
12476 let w = x
12477 .const_f32_like(
12478 vec![0.0_f32; 3 * 2 * 3 * 3],
12479 Shape::from_dims(&[3, 2, 3, 3]),
12480 )
12481 .unwrap();
12482 let b = x
12483 .const_f32_like(vec![0.0_f32; 3], Shape::from_dims(&[3]))
12484 .unwrap();
12485 let y = x.conv2d(&w, Some(&b), (1, 1), (1, 1), 1);
12486 assert_eq!(y.shape().dims(), &[1, 3, 4, 4]);
12487 }
12488
12489 #[test]
12490 fn conv2d_builder_stride_and_no_padding() {
12491 // k=3 s=2 p=0 on H=W=8 gives (8-3)/2+1 = 3.
12492 let x = NodeHandle::from_f32(
12493 vec![0.0_f32; 2 * 8 * 8],
12494 Shape::from_dims(&[1, 2, 8, 8]),
12495 cpu_dev(),
12496 )
12497 .unwrap();
12498 let w = x
12499 .const_f32_like(
12500 vec![0.0_f32; 4 * 2 * 3 * 3],
12501 Shape::from_dims(&[4, 2, 3, 3]),
12502 )
12503 .unwrap();
12504 let y = x.conv2d(&w, None, (2, 2), (0, 0), 1);
12505 assert_eq!(y.shape().dims(), &[1, 4, 3, 3]);
12506 }
12507
12508 #[test]
12509 fn conv2d_builder_depthwise_groups() {
12510 // groups=Cin=Cout=4 is the depthwise case. Weight per channel is [Cin/groups=1, kH, kW].
12511 let x = NodeHandle::from_f32(
12512 vec![0.0_f32; 4 * 4 * 4],
12513 Shape::from_dims(&[1, 4, 4, 4]),
12514 cpu_dev(),
12515 )
12516 .unwrap();
12517 let w = x
12518 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 1, 3, 3]))
12519 .unwrap();
12520 let y = x.conv2d(&w, None, (1, 1), (1, 1), 4);
12521 assert_eq!(y.shape().dims(), &[1, 4, 4, 4]);
12522 }
12523
12524 #[test]
12525 fn conv_transpose2d_builder_emits_node_with_right_shape() {
12526 // Hin=4, Kh=3, s=2, pad=1, out_pad=1 → Hout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12527 let x = NodeHandle::from_f32(
12528 vec![0.0_f32; 2 * 4 * 4],
12529 Shape::from_dims(&[1, 2, 4, 4]),
12530 cpu_dev(),
12531 )
12532 .unwrap();
12533 let w = x
12534 .const_f32_like(
12535 vec![0.0_f32; 2 * 3 * 3 * 3],
12536 Shape::from_dims(&[2, 3, 3, 3]),
12537 )
12538 .unwrap();
12539 let y = x.conv_transpose2d(&w, (2, 2), (1, 1), (1, 1), (1, 1), 1);
12540 assert_eq!(y.shape().dims(), &[1, 3, 8, 8]);
12541 }
12542
12543 #[test]
12544 fn conv_transpose1d_builder_shape_stride_2_pad_1() {
12545 // Lin=4, K=3, s=2, pad=1, out_pad=1, dil=1
12546 // Lout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12547 let x = NodeHandle::from_f32(
12548 vec![0.0_f32; 2 * 4],
12549 Shape::from_dims(&[1, 2, 4]),
12550 cpu_dev(),
12551 )
12552 .unwrap();
12553 let w = x
12554 .const_f32_like(vec![0.0_f32; 2 * 3 * 3], Shape::from_dims(&[2, 3, 3]))
12555 .unwrap();
12556 let y = x.conv_transpose1d(&w, 2, 1, 1, 1, 1);
12557 assert_eq!(y.shape().dims(), &[1, 3, 8]);
12558 }
12559
12560 #[test]
12561 fn conv_transpose1d_builder_shape_stride_4_no_pad() {
12562 // Lin=2, K=4, s=4, pad=0, out_pad=0, dil=1
12563 // Lout = (2-1)*4 + (4-1) + 0 + 1 - 0 = 8.
12564 let x = NodeHandle::from_f32(vec![0.0_f32; 2], Shape::from_dims(&[1, 1, 2]), cpu_dev())
12565 .unwrap();
12566 let w = x
12567 .const_f32_like(vec![0.0_f32; 4], Shape::from_dims(&[1, 1, 4]))
12568 .unwrap();
12569 let y = x.conv_transpose1d(&w, 4, 0, 0, 1, 1);
12570 assert_eq!(y.shape().dims(), &[1, 1, 8]);
12571 }
12572
12573 #[test]
12574 fn conv_transpose1d_builder_with_groups() {
12575 // groups=2: input Cin=4 splits into 2 groups of 2; weight
12576 // Cin=4 first dim matches input; Cout/group=3 → total Cout=6.
12577 // Lin=3, K=3, s=1, pad=0, out_pad=0, dil=1 → Lout = (3-1)*1 + 2 + 0 + 1 = 5.
12578 let x = NodeHandle::from_f32(
12579 vec![0.0_f32; 4 * 3],
12580 Shape::from_dims(&[1, 4, 3]),
12581 cpu_dev(),
12582 )
12583 .unwrap();
12584 let w = x
12585 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 3, 3]))
12586 .unwrap();
12587 let y = x.conv_transpose1d(&w, 1, 0, 0, 1, 2);
12588 assert_eq!(y.shape().dims(), &[1, 6, 5]);
12589 }
12590
12591 #[test]
12592 fn conv2d_backward_grads_have_input_shapes() {
12593 // Forward Y = conv2d(X, W) with stride=1, pad=1, groups=1 keeps H,W.
12594 // Backward should produce dX with X's shape and dW with W's shape.
12595 let x = NodeHandle::from_f32(
12596 (0..(2 * 4 * 4))
12597 .map(|i| (i as f32) * 0.05 - 0.5)
12598 .collect::<Vec<f32>>(),
12599 Shape::from_dims(&[1, 2, 4, 4]),
12600 cpu_dev(),
12601 )
12602 .unwrap();
12603 let w = x
12604 .const_f32_like(
12605 (0..(3 * 2 * 3 * 3))
12606 .map(|i| (i as f32) * 0.07 - 0.4)
12607 .collect::<Vec<f32>>(),
12608 Shape::from_dims(&[3, 2, 3, 3]),
12609 )
12610 .unwrap();
12611 let y = x.conv2d(&w, None, (1, 1), (1, 1), 1);
12612 let scalar_out = y.sum_all();
12613 let grads = scalar_out.backward();
12614 let dx = grads.get(&x).expect("conv2d backward produced no dX");
12615 let dw = grads.get(&w).expect("conv2d backward produced no dW");
12616 assert_eq!(dx.shape().dims(), x.shape().dims());
12617 assert_eq!(dw.shape().dims(), w.shape().dims());
12618 }
12619
12620 #[test]
12621 fn destructive_input_move_is_some_zero() {
12622 assert_eq!(
12623 Op::Move {
12624 target: DeviceLocation::Cpu
12625 }
12626 .destructive_input(),
12627 Some(0)
12628 );
12629 }
12630
12631 #[test]
12632 fn destructive_input_non_destructive_ops_are_none() {
12633 assert_eq!(
12634 Op::Copy {
12635 target: DeviceLocation::Cpu
12636 }
12637 .destructive_input(),
12638 None
12639 );
12640 assert_eq!(Op::Add.destructive_input(), None);
12641 assert_eq!(Op::Mul.destructive_input(), None);
12642 assert_eq!(Op::MatMul.destructive_input(), None);
12643 assert_eq!(Op::Relu.destructive_input(), None);
12644 }
12645
12646 #[test]
12647 fn move_to_device_emits_op_move_node() {
12648 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12649 let moved = a.move_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12650 let g = moved.graph().read().unwrap();
12651 match &g.node(moved.id()).op {
12652 Op::Move { target } => {
12653 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12654 }
12655 other => panic!("expected Op::Move, got {other:?}"),
12656 }
12657 assert_eq!(g.node(moved.id()).inputs, vec![a.id()]);
12658 // Output has the input's shape (residency changes, data doesn't).
12659 assert_eq!(g.node(moved.id()).shape.elem_count(), 2);
12660 }
12661
12662 #[test]
12663 fn copy_to_device_emits_op_copy_node() {
12664 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12665 let b = a.copy_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12666 let g = b.graph().read().unwrap();
12667 match &g.node(b.id()).op {
12668 Op::Copy { target } => {
12669 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12670 }
12671 other => panic!("expected Op::Copy, got {other:?}"),
12672 }
12673 // Source stays resident: the original `a` node still in the graph
12674 // and is the input of the Copy node.
12675 assert_eq!(g.node(b.id()).inputs, vec![a.id()]);
12676 }
12677
12678 #[test]
12679 fn release_builder_emits_op_release_node() {
12680 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12681 let released = a.release();
12682 let g = released.graph().read().unwrap();
12683 assert!(matches!(g.node(released.id()).op, Op::Release));
12684 assert_eq!(g.node(released.id()).inputs, vec![a.id()]);
12685 // Output is a zero-element marker.
12686 assert_eq!(g.node(released.id()).shape.elem_count(), 0);
12687 }
12688
12689 #[test]
12690 fn placement_is_none_by_default() {
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.placement(), None);
12694 }
12695
12696 #[test]
12697 fn on_device_sets_placement_hint() {
12698 let a =
12699 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12700 let b = a
12701 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12702 .unwrap();
12703 // Only tag the Add node; the const leaves remain unplaced.
12704 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
12705 assert_eq!(c.placement(), Some(DeviceLocation::Vulkan { gpu_id: 0 }));
12706 assert_eq!(a.placement(), None);
12707 assert_eq!(b.placement(), None);
12708 }
12709
12710 #[test]
12711 fn placement_survives_graph_re_reads() {
12712 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12713 let tagged = a.clone().on_device(DeviceLocation::Cpu);
12714 // Re-read from a fresh borrow — round-trips through the side-table.
12715 assert_eq!(
12716 tagged.graph().read().unwrap().placement(tagged.id()),
12717 Some(DeviceLocation::Cpu)
12718 );
12719 }
12720
12721 #[test]
12722 fn from_f32_creates_single_const_node() {
12723 let a =
12724 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12725 assert_eq!(a.graph().read().unwrap().len(), 1);
12726 assert_eq!(a.shape().dims(), &[3]);
12727 assert_eq!(a.dtype(), DType::F32);
12728 let node = a.graph().read().unwrap().node(a.id()).clone();
12729 // Phase 7.5 G2: factory now emits Op::Const + slot.
12730 assert!(matches!(node.op, Op::Const));
12731 assert!(node.inputs.is_empty());
12732 // The slot is populated with F32 storage.
12733 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12734 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
12735 }
12736
12737 #[test]
12738 fn add_appends_a_node_and_tracks_inputs() {
12739 let a =
12740 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12741 let b = a
12742 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12743 .unwrap();
12744 let c = a.add(&b);
12745 assert_eq!(c.graph().read().unwrap().len(), 3); // const, const, add
12746 let node = c.graph().read().unwrap().node(c.id()).clone();
12747 assert!(matches!(node.op, Op::Add));
12748 assert_eq!(node.inputs.len(), 2);
12749 assert_eq!(node.inputs[0], a.id());
12750 assert_eq!(node.inputs[1], b.id());
12751 assert_eq!(c.shape().dims(), &[3]);
12752 }
12753
12754 #[test]
12755 fn chained_ops_all_share_one_graph() {
12756 let a =
12757 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12758 let b = a
12759 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12760 .unwrap();
12761 let c = a.add(&b).mul(&a).sqr().relu();
12762 assert_eq!(c.graph().read().unwrap().len(), 6); // 2 consts + add + mul + sqr + relu
12763 assert_eq!(c.shape().dims(), &[3]);
12764 }
12765
12766 #[test]
12767 fn matmul_validates_shapes_and_produces_correct_output_shape() {
12768 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12769 let b = a
12770 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
12771 .unwrap();
12772 let c = a.matmul(&b);
12773 assert_eq!(c.shape().dims(), &[2, 4]);
12774 }
12775
12776 #[test]
12777 #[should_panic(expected = "shape mismatch")]
12778 fn add_panics_on_shape_mismatch() {
12779 let a =
12780 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12781 let b = a
12782 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12783 .unwrap();
12784 let _ = a.add(&b);
12785 }
12786
12787 #[test]
12788 #[should_panic(expected = "inner dim mismatch")]
12789 fn matmul_panics_on_inner_dim_mismatch() {
12790 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12791 let b = a
12792 .const_f32_like(vec![1.0; 8], Shape::from_dims(&[4, 2]))
12793 .unwrap();
12794 let _ = a.matmul(&b);
12795 }
12796
12797 #[test]
12798 #[should_panic(expected = "must live on the same graph")]
12799 fn cross_graph_op_is_rejected() {
12800 let a =
12801 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12802 let b =
12803 NodeHandle::from_f32(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12804 let _ = a.add(&b);
12805 }
12806
12807 // ----- graph identity + graph-scoped construction -----
12808 //
12809 // Two changes land together: (1) every Graph carries a monotonic GraphId so
12810 // an affinity failure can name WHICH graphs rather than only that they
12811 // differ; (2) constructors accept an existing graph, so a consumer never has
12812 // to discover `const_*_like` to build a second tensor.
12813
12814 #[test]
12815 fn each_new_graph_gets_a_distinct_id() {
12816 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12817 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12818 assert_ne!(a.graph_id(), b.graph_id());
12819 }
12820
12821 #[test]
12822 fn same_graph_tensors_share_one_id() {
12823 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12824 let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
12825 assert_eq!(a.graph_id(), b.graph_id());
12826 }
12827
12828 #[test]
12829 fn affinity_panic_names_both_graph_ids() {
12830 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12831 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12832 let (ia, ib) = (a.graph_id(), b.graph_id());
12833 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| a.add(&b)))
12834 .expect_err("cross-graph add must panic");
12835 let text = err
12836 .downcast_ref::<String>()
12837 .cloned()
12838 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
12839 .expect("panic payload is a string");
12840 assert!(
12841 text.contains(&format!("#{ia}")) && text.contains(&format!("#{ib}")),
12842 "affinity panic must name BOTH graph ids so the caller can see it made two; got: {text}",
12843 );
12844 }
12845
12846 #[test]
12847 fn from_f32_on_builds_into_the_given_graph() {
12848 let root =
12849 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12850 let w = NodeHandle::from_f32_on(
12851 root.graph(),
12852 vec![4.0, 5.0, 6.0],
12853 Shape::from_dims(&[3]),
12854 cpu_dev(),
12855 )
12856 .unwrap();
12857 assert_eq!(root.graph_id(), w.graph_id());
12858 assert!(Arc::ptr_eq(root.graph(), w.graph()));
12859 }
12860
12861 #[test]
12862 fn graph_scoped_construction_composes_without_an_anchor() {
12863 // The program that could not previously be written: build two tensors
12864 // and combine them, without discovering `const_*_like`.
12865 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12866 let a = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev())
12867 .unwrap();
12868 let b = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[3, 2]), cpu_dev())
12869 .unwrap();
12870 let y = a.matmul(&b);
12871 assert_eq!(y.shape().dims(), &[2, 2]);
12872 assert_eq!(y.graph_id(), a.graph_id());
12873 }
12874
12875 #[test]
12876 fn graph_scoped_constructors_cover_every_dtype() {
12877 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12878 let s = Shape::from_dims(&[1]);
12879 let f32t = NodeHandle::from_f32_on(&g, vec![1.0f32], s.clone(), cpu_dev()).unwrap();
12880 let f64t = NodeHandle::from_f64_on(&g, vec![1.0f64], s.clone(), cpu_dev()).unwrap();
12881 let bf16t =
12882 NodeHandle::from_bf16_on(&g, vec![half::bf16::from_f32(1.0)], s.clone(), cpu_dev())
12883 .unwrap();
12884 let f16t =
12885 NodeHandle::from_f16_on(&g, vec![half::f16::from_f32(1.0)], s.clone(), cpu_dev())
12886 .unwrap();
12887 let u32t = NodeHandle::from_u32_on(&g, vec![1u32], s, cpu_dev()).unwrap();
12888 for t in [&f64t, &bf16t, &f16t, &u32t] {
12889 assert_eq!(
12890 t.graph_id(),
12891 f32t.graph_id(),
12892 "all must share the given graph"
12893 );
12894 }
12895 assert_eq!(f64t.dtype(), DType::F64);
12896 assert_eq!(bf16t.dtype(), DType::BF16);
12897 assert_eq!(f16t.dtype(), DType::F16);
12898 assert_eq!(u32t.dtype(), DType::U32);
12899 }
12900
12901 // ----- multi-dtype graph builders -----
12902
12903 #[test]
12904 fn from_f64_tags_node_with_f64_dtype() {
12905 let a =
12906 NodeHandle::from_f64(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12907 assert_eq!(a.dtype(), DType::F64);
12908 let node = a.graph().read().unwrap().node(a.id()).clone();
12909 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
12910 assert!(matches!(node.op, Op::Const));
12911 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12912 assert_eq!(slot.read().unwrap().dtype(), DType::F64);
12913 }
12914
12915 #[test]
12916 fn from_bf16_tags_node_with_bf16_dtype() {
12917 let a = NodeHandle::from_bf16(
12918 vec![bf16::from_f32(1.0), bf16::from_f32(2.0)],
12919 Shape::from_dims(&[2]),
12920 cpu_dev(),
12921 )
12922 .unwrap();
12923 assert_eq!(a.dtype(), DType::BF16);
12924 let node = a.graph().read().unwrap().node(a.id()).clone();
12925 assert!(matches!(node.op, Op::Const));
12926 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12927 assert_eq!(slot.read().unwrap().dtype(), DType::BF16);
12928 }
12929
12930 #[test]
12931 fn from_f16_tags_node_with_f16_dtype() {
12932 let a = NodeHandle::from_f16(
12933 vec![f16::from_f32(1.0), f16::from_f32(2.0)],
12934 Shape::from_dims(&[2]),
12935 cpu_dev(),
12936 )
12937 .unwrap();
12938 assert_eq!(a.dtype(), DType::F16);
12939 let node = a.graph().read().unwrap().node(a.id()).clone();
12940 assert!(matches!(node.op, Op::Const));
12941 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12942 assert_eq!(slot.read().unwrap().dtype(), DType::F16);
12943 }
12944
12945 #[test]
12946 #[should_panic(expected = "dtype mismatch")]
12947 fn add_panics_on_mixed_dtype() {
12948 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12949 let b = a
12950 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12951 .unwrap();
12952 let _ = a.add(&b);
12953 }
12954
12955 // ----- transpose -----
12956
12957 #[test]
12958 fn transpose_swaps_shape_dims() {
12959 let a = NodeHandle::from_f32(
12960 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
12961 Shape::from_dims(&[2, 3]),
12962 cpu_dev(),
12963 )
12964 .unwrap();
12965 let t = a.transpose();
12966 assert_eq!(t.shape().dims(), &[3, 2]);
12967 let node = t.graph().read().unwrap().node(t.id()).clone();
12968 assert!(matches!(node.op, Op::Transpose));
12969 assert_eq!(node.inputs, vec![a.id()]);
12970 }
12971
12972 #[test]
12973 #[should_panic(expected = "rank ≥ 2")]
12974 fn transpose_rejects_rank_1() {
12975 let a =
12976 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12977 let _ = a.transpose();
12978 }
12979
12980 #[test]
12981 fn transpose_on_rank_3_swaps_last_two_dims() {
12982 // [2, 3, 4] → [2, 4, 3]
12983 let a = NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev())
12984 .unwrap();
12985 let t = a.transpose();
12986 assert_eq!(t.shape().dims(), &[2, 4, 3]);
12987 }
12988
12989 // ----- additional builder validation tests -----
12990
12991 #[test]
12992 fn matmul_rank_3_batched_shape() {
12993 // [2, 3, 4] @ [2, 4, 5] → [2, 3, 5]
12994 let a =
12995 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12996 let b = a
12997 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12998 .unwrap();
12999 let c = a.matmul(&b);
13000 assert_eq!(c.shape().dims(), &[2, 3, 5]);
13001 }
13002
13003 #[test]
13004 #[should_panic(expected = "batch dim mismatch")]
13005 fn matmul_rank_3_rejects_batch_dim_mismatch() {
13006 let a =
13007 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13008 let b = a
13009 .const_f32_like(vec![0.0; 60], Shape::from_dims(&[3, 4, 5]))
13010 .unwrap();
13011 let _ = a.matmul(&b);
13012 }
13013
13014 #[test]
13015 fn matmul_auto_broadcasts_rank_2_rhs_against_batched_lhs() {
13016 // [batch=2, seq=3, k=4] @ [k=4, n=5] → [2, 3, 5]. This is the
13017 // canonical "linear layer across a batch" pattern and should
13018 // Just Work without an explicit broadcast_to on the RHS.
13019 let a =
13020 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13021 let b = a
13022 .const_f32_like(vec![0.0; 20], Shape::from_dims(&[4, 5]))
13023 .unwrap();
13024 let c = a.matmul(&b);
13025 assert_eq!(c.shape().dims(), &[2, 3, 5]);
13026 }
13027
13028 #[test]
13029 fn matmul_auto_broadcasts_rank_2_lhs_against_batched_rhs() {
13030 // [m=3, k=4] @ [batch=2, k=4, n=5] → [2, 3, 5].
13031 let a = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13032 let b = a
13033 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
13034 .unwrap();
13035 let c = a.matmul(&b);
13036 assert_eq!(c.shape().dims(), &[2, 3, 5]);
13037 }
13038
13039 #[test]
13040 fn concat_output_shape_sums_along_dim() {
13041 // [2, 3] concat [2, 4] along dim 1 → [2, 7]
13042 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13043 let b = a
13044 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13045 .unwrap();
13046 let c = a.concat(&b, 1);
13047 assert_eq!(c.shape().dims(), &[2, 7]);
13048 }
13049
13050 #[test]
13051 #[should_panic(expected = "non-dim shapes")]
13052 fn concat_rejects_nondim_shape_mismatch() {
13053 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13054 let b = a
13055 .const_f32_like(vec![0.0; 12], Shape::from_dims(&[3, 4]))
13056 .unwrap();
13057 let _ = a.concat(&b, 1);
13058 }
13059
13060 #[test]
13061 #[should_panic(expected = "rank mismatch")]
13062 fn concat_rejects_rank_mismatch() {
13063 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13064 let b = a
13065 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[6]))
13066 .unwrap();
13067 let _ = a.concat(&b, 0);
13068 }
13069
13070 #[test]
13071 fn slice_shrinks_only_the_slice_dim() {
13072 // [3, 4] slice dim 1, start 1, len 2 → [3, 2]
13073 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13074 let s = x.slice(1, 1, 2);
13075 assert_eq!(s.shape().dims(), &[3, 2]);
13076 }
13077
13078 #[test]
13079 #[should_panic(expected = "exceeds dim size")]
13080 fn slice_rejects_out_of_bounds_range() {
13081 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13082 let _ = x.slice(1, 1, 3); // start=1, len=3 → would need dim>=4
13083 }
13084
13085 #[test]
13086 fn broadcast_add_shape_promotes_to_common_shape() {
13087 // [4, 1] + [1, 3] → [4, 3]
13088 let a = NodeHandle::from_f32(vec![0.0; 4], Shape::from_dims(&[4, 1]), cpu_dev()).unwrap();
13089 let b = a
13090 .const_f32_like(vec![0.0; 3], Shape::from_dims(&[1, 3]))
13091 .unwrap();
13092 let c = a.broadcast_add(&b);
13093 assert_eq!(c.shape().dims(), &[4, 3]);
13094 }
13095
13096 #[test]
13097 fn broadcast_sub_pads_shorter_shape_with_leading_ones() {
13098 // [3] - [2, 3] → [2, 3]
13099 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13100 let b = a
13101 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[2, 3]))
13102 .unwrap();
13103 let c = a.broadcast_sub(&b);
13104 assert_eq!(c.shape().dims(), &[2, 3]);
13105 }
13106
13107 #[test]
13108 #[should_panic(expected = "incompatible shapes")]
13109 fn broadcast_add_rejects_incompatible_shapes() {
13110 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13111 let b = a
13112 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13113 .unwrap();
13114 let _ = a.broadcast_add(&b);
13115 }
13116
13117 #[test]
13118 fn argmax_dim_is_u32_and_removes_reduced_dim() {
13119 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13120 let am = x.argmax_dim(1);
13121 assert_eq!(am.dtype(), DType::U32);
13122 assert_eq!(am.shape().dims(), &[2]);
13123 }
13124
13125 #[test]
13126 #[should_panic(expected = "out of bounds")]
13127 fn argmax_dim_rejects_bad_dim() {
13128 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13129 let _ = x.argmax_dim(5);
13130 }
13131
13132 #[test]
13133 fn index_add_shape_validation() {
13134 let base = NodeHandle::from_f32(vec![0.0; 10], Shape::from_dims(&[10]), cpu_dev()).unwrap();
13135 let idx = base
13136 .const_u32_like(vec![1, 3, 5], Shape::from_dims(&[3]))
13137 .unwrap();
13138 let src = base
13139 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13140 .unwrap();
13141 let out = base.index_add(0, &idx, &src);
13142 assert_eq!(out.shape().dims(), &[10]);
13143 }
13144
13145 #[test]
13146 #[should_panic(expected = "dtypes must match")]
13147 fn index_add_rejects_dtype_mismatch() {
13148 let base = NodeHandle::from_f32(vec![0.0; 5], Shape::from_dims(&[5]), cpu_dev()).unwrap();
13149 let idx = base
13150 .const_u32_like(vec![0, 2], Shape::from_dims(&[2]))
13151 .unwrap();
13152 let src = base
13153 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13154 .unwrap();
13155 let _ = base.index_add(0, &idx, &src);
13156 }
13157
13158 #[test]
13159 fn scatter_add_validates_index_matches_src() {
13160 let base =
13161 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13162 let idx = base
13163 .const_u32_like(vec![0, 2, 1, 0], Shape::from_dims(&[2, 2]))
13164 .unwrap();
13165 let src = base
13166 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13167 .unwrap();
13168 let out = base.scatter_add(1, &idx, &src);
13169 assert_eq!(out.shape().dims(), &[2, 3]);
13170 }
13171
13172 #[test]
13173 #[should_panic(expected = "same shape")]
13174 fn scatter_add_rejects_index_src_shape_mismatch() {
13175 let base =
13176 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13177 let idx = base
13178 .const_u32_like(vec![0, 1], Shape::from_dims(&[2]))
13179 .unwrap();
13180 let src = base
13181 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13182 .unwrap();
13183 let _ = base.scatter_add(1, &idx, &src);
13184 }
13185
13186 #[test]
13187 fn reduce_sum_to_validates_compatibility() {
13188 // [3, 4] can reduce to [4] (sum along dim 0) or [3, 1] (sum along dim 1).
13189 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13190 let r1 = x.reduce_sum_to(Shape::from_dims(&[4]));
13191 assert_eq!(r1.shape().dims(), &[4]);
13192 let r2 = x.reduce_sum_to(Shape::from_dims(&[3, 1]));
13193 assert_eq!(r2.shape().dims(), &[3, 1]);
13194 }
13195
13196 #[test]
13197 #[should_panic(expected = "incompatible")]
13198 fn reduce_sum_to_rejects_non_broadcast_target() {
13199 // [3, 4] cannot reduce to [3, 2] — target must be broadcast-into-source.
13200 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13201 let _ = x.reduce_sum_to(Shape::from_dims(&[3, 2]));
13202 }
13203
13204 #[test]
13205 fn unsqueeze_inserts_size_one_dim() {
13206 let x = NodeHandle::from_f32(
13207 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13208 Shape::from_dims(&[2, 3]),
13209 cpu_dev(),
13210 )
13211 .unwrap();
13212 // Insert at position 0: [2, 3] -> [1, 2, 3]
13213 let y0 = x.unsqueeze(0);
13214 assert_eq!(y0.shape().dims(), &[1, 2, 3]);
13215 // Insert at position 1: [2, 3] -> [2, 1, 3]
13216 let y1 = x.unsqueeze(1);
13217 assert_eq!(y1.shape().dims(), &[2, 1, 3]);
13218 // Insert at the end (rank): [2, 3] -> [2, 3, 1]
13219 let y2 = x.unsqueeze(2);
13220 assert_eq!(y2.shape().dims(), &[2, 3, 1]);
13221 // Op variant correctness.
13222 let g = x.graph().read().unwrap();
13223 assert!(matches!(g.node(y0.id()).op, Op::Unsqueeze { dim: 0 }));
13224 assert!(matches!(g.node(y1.id()).op, Op::Unsqueeze { dim: 1 }));
13225 assert!(matches!(g.node(y2.id()).op, Op::Unsqueeze { dim: 2 }));
13226 }
13227
13228 #[test]
13229 #[should_panic(expected = "out of bounds")]
13230 fn unsqueeze_rejects_dim_above_rank() {
13231 let x = NodeHandle::from_f32(vec![1.0; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
13232 // dim=2 > rank=1 → panic.
13233 let _ = x.unsqueeze(2);
13234 }
13235
13236 #[test]
13237 fn unsqueeze_layout_side_table_populated() {
13238 // After Graph::push auto-derives the Layout side-table for view
13239 // ops, an unsqueeze node should have an explicit layout entry
13240 // with a stride-0 axis at the inserted position.
13241 let x = NodeHandle::from_f32(
13242 vec![1.0, 2.0, 3.0, 4.0],
13243 Shape::from_dims(&[2, 2]),
13244 cpu_dev(),
13245 )
13246 .unwrap();
13247 let y = x.unsqueeze(1);
13248 let g = x.graph().read().unwrap();
13249 assert!(
13250 g.has_explicit_layout(y.id()),
13251 "Graph::push should auto-populate layout for view ops"
13252 );
13253 let l = g.layout(y.id());
13254 assert_eq!(l.shape().dims(), &[2, 1, 2]);
13255 // Stride at the inserted axis should be 0 (per the convention
13256 // chosen in Layout::unsqueeze).
13257 assert_eq!(l.stride()[1], 0);
13258 }
13259
13260 #[test]
13261 fn reduce_max_to_validates_compatibility() {
13262 // [3, 4] can reduce to [4] (max along dim 0) or [3, 1] (max along dim 1).
13263 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13264 let r1 = x.reduce_max_to(Shape::from_dims(&[4]));
13265 assert_eq!(r1.shape().dims(), &[4]);
13266 assert!(matches!(
13267 r1.graph().read().unwrap().node(r1.id()).op,
13268 Op::ReduceMaxTo(_)
13269 ));
13270 let r2 = x.reduce_max_to(Shape::from_dims(&[3, 1]));
13271 assert_eq!(r2.shape().dims(), &[3, 1]);
13272 }
13273
13274 #[test]
13275 #[should_panic(expected = "incompatible")]
13276 fn reduce_max_to_rejects_non_broadcast_target() {
13277 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13278 let _ = x.reduce_max_to(Shape::from_dims(&[3, 2]));
13279 }
13280
13281 #[test]
13282 fn reshape_preserves_element_count() {
13283 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13284 let r = x.reshape(Shape::from_dims(&[2, 6]));
13285 assert_eq!(r.shape().dims(), &[2, 6]);
13286 }
13287
13288 #[test]
13289 #[should_panic(expected = "element count mismatch")]
13290 fn reshape_rejects_different_element_count() {
13291 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13292 let _ = x.reshape(Shape::from_dims(&[3, 3]));
13293 }
13294
13295 #[test]
13296 #[should_panic(expected = "same graph")]
13297 fn concat_across_graphs_panics() {
13298 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13299 let b = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13300 let _ = a.concat(&b, 0);
13301 }
13302
13303 #[test]
13304 fn scalar_ops_preserve_shape_and_dtype() {
13305 let x =
13306 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13307 let y = x.add_scalar(5.0).mul_scalar(2.0).powi(2).clamp(0.0, 100.0);
13308 assert_eq!(y.shape().dims(), &[3]);
13309 assert_eq!(y.dtype(), DType::F32);
13310 }
13311
13312 #[test]
13313 fn maximum_requires_matching_shapes() {
13314 let a =
13315 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13316 let b = a
13317 .const_f32_like(vec![4.0, 1.0, 5.0], Shape::from_dims(&[3]))
13318 .unwrap();
13319 let m = a.maximum(&b);
13320 assert_eq!(m.shape().dims(), &[3]);
13321 }
13322
13323 #[test]
13324 #[should_panic(expected = "shape mismatch")]
13325 fn maximum_rejects_shape_mismatch() {
13326 let a =
13327 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13328 let b = a
13329 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13330 .unwrap();
13331 let _ = a.maximum(&b);
13332 }
13333
13334 // ----- topo_order -----
13335
13336 #[test]
13337 fn topo_order_places_inputs_before_dependents() {
13338 // Build: c = (a + b) * a
13339 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13340 let b = a
13341 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13342 .unwrap();
13343 let sum = a.add(&b);
13344 let c = sum.mul(&a);
13345 let order = topo_order(&c.graph().read().unwrap(), c.id());
13346 // The order should contain exactly 4 nodes (a, b, sum, c) and
13347 // place each input strictly before its dependents.
13348 assert_eq!(order.len(), 4);
13349 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13350 assert!(pos(a.id()) < pos(sum.id()));
13351 assert!(pos(b.id()) < pos(sum.id()));
13352 assert!(pos(sum.id()) < pos(c.id()));
13353 assert!(pos(a.id()) < pos(c.id()));
13354 }
13355
13356 #[test]
13357 fn topo_order_visits_each_node_once_when_shared() {
13358 // (a + a) — `a` appears twice in the Add's inputs but the topo
13359 // pass should still visit it exactly once.
13360 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13361 let double = a.add(&a);
13362 let order = topo_order(&double.graph().read().unwrap(), double.id());
13363 assert_eq!(order.len(), 2);
13364 assert_eq!(order[0], a.id());
13365 assert_eq!(order[1], double.id());
13366 }
13367
13368 #[test]
13369 fn topo_order_multi_unions_multiple_roots() {
13370 // Build a DAG where two "output" nodes share a common input.
13371 //
13372 // a ─┬─> add1 (= a + b) ← root_1
13373 // └─> add2 (= a + c) ← root_2
13374 // b ───> add1
13375 // c ───> add2
13376 //
13377 // topo_order_multi(&[add1, add2]) must contain all 5 nodes
13378 // (a, b, c, add1, add2) with a before add1/add2 and b before
13379 // add1 and c before add2.
13380 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13381 let b = a
13382 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13383 .unwrap();
13384 let c = a
13385 .const_f32_like(vec![5.0, 6.0], Shape::from_dims(&[2]))
13386 .unwrap();
13387 let add1 = a.add(&b);
13388 let add2 = a.add(&c);
13389 let order = topo_order_multi(&add1.graph().read().unwrap(), &[add1.id(), add2.id()]);
13390 assert_eq!(order.len(), 5);
13391 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13392 assert!(pos(a.id()) < pos(add1.id()));
13393 assert!(pos(a.id()) < pos(add2.id()));
13394 assert!(pos(b.id()) < pos(add1.id()));
13395 assert!(pos(c.id()) < pos(add2.id()));
13396 }
13397
13398 // ----- backward -----
13399
13400 #[test]
13401 fn backward_of_lone_const_seeds_ones() {
13402 // backward(a) gives a = 1s (the root's upstream is a ones tensor,
13403 // which is the gradient stored for the root itself).
13404 let a =
13405 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13406 let grads = a.backward();
13407 let g_a = grads.get(&a).expect("root gets a seed gradient");
13408 // The seed is a Const ones node of matching shape. Phase 7.5
13409 // G2: gradient consts are slot-rooted Op::Const — no
13410 // host-side ConstData on the node.
13411 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13412 assert!(matches!(node.op, Op::Const));
13413 let slot = g_a.graph().read().unwrap().storage_for(g_a.id()).unwrap();
13414 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
13415 assert_eq!(g_a.shape().dims(), &[3]);
13416 }
13417
13418 #[test]
13419 fn backward_of_add_passes_upstream_through() {
13420 // c = a + b ⇒ dc/da = 1, dc/db = 1.
13421 // Upstream seed is a ones tensor. So grad_a and grad_b are both
13422 // the same ones node (no new math emitted for Add's backward).
13423 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13424 let b = a
13425 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13426 .unwrap();
13427 let c = a.add(&b);
13428 let grads = c.backward();
13429 let g_a = grads.get(&a).unwrap();
13430 let g_b = grads.get(&b).unwrap();
13431 assert_eq!(g_a.id(), g_b.id(), "Add backward routes upstream unchanged");
13432 assert_eq!(g_a.shape().dims(), &[2]);
13433 }
13434
13435 #[test]
13436 fn backward_of_mul_emits_two_mul_nodes() {
13437 // c = a * b ⇒ dc/da = b, dc/db = a (upstream is 1s).
13438 // The backward pass should emit two new Mul nodes (upstream * b,
13439 // upstream * a).
13440 let a = NodeHandle::from_f32(vec![2.0, 3.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13441 let b = a
13442 .const_f32_like(vec![5.0, 7.0], Shape::from_dims(&[2]))
13443 .unwrap();
13444 let c = a.mul(&b);
13445 let nodes_before = c.graph().read().unwrap().len();
13446 let grads = c.backward();
13447 let nodes_after = grads.graph.read().unwrap().len();
13448 // Backward adds: one ones const + two Mul nodes = 3 new nodes.
13449 assert_eq!(nodes_after - nodes_before, 3);
13450 let g_a = grads.get(&a).unwrap();
13451 let g_b = grads.get(&b).unwrap();
13452 // Both gradient nodes should be Mul nodes.
13453 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13454 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13455 assert!(matches!(node_a.op, Op::Mul));
13456 assert!(matches!(node_b.op, Op::Mul));
13457 }
13458
13459 #[test]
13460 fn backward_accumulates_when_node_used_twice() {
13461 // c = a * a ⇒ dc/da = 2a via two separate contributions.
13462 // After backward, the gradient for a should be an Add node
13463 // combining the two Mul contributions (one from each input slot
13464 // of the forward Mul).
13465 let a = NodeHandle::from_f32(vec![3.0, 5.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13466 let c = a.mul(&a);
13467 let grads = c.backward();
13468 let g_a = grads.get(&a).unwrap();
13469 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13470 // The final gradient for `a` is an Add combining the two
13471 // upstream-times-other-input contributions.
13472 assert!(
13473 matches!(node.op, Op::Add),
13474 "expected accumulated gradient to be an Add node, got {:?}",
13475 node.op,
13476 );
13477 }
13478
13479 #[test]
13480 fn backward_of_matmul_emits_transpose_and_matmul_nodes() {
13481 // Forward: Y = A @ B, A:[2,3], B:[3,4], Y:[2,4].
13482 // Backward: dA = dY @ B^T (shape [2,3]), dB = A^T @ dY (shape [3,4]).
13483 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13484 let b = a
13485 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13486 .unwrap();
13487 let y = a.matmul(&b);
13488 let grads = y.backward();
13489 let g_a = grads.get(&a).unwrap();
13490 let g_b = grads.get(&b).unwrap();
13491 // Gradient shapes must match the forward shapes.
13492 assert_eq!(g_a.shape().dims(), &[2, 3]);
13493 assert_eq!(g_b.shape().dims(), &[3, 4]);
13494 // Both should be MatMul nodes (the outermost op of each gradient).
13495 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13496 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13497 assert!(matches!(node_a.op, Op::MatMul));
13498 assert!(matches!(node_b.op, Op::MatMul));
13499 }
13500
13501 // ----- new builder validation -----
13502
13503 #[test]
13504 fn cast_tags_node_with_target_dtype() {
13505 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13506 let b = a.cast(DType::F64);
13507 assert_eq!(b.dtype(), DType::F64);
13508 assert_eq!(b.shape().dims(), &[2]);
13509 let node = b.graph().read().unwrap().node(b.id()).clone();
13510 assert!(matches!(node.op, Op::Cast(DType::F64)));
13511 }
13512
13513 #[test]
13514 fn broadcast_to_accepts_right_aligned_expansion() {
13515 // [3] broadcasts to [2, 3]: pad with leading 1, expand.
13516 let a =
13517 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13518 let b = a.broadcast_to(Shape::from_dims(&[2, 3]));
13519 assert_eq!(b.shape().dims(), &[2, 3]);
13520 }
13521
13522 #[test]
13523 fn broadcast_to_accepts_size_one_expansion() {
13524 // [3, 1] broadcasts to [3, 4]: size-1 dim expands.
13525 let a = NodeHandle::from_f32(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3, 1]), cpu_dev())
13526 .unwrap();
13527 let b = a.broadcast_to(Shape::from_dims(&[3, 4]));
13528 assert_eq!(b.shape().dims(), &[3, 4]);
13529 }
13530
13531 #[test]
13532 #[should_panic(expected = "incompatible")]
13533 fn broadcast_to_rejects_incompatible_dim() {
13534 // [3] cannot broadcast to [2, 4] — the source dim 3 must match 4.
13535 let a =
13536 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13537 let _ = a.broadcast_to(Shape::from_dims(&[2, 4]));
13538 }
13539
13540 #[test]
13541 fn sum_all_produces_rank_zero_output() {
13542 let a =
13543 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13544 let s = a.sum_all();
13545 assert_eq!(s.shape().dims(), &[] as &[usize]);
13546 }
13547
13548 #[test]
13549 fn sum_dim_removes_reduced_dim_from_shape() {
13550 let a =
13551 NodeHandle::from_f32(vec![1.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13552 // Reducing dim 1 should give shape [2, 4].
13553 let s = a.sum_dim(1);
13554 assert_eq!(s.shape().dims(), &[2, 4]);
13555 }
13556
13557 #[test]
13558 #[should_panic(expected = "out of bounds")]
13559 fn sum_dim_rejects_bad_dim() {
13560 let a =
13561 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13562 let _ = a.sum_dim(5);
13563 }
13564
13565 #[test]
13566 fn softmax_and_layer_norm_preserve_shape() {
13567 let a = NodeHandle::from_f32(
13568 vec![1.0, 2.0, 3.0, 4.0],
13569 Shape::from_dims(&[2, 2]),
13570 cpu_dev(),
13571 )
13572 .unwrap();
13573 assert_eq!(a.softmax_last_dim().shape().dims(), &[2, 2]);
13574 assert_eq!(a.layer_norm_last_dim(1e-5).shape().dims(), &[2, 2]);
13575 }
13576
13577 #[test]
13578 fn neg_sub_div_sqrt_log_sin_cos_tanh_sigmoid_all_build() {
13579 // Smoke test: every new builder produces a node with the expected
13580 // shape and dtype. Numerical correctness is exercised in exec.rs.
13581 let a =
13582 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13583 let b = a
13584 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13585 .unwrap();
13586 for tensor in [
13587 a.neg(),
13588 a.sub(&b),
13589 a.div(&b),
13590 a.sqrt(),
13591 a.log(),
13592 a.sin(),
13593 a.cos(),
13594 a.tanh(),
13595 a.sigmoid(),
13596 a.step(),
13597 ] {
13598 assert_eq!(tensor.shape().dims(), &[3]);
13599 assert_eq!(tensor.dtype(), DType::F32);
13600 }
13601 }
13602
13603 // ----- index tensors and indexing ops -----
13604
13605 #[test]
13606 fn from_u32_tags_node_with_u32_dtype() {
13607 let a = NodeHandle::from_u32(vec![1, 2, 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13608 assert_eq!(a.dtype(), DType::U32);
13609 let node = a.graph().read().unwrap().node(a.id()).clone();
13610 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13611 assert!(matches!(node.op, Op::Const));
13612 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13613 assert_eq!(slot.read().unwrap().dtype(), DType::U32);
13614 }
13615
13616 #[test]
13617 fn index_select_produces_shape_with_dim_replaced() {
13618 let data =
13619 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13620 let idx = data
13621 .const_u32_like(vec![0, 2, 1, 0, 2], Shape::from_dims(&[5]))
13622 .unwrap();
13623 let out = data.index_select(0, &idx);
13624 assert_eq!(out.shape().dims(), &[5, 4]);
13625 assert_eq!(out.dtype(), DType::F32);
13626 }
13627
13628 #[test]
13629 #[should_panic(expected = "must be U32")]
13630 fn index_select_rejects_float_index() {
13631 let data =
13632 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13633 let bad = data
13634 .const_f32_like(vec![0.0, 1.0], Shape::from_dims(&[2]))
13635 .unwrap();
13636 let _ = data.index_select(0, &bad);
13637 }
13638
13639 #[test]
13640 #[should_panic(expected = "must be rank 1")]
13641 fn index_select_rejects_multi_dim_index() {
13642 let data =
13643 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13644 let idx = data
13645 .const_u32_like(vec![0, 1, 0, 1], Shape::from_dims(&[2, 2]))
13646 .unwrap();
13647 let _ = data.index_select(0, &idx);
13648 }
13649
13650 #[test]
13651 fn gather_output_shape_matches_index_shape() {
13652 let data =
13653 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13654 // Index shape [2, 5] — same rank as data (rank 2).
13655 let idx = data
13656 .const_u32_like(vec![0; 10], Shape::from_dims(&[2, 5]))
13657 .unwrap();
13658 let out = data.gather(1, &idx);
13659 assert_eq!(out.shape().dims(), &[2, 5]);
13660 }
13661
13662 #[test]
13663 #[should_panic(expected = "same rank")]
13664 fn gather_rejects_rank_mismatch() {
13665 let data =
13666 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13667 // Rank-1 index for rank-2 data → error.
13668 let idx = data
13669 .const_u32_like(vec![0, 1, 0], Shape::from_dims(&[3]))
13670 .unwrap();
13671 let _ = data.gather(1, &idx);
13672 }
13673
13674 #[test]
13675 fn backward_of_relu_emits_step_node() {
13676 // Before: this used to panic. After adding Step + Relu backward,
13677 // it should successfully emit a backward graph rooted in a Mul
13678 // whose second input is a Step node.
13679 let a =
13680 NodeHandle::from_f32(vec![-1.0, 2.0, -3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13681 let y = a.relu();
13682 let grads = y.backward();
13683 let g_a = grads.get(&a).unwrap();
13684 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13685 assert!(matches!(node.op, Op::Mul));
13686 // Find a Step node somewhere in the node's inputs.
13687 let any_step = node
13688 .inputs
13689 .iter()
13690 .any(|&id| matches!(g_a.graph().read().unwrap().node(id).op, Op::Step,));
13691 assert!(any_step, "Relu backward must reference a Step node");
13692 }
13693
13694 #[test]
13695 fn recip_and_abs_builders_produce_unary_nodes() {
13696 // Smoke test: NodeHandle::recip()/abs() build single-input nodes
13697 // with the expected op variant and shape passthrough.
13698 let a =
13699 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13700 let r = a.recip();
13701 let b = a.abs();
13702 assert_eq!(r.shape().dims(), &[3]);
13703 assert_eq!(b.shape().dims(), &[3]);
13704 let r_node = r.graph().read().unwrap().node(r.id()).clone();
13705 let b_node = b.graph().read().unwrap().node(b.id()).clone();
13706 assert!(matches!(r_node.op, Op::Recip));
13707 assert!(matches!(b_node.op, Op::Abs));
13708 assert_eq!(r_node.inputs, vec![a.id()]);
13709 assert_eq!(b_node.inputs, vec![a.id()]);
13710 }
13711
13712 #[test]
13713 fn backward_of_recip_is_neg_of_upstream_times_y_squared() {
13714 // y = 1/x ⇒ dy/dx = -y². The backward graph should be a Neg
13715 // wrapping a Mul whose inputs include a Sqr node — and the Sqr
13716 // should reference the forward Recip output, not a fresh recompute.
13717 let a = NodeHandle::from_f32(vec![2.0, 4.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13718 let y = a.recip();
13719 let y_id = y.id();
13720 let grads = y.backward();
13721 let g_a = grads.get(&a).unwrap();
13722 let g = g_a.graph().read().unwrap();
13723 let neg_node = g.node(g_a.id()).clone();
13724 assert!(
13725 matches!(neg_node.op, Op::Neg),
13726 "outermost backward op must be Neg"
13727 );
13728 let mul_id = neg_node.inputs[0];
13729 let mul_node = g.node(mul_id).clone();
13730 assert!(matches!(mul_node.op, Op::Mul));
13731 // One of the Mul's inputs is a Sqr node fed by the forward Recip.
13732 let sqr_id = mul_node
13733 .inputs
13734 .iter()
13735 .copied()
13736 .find(|&id| matches!(g.node(id).op, Op::Sqr))
13737 .expect("backward chain must contain a Sqr node");
13738 let sqr_node = g.node(sqr_id).clone();
13739 assert_eq!(
13740 sqr_node.inputs,
13741 vec![y_id],
13742 "Sqr's input must be the forward Recip output, not a recompute"
13743 );
13744 }
13745
13746 #[test]
13747 fn backward_of_abs_emits_sign_mul() {
13748 // y = |x|, dy/dx = sign(x). After PR B2 landed Op::Sign, the
13749 // backward chain shrinks from 5 nodes (step+neg+step+sub+mul)
13750 // to 2 (sign+mul): grad_x = upstream * sign(x), where Sign is
13751 // a single primitive that returns -1/0/1 directly.
13752 let a = NodeHandle::from_f32(vec![-2.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13753 let y = a.abs();
13754 let grads = y.backward();
13755 let g_a = grads.get(&a).unwrap();
13756 let g = g_a.graph().read().unwrap();
13757 let mul_node = g.node(g_a.id()).clone();
13758 assert!(matches!(mul_node.op, Op::Mul));
13759 // Exactly one input of the Mul is a Sign node (the other is
13760 // the upstream gradient — a Const-rooted ones-tensor here).
13761 let sign_count = mul_node
13762 .inputs
13763 .iter()
13764 .filter(|&&id| matches!(g.node(id).op, Op::Sign))
13765 .count();
13766 assert_eq!(
13767 sign_count, 1,
13768 "Abs backward must reference exactly 1 Sign node, got {sign_count}"
13769 );
13770 // The Sign node should feed off the original input `a`.
13771 let sign_id = mul_node
13772 .inputs
13773 .iter()
13774 .copied()
13775 .find(|&id| matches!(g.node(id).op, Op::Sign))
13776 .unwrap();
13777 assert_eq!(
13778 g.node(sign_id).inputs,
13779 vec![a.id()],
13780 "Sign's input must be the forward input `a`"
13781 );
13782 }
13783
13784 #[test]
13785 fn eq_builder_produces_bool_output_with_input_shape() {
13786 // GAP-168(c): NodeHandle::eq builds a binary node whose dtype is Bool
13787 // regardless of input dtype (CireSnave's ruling — "Fuel uses Bool
13788 // where possible"), with shape == lhs.shape() (and == rhs.shape()).
13789 let a =
13790 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13791 let b = a
13792 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13793 .unwrap();
13794 let m = a.eq(&b);
13795 assert_eq!(m.shape().dims(), &[3]);
13796 assert_eq!(m.dtype(), DType::Bool, "eq output must be Bool");
13797 let m_node = m.graph().read().unwrap().node(m.id()).clone();
13798 assert!(matches!(m_node.op, Op::Equal));
13799 assert_eq!(m_node.inputs, vec![a.id(), b.id()]);
13800 }
13801
13802 #[test]
13803 fn all_six_comparisons_produce_bool() {
13804 // GAP-168(c): eq/ne/lt/le/gt/ge every one returns DType::Bool, not the
13805 // legacy U8 mask. Shape is preserved (== lhs == rhs). One assertion per
13806 // operator so a regression names the operator that drifted.
13807 let a =
13808 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13809 let b = a
13810 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13811 .unwrap();
13812 for (name, m) in [
13813 ("eq", a.eq(&b)),
13814 ("ne", a.ne(&b)),
13815 ("lt", a.lt(&b)),
13816 ("le", a.le(&b)),
13817 ("gt", a.gt(&b)),
13818 ("ge", a.ge(&b)),
13819 ] {
13820 assert_eq!(m.dtype(), DType::Bool, "{name} output must be Bool");
13821 assert_eq!(m.shape().dims(), &[3], "{name} preserves input shape");
13822 }
13823 }
13824
13825 #[test]
13826 fn try_unsqueeze_returns_err_on_dim_above_rank() {
13827 // try_unsqueeze surfaces bad dim as Err; unsqueeze panics
13828 // on the same input. Both share the validation message.
13829 let a =
13830 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13831 let err = a.try_unsqueeze(5).expect_err("dim above rank must error");
13832 assert!(
13833 format!("{err:?}").contains("out of bounds"),
13834 "error must mention bounds, got: {err:?}"
13835 );
13836 // Happy path still works.
13837 let ok = a.try_unsqueeze(0).expect("dim=0 valid for any rank");
13838 assert_eq!(ok.shape().dims(), &[1, 3]);
13839 }
13840
13841 #[test]
13842 fn try_reshape_returns_err_on_count_mismatch() {
13843 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
13844 .unwrap();
13845 let err = a
13846 .try_reshape(Shape::from_dims(&[3]))
13847 .expect_err("count mismatch must error");
13848 assert!(
13849 format!("{err:?}").contains("element count mismatch"),
13850 "error must mention count mismatch, got: {err:?}"
13851 );
13852 let ok = a
13853 .try_reshape(Shape::from_dims(&[2, 2]))
13854 .expect("matching count is ok");
13855 assert_eq!(ok.shape().dims(), &[2, 2]);
13856 }
13857
13858 #[test]
13859 fn try_broadcast_to_returns_err_on_incompatible_shape() {
13860 let a =
13861 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13862 let err = a
13863 .try_broadcast_to(Shape::from_dims(&[2, 4]))
13864 .expect_err("source dim 3 cannot broadcast to dim 4");
13865 assert!(
13866 format!("{err:?}").contains("incompatible"),
13867 "error must mention incompatibility, got: {err:?}"
13868 );
13869 let ok = a
13870 .try_broadcast_to(Shape::from_dims(&[2, 3]))
13871 .expect("dim 3 broadcasts to dim 3");
13872 assert_eq!(ok.shape().dims(), &[2, 3]);
13873 }
13874
13875 #[test]
13876 fn try_transpose_returns_err_on_rank_below_2() {
13877 let a =
13878 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13879 let err = a
13880 .try_transpose()
13881 .expect_err("rank-1 input cannot transpose");
13882 assert!(
13883 format!("{err:?}").contains("rank ≥ 2"),
13884 "error must mention rank requirement, got: {err:?}"
13885 );
13886 let m = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13887 let mt = m.try_transpose().expect("rank-2 transposes ok");
13888 assert_eq!(mt.shape().dims(), &[3, 2]);
13889 }
13890
13891 #[test]
13892 fn try_permute_returns_err_on_bad_axes() {
13893 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13894 // Wrong axes length:
13895 let err = a.try_permute(&[0]).expect_err("axes length mismatch");
13896 assert!(
13897 format!("{err:?}").contains("must equal tensor rank"),
13898 "error must mention length, got: {err:?}"
13899 );
13900 // Out-of-bounds axis:
13901 let err = a.try_permute(&[0, 5]).expect_err("axis 5 out of rank 2");
13902 assert!(format!("{err:?}").contains("out of bounds"));
13903 // Duplicate axis:
13904 let err = a.try_permute(&[0, 0]).expect_err("duplicate axis");
13905 assert!(format!("{err:?}").contains("duplicate"));
13906 // Happy path:
13907 let ok = a.try_permute(&[1, 0]).expect("valid permutation");
13908 assert_eq!(ok.shape().dims(), &[3, 2]);
13909 }
13910
13911 #[test]
13912 fn squeeze_drops_size_one_dim_metadata_only() {
13913 // Build [2, 1, 3] → squeeze(1) → [2, 3]. Op::Squeeze, view-op,
13914 // shape pruned, dtype preserved, single input slot.
13915 let a =
13916 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13917 let s = a.squeeze(1).expect("squeeze on size-1 dim");
13918 assert_eq!(s.shape().dims(), &[2, 3]);
13919 assert_eq!(s.dtype(), DType::F32);
13920 let node = s.graph().read().unwrap().node(s.id()).clone();
13921 assert!(matches!(node.op, Op::Squeeze { dim: 1 }));
13922 assert_eq!(node.inputs, vec![a.id()]);
13923 // Squeeze joins the view-op set so the Layout side-table is
13924 // populated automatically.
13925 assert!(
13926 node.op.is_view_op(),
13927 "Op::Squeeze must register as a view op"
13928 );
13929 }
13930
13931 #[test]
13932 fn squeeze_rejects_non_size_one_dim() {
13933 // Result-returning: bad dim surfaces as Err, not panic.
13934 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13935 let err = a
13936 .squeeze(1)
13937 .expect_err("squeezing a non-size-1 dim must error");
13938 assert!(
13939 format!("{err:?}").contains("expected 1"),
13940 "error message should mention the size-1 expectation, got: {err:?}"
13941 );
13942 }
13943
13944 #[test]
13945 fn squeeze_rejects_dim_above_rank() {
13946 let a =
13947 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13948 let err = a.squeeze(5).expect_err("dim above rank must error");
13949 assert!(
13950 format!("{err:?}").contains("out of bounds"),
13951 "error message should mention bounds, got: {err:?}"
13952 );
13953 }
13954
13955 #[test]
13956 fn backward_through_squeeze_emits_unsqueeze() {
13957 // y = squeeze(x, 1). Backward: re-insert dim 1 via Unsqueeze.
13958 // Gradient shape must equal x.shape exactly.
13959 let a =
13960 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13961 let y = a.squeeze(1).expect("squeeze on size-1 dim");
13962 let grads = y.backward();
13963 let g_a = grads.get(&a).expect("gradient for a");
13964 assert_eq!(
13965 g_a.shape().dims(),
13966 &[2, 1, 3],
13967 "Squeeze backward gradient must restore the original shape"
13968 );
13969 // The chain is: ones-seed (post-squeeze, shape [2,3])
13970 // → Unsqueeze(dim=1) → shape [2, 1, 3].
13971 let g_node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13972 assert!(
13973 matches!(g_node.op, Op::Unsqueeze { dim: 1 }),
13974 "Squeeze backward must be Unsqueeze at the same dim"
13975 );
13976 }
13977
13978 #[test]
13979 fn floor_builder_produces_unary_node_same_dtype() {
13980 // NodeHandle::floor builds a unary node preserving shape + dtype.
13981 let a =
13982 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13983 let f = a.floor();
13984 assert_eq!(f.shape().dims(), &[3]);
13985 assert_eq!(f.dtype(), DType::F32);
13986 let node = f.graph().read().unwrap().node(f.id()).clone();
13987 assert!(matches!(node.op, Op::Floor));
13988 assert_eq!(node.inputs, vec![a.id()]);
13989 }
13990
13991 #[test]
13992 fn backward_through_floor_drops_gradient_silently() {
13993 // Op::Floor has zero gradient almost everywhere; the inline
13994 // backward arm is a no-op. backward() must succeed and the
13995 // input gets no gradient (the input's upstream is never
13996 // populated through the Floor node).
13997 let a =
13998 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13999 let y = a.floor();
14000 let grads = y.backward();
14001 // a's gradient is dropped — no entry in the GradMap.
14002 assert!(
14003 grads.get(&a).is_none(),
14004 "Floor must not propagate gradient to its input"
14005 );
14006 }
14007
14008 #[test]
14009 fn where_cond_builder_produces_ternary_with_a_dtype() {
14010 // self is a Bool cond (GAP-168(c)); a/b are F32. Output dtype = F32
14011 // (= a's dtype), shape = self.shape() (= a.shape() = b.shape()).
14012 // Op::Where node carries 3 inputs in order (cond, a, b).
14013 let a =
14014 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14015 let b = a
14016 .const_f32_like(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3]))
14017 .unwrap();
14018 let eq_a_b = a.eq(&b); // Bool mask
14019 let picked = eq_a_b.where_cond(&a, &b);
14020 assert_eq!(picked.shape().dims(), &[3]);
14021 assert_eq!(picked.dtype(), DType::F32, "Where output dtype = a/b dtype");
14022 let node = picked.graph().read().unwrap().node(picked.id()).clone();
14023 assert!(matches!(node.op, Op::Where));
14024 assert_eq!(node.inputs.len(), 3);
14025 assert_eq!(
14026 node.inputs,
14027 vec![eq_a_b.id(), a.id(), b.id()],
14028 "Where input order: (cond, a, b)"
14029 );
14030 }
14031
14032 #[test]
14033 fn backward_reuses_exp_forward_output() {
14034 // Exp's backward rule uses the forward output directly. The
14035 // gradient for x should be a Mul whose inputs include the
14036 // forward Exp node (not a new Exp node).
14037 let a = NodeHandle::from_f32(vec![0.0, 1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14038 let e = a.exp();
14039 let exp_forward_id = e.id();
14040 let grads = e.backward();
14041 let g_a = grads.get(&a).unwrap();
14042 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
14043 assert!(matches!(node.op, Op::Mul));
14044 // One of the Mul's inputs should be the original forward Exp node.
14045 assert!(
14046 node.inputs.contains(&exp_forward_id),
14047 "Exp backward should reference the forward output ({exp_forward_id:?}), \
14048 got inputs {:?}",
14049 node.inputs,
14050 );
14051 }
14052
14053 // ---- Op::WriteSlice (Phase E.3.2) ---------------------------------------
14054
14055 #[test]
14056 fn write_slice_destructive_input_is_zero() {
14057 let op = Op::WriteSlice {
14058 ranges: vec![(0, 1), (0, 32), (0, 128)],
14059 dyn_offset: None,
14060 };
14061 assert_eq!(op.destructive_input(), Some(0));
14062 }
14063
14064 #[test]
14065 fn write_slice_short_name() {
14066 let op = Op::WriteSlice {
14067 ranges: vec![(0, 1)],
14068 dyn_offset: None,
14069 };
14070 assert_eq!(op.short_name(), "WriteSlice");
14071 }
14072
14073 #[test]
14074 fn write_slice_emits_op_writeslice_node() {
14075 // dest shape [4, 3]; source shape [1, 3]; write at row 2.
14076 let dest =
14077 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14078 let src = dest
14079 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14080 .unwrap();
14081 let out = dest
14082 .write_slice(&src, vec![(2, 3), (0, 3)])
14083 .expect("write_slice should accept matching shapes");
14084 let g = out.graph().read().unwrap();
14085 match &g.node(out.id()).op {
14086 Op::WriteSlice { ranges, dyn_offset } => {
14087 assert_eq!(ranges, &vec![(2, 3), (0, 3)]);
14088 assert_eq!(dyn_offset, &None);
14089 }
14090 other => panic!("expected Op::WriteSlice, got {other:?}"),
14091 }
14092 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14093 // Output shape == destination shape; bytes are post-write same buffer.
14094 assert_eq!(g.node(out.id()).shape.dims(), &[4, 3]);
14095 }
14096
14097 #[test]
14098 fn write_slice_dyn_records_dynamic_offset() {
14099 use fuel_ir::{DynScalar, SymId};
14100 // dest capacity [8, 3]; source [1, 3]; dynamic start on axis 0.
14101 let dest =
14102 NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[8, 3]), cpu_dev()).unwrap();
14103 let src = dest
14104 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14105 .unwrap();
14106 let sym = SymId(0);
14107 // ranges[0].0 is ignored (start is dynamic); width = 1 - 0 = 1
14108 // matches source dim 0. Axis 1 is static, full width.
14109 let out = dest
14110 .write_slice_dyn(&src, vec![(0, 1), (0, 3)], 0, DynScalar::Sym(sym))
14111 .expect("write_slice_dyn should accept matching widths");
14112 let g = out.graph().read().unwrap();
14113 match &g.node(out.id()).op {
14114 Op::WriteSlice { ranges, dyn_offset } => {
14115 assert_eq!(ranges, &vec![(0, 1), (0, 3)]);
14116 assert_eq!(dyn_offset, &Some((0, DynScalar::Sym(sym))));
14117 }
14118 other => panic!("expected Op::WriteSlice, got {other:?}"),
14119 }
14120 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14121 assert_eq!(g.node(out.id()).shape.dims(), &[8, 3]);
14122 }
14123
14124 #[test]
14125 fn write_slice_dyn_rejects_slab_wider_than_capacity() {
14126 use fuel_ir::{DynScalar, SymId};
14127 // dest capacity on axis 0 is 2, but the dynamic-axis slab is
14128 // width 4 — can never fit regardless of the runtime offset.
14129 let dest =
14130 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14131 let src = dest
14132 .const_f32_like(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]))
14133 .unwrap();
14134 let err = dest.write_slice_dyn(&src, vec![(0, 4), (0, 3)], 0, DynScalar::Sym(SymId(0)));
14135 assert!(
14136 err.is_err(),
14137 "dynamic-axis slab wider than capacity must error at build"
14138 );
14139 }
14140
14141 #[test]
14142 fn write_slice_dyn_rejects_axis_out_of_bounds() {
14143 use fuel_ir::{DynScalar, SymId};
14144 let dest =
14145 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14146 let src = dest
14147 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14148 .unwrap();
14149 let err = dest.write_slice_dyn(&src, vec![(0, 1), (0, 3)], 5, DynScalar::Sym(SymId(0)));
14150 assert!(err.is_err(), "dyn_axis past rank must error");
14151 }
14152
14153 #[test]
14154 fn flash_attn_dyn_records_runtime_k_len() {
14155 use fuel_ir::{DynScalar, SymId};
14156 // q [1, 2, 3, 4]; K/V capacity [1, 1, 8, 4] (GQA Hq=2, Hkv=1).
14157 let q = NodeHandle::from_f32(
14158 vec![0.0_f32; 2 * 3 * 4],
14159 Shape::from_dims(&[1, 2, 3, 4]),
14160 cpu_dev(),
14161 )
14162 .unwrap();
14163 let k = q
14164 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14165 .unwrap();
14166 let v = q
14167 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14168 .unwrap();
14169 let sym = SymId(0);
14170 let out = q.flash_attn_dyn(
14171 &k,
14172 &v,
14173 None,
14174 /*scale*/ 0.5,
14175 /*causal*/ true,
14176 None,
14177 None,
14178 None,
14179 DynScalar::Sym(sym),
14180 );
14181 // Output adopts q's shape, not the capacity.
14182 assert_eq!(out.shape().dims(), &[1, 2, 3, 4]);
14183 let g = out.graph().read().unwrap();
14184 match &g.node(out.id()).op {
14185 Op::Fused(fid, crate::registry::FusedOpParams::FlashAttn { causal, k_len, .. })
14186 if *fid == crate::registry::FusedOps::FLASH_ATTN =>
14187 {
14188 assert!(*causal);
14189 assert_eq!(k_len, &Some(DynScalar::Sym(sym)));
14190 }
14191 other => panic!("expected Op::Fused(FLASH_ATTN, FlashAttn), got {other:?}"),
14192 }
14193 assert_eq!(g.node(out.id()).inputs, vec![q.id(), k.id(), v.id()]);
14194 }
14195
14196 #[test]
14197 #[should_panic(expected = "k_len")]
14198 fn flash_attn_dyn_concrete_k_len_exceeding_capacity_panics() {
14199 use fuel_ir::DynScalar;
14200 let q = NodeHandle::from_f32(
14201 vec![0.0_f32; 2 * 4],
14202 Shape::from_dims(&[1, 1, 2, 4]),
14203 cpu_dev(),
14204 )
14205 .unwrap();
14206 let k = q
14207 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14208 .unwrap();
14209 let v = q
14210 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14211 .unwrap();
14212 // Concrete k_len=5 > capacity 4 → build-time panic.
14213 let _ = q.flash_attn_dyn(
14214 &k,
14215 &v,
14216 None,
14217 1.0,
14218 true,
14219 None,
14220 None,
14221 None,
14222 DynScalar::Concrete(5),
14223 );
14224 }
14225
14226 #[test]
14227 fn write_slice_rejects_rank_mismatch() {
14228 let dest =
14229 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14230 let src = dest
14231 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
14232 .unwrap();
14233 // ranges has rank 2 (matches dest) but source has rank 1.
14234 let err = dest.write_slice(&src, vec![(0, 1), (0, 3)]);
14235 assert!(err.is_err(), "rank mismatch must error");
14236 }
14237
14238 // ---- cross-graph operands must fail at BUILD time, never hang -----------
14239 //
14240 // Node ids are indices into ONE graph's arena, so an operand built on a
14241 // DIFFERENT graph records an id that indexes an unrelated node (or none),
14242 // producing a malformed dependency graph. The failure surfaces as neither
14243 // a panic nor an error: the executor **HANGS at realize**, waiting on a
14244 // dependency that can never resolve — low CPU, no stack, no message. That
14245 // is strictly worse than a panic, and it violates two rules at once:
14246 // "validate at graph-build time" and never-hang.
14247 //
14248 // `matmul`, `qmatmul`, `conv2d`, `paged_attn`, and everything routed via
14249 // `binary_op` already assert this. These builders did not — a real cost: a
14250 // peer session spent a long bisect localizing exactly this on `write_slice`.
14251 //
14252 // These tests only BUILD, never realize, so before the fix they fail fast
14253 // instead of hanging the suite.
14254
14255 #[test]
14256 fn write_slice_rejects_cross_graph_source() {
14257 let dest =
14258 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14259 // A SECOND `from_*` mints a second graph — the easy mistake to make,
14260 // and currently the un-diagnosable one.
14261 let foreign =
14262 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]), cpu_dev())
14263 .unwrap();
14264 assert_ne!(
14265 dest.graph_id(),
14266 foreign.graph_id(),
14267 "fixture must be cross-graph"
14268 );
14269
14270 let err = dest.write_slice(&foreign, vec![(2, 3), (0, 3)]);
14271 assert!(
14272 err.is_err(),
14273 "cross-graph source must be a build-time Err, not a realize-time hang",
14274 );
14275 let msg = format!("{}", err.unwrap_err());
14276 assert!(
14277 msg.contains("same graph"),
14278 "error should say the operands must share a graph, got: {msg}",
14279 );
14280 }
14281
14282 #[test]
14283 fn masked_fill_rejects_cross_graph_mask() {
14284 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14285 let foreign_mask =
14286 NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14287 assert_ne!(
14288 x.graph_id(),
14289 foreign_mask.graph_id(),
14290 "fixture must be cross-graph"
14291 );
14292
14293 let err = x.masked_fill(&foreign_mask, Scalar::F32(0.0));
14294 assert!(
14295 err.is_err(),
14296 "cross-graph mask must be a build-time Err, not a realize-time hang",
14297 );
14298 // MUST assert the reason, not just is_err(): this fixture also has a
14299 // dtype mismatch, so a bare `is_err()` passes for the WRONG reason and
14300 // would stay green even with no graph check at all.
14301 let msg = format!("{}", err.unwrap_err());
14302 assert!(
14303 msg.contains("same graph"),
14304 "must fail on GRAPH affinity, not incidentally on dtype, got: {msg}",
14305 );
14306 }
14307
14308 #[test]
14309 fn masked_fill_rejects_scale_dtype_at_build() {
14310 // F8E8M0 is a block-scale dtype: it HAS a scalar value (so the
14311 // value-dtype check passes) but no zero, so the MaskedFill backward
14312 // cannot produce a gradient. Reject at build time — and this must fail
14313 // on the dtype guard specifically: graph / shape / mask-Bool / value-dtype
14314 // are all satisfied, so a bare `is_err()` can only be the guard firing.
14315 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14316 let scale = x.cast(DType::F8E8M0);
14317 let mask = x.cast(DType::Bool);
14318 let value = Scalar::one(DType::F8E8M0).unwrap();
14319
14320 let err = scale.masked_fill(&mask, value);
14321 assert!(
14322 err.is_err(),
14323 "masked_fill on a scale dtype must be a build-time Err"
14324 );
14325 let msg = format!("{}", err.unwrap_err());
14326 assert!(
14327 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14328 "must fail on the packed/scale dtype guard, got: {msg}",
14329 );
14330 }
14331
14332 /// GAP-075 fix B: pin the REJECT verdict for every unfillable dtype
14333 /// individually (not a bucket count). The guard is semantic — packed
14334 /// formats (F4/F6*) have no representable fill value; block-scales
14335 /// (F8E8M0/F8E6M2) have no zero for the zero-filling backward — so each must
14336 /// be a build-time Err on the dtype GUARD specifically (its message names
14337 /// the op). Per-dtype pinning protects the classification: a future dtype
14338 /// misfiled into the allow arm can't hide behind a passing tally, and a new
14339 /// dtype with no verdict is caught by the compiler (the match is exhaustive,
14340 /// no wildcard). Paired with the allow test below (opposite assertion), the
14341 /// two are mutually non-vacuous.
14342 #[test]
14343 fn masked_fill_rejects_every_unfillable_dtype() {
14344 for dt in [
14345 DType::F4,
14346 DType::F6E2M3,
14347 DType::F6E3M2,
14348 DType::F8E8M0,
14349 DType::F8E6M2,
14350 ] {
14351 let x =
14352 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14353 let t = x.cast(dt);
14354 let mask = x.cast(DType::Bool);
14355 // The dtype guard fires before the value-dtype check, so a dummy
14356 // value is fine; the message assertion proves it was the guard.
14357 let err = t.masked_fill(&mask, Scalar::F32(0.0));
14358 assert!(err.is_err(), "masked_fill must reject {dt:?} at build time");
14359 let msg = format!("{}", err.unwrap_err());
14360 assert!(
14361 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14362 "{dt:?} must fail on the semantic dtype guard, got: {msg}",
14363 );
14364 }
14365 }
14366
14367 /// GAP-075 fix B: the allow arm is a graph-build PERMISSION (masked_fill is
14368 /// semantically well-defined — a fill value + a zero), NOT a claim a backend
14369 /// can allocate/run the dtype. F32 is the live consumer path (attention
14370 /// masking); I32 is an allowed verdict no consumer currently exercises —
14371 /// locking it preserves today's answer without asserting integer masked_fill
14372 /// is known to compute correctly (a backend lacking I32 storage still
14373 /// declines loudly at allocation, downstream of this permission).
14374 #[test]
14375 fn masked_fill_permits_fillable_dtypes_as_permission_not_capability() {
14376 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14377 let mask = x.cast(DType::Bool);
14378 assert!(
14379 x.masked_fill(&mask, Scalar::F32(0.0)).is_ok(),
14380 "F32 masked_fill must build (the live consumer path)",
14381 );
14382 let xi = x.cast(DType::I32);
14383 assert!(
14384 xi.masked_fill(&mask, Scalar::one(DType::I32).unwrap())
14385 .is_ok(),
14386 "I32 masked_fill must build — permission preserved, not a correctness claim",
14387 );
14388 }
14389
14390 #[test]
14391 #[should_panic(expected = "same graph")]
14392 fn rope_with_tables_panics_on_cross_graph_tables() {
14393 // Returns `NodeHandle`, so it follows the convention of the already-checked
14394 // builders (`matmul`, `paged_attn`) and asserts. A panic names the
14395 // problem at the build site; the status quo hangs later saying nothing.
14396 let x = NodeHandle::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[1, 1, 2, 4]), cpu_dev())
14397 .unwrap();
14398 let cos =
14399 NodeHandle::from_f32(vec![1.0_f32; 8], Shape::from_dims(&[2, 4]), cpu_dev()).unwrap();
14400 let sin = x
14401 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]))
14402 .unwrap();
14403 let _ = x.rope_with_tables(&cos, &sin);
14404 }
14405
14406 #[test]
14407 fn write_slice_rejects_slab_width_mismatch() {
14408 let dest =
14409 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14410 // Source has 2 elements along axis 0, but slab is width 1.
14411 let src = dest
14412 .const_f32_like(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]))
14413 .unwrap();
14414 let err = dest.write_slice(&src, vec![(2, 3), (0, 3)]);
14415 assert!(err.is_err(), "slab-width mismatch must error");
14416 }
14417
14418 #[test]
14419 fn write_slice_rejects_range_past_dest_extent() {
14420 let dest =
14421 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14422 let src = dest
14423 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14424 .unwrap();
14425 // axis 0: dest extent is 4; range [4, 5) is out of bounds.
14426 let err = dest.write_slice(&src, vec![(4, 5), (0, 3)]);
14427 assert!(err.is_err(), "range past dest extent must error");
14428 }
14429
14430 #[test]
14431 fn write_slice_derives_ordering_after_other_readers() {
14432 // Graph:
14433 // dest = ...; src = ...
14434 // ro = dest.relu() (non-destructive reader of dest)
14435 // w = dest.write_slice(&src, [(0,1),(0,3)]) (destructive on dest)
14436 // Expected ordering: w must run after ro.
14437 let dest =
14438 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14439 let src = dest
14440 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14441 .unwrap();
14442 let ro = dest.relu();
14443 let w = dest.write_slice(&src, vec![(0, 1), (0, 3)]).unwrap();
14444 let ord = crate::opt::derive_ordering(&dest.graph().read().unwrap(), &[ro.id(), w.id()]);
14445 let deps = ord.deps_of(w.id());
14446 assert_eq!(
14447 deps.len(),
14448 1,
14449 "write_slice should have one ordering dep (the relu)"
14450 );
14451 assert_eq!(
14452 deps[0],
14453 ro.id(),
14454 "write_slice must run after the non-destructive reader"
14455 );
14456 }
14457
14458 // ---- In-place ops Phase 1 -----------------------------------------------
14459 //
14460 // Smoke tests for the 5 new in-place unary variants
14461 // (`Op::ReluInplace`, `Op::SiluInplace`, `Op::GeluTanhInplace`,
14462 // `Op::TanhInplace`, `Op::SigmoidInplace`) and `FusedOps::INPLACE_AFFINE`.
14463 // Phase 1 only ships the structural plumbing (Op IR + destructive_input +
14464 // short_name + scheduler integration); dispatch + autograd land in Phases
14465 // 3 + 4. See `docs/session-prompts/in-place-ops-infrastructure.md`.
14466
14467 #[test]
14468 fn inplace_unary_destructive_input_is_zero() {
14469 for op in [
14470 Op::ReluInplace,
14471 Op::SiluInplace,
14472 Op::GeluTanhInplace,
14473 Op::TanhInplace,
14474 Op::SigmoidInplace,
14475 Op::NegInplace,
14476 Op::AbsInplace,
14477 Op::SqrInplace,
14478 Op::SqrtInplace,
14479 Op::RsqrtInplace,
14480 Op::RecipInplace,
14481 Op::ExpInplace,
14482 Op::LogInplace,
14483 Op::SinInplace,
14484 Op::CosInplace,
14485 Op::SignInplace,
14486 Op::FloorInplace,
14487 Op::CeilInplace,
14488 Op::RoundInplace,
14489 Op::ErfInplace,
14490 Op::GeluInplace,
14491 ] {
14492 assert_eq!(
14493 op.destructive_input(),
14494 Some(0),
14495 "in-place unary {op:?} must declare input 0 destructive",
14496 );
14497 }
14498 }
14499
14500 #[test]
14501 fn inplace_unary_short_names_round_trip() {
14502 assert_eq!(Op::ReluInplace.short_name(), "ReluInplace");
14503 assert_eq!(Op::SiluInplace.short_name(), "SiluInplace");
14504 assert_eq!(Op::GeluTanhInplace.short_name(), "GeluTanhInplace");
14505 assert_eq!(Op::TanhInplace.short_name(), "TanhInplace");
14506 assert_eq!(Op::SigmoidInplace.short_name(), "SigmoidInplace");
14507 assert_eq!(Op::NegInplace.short_name(), "NegInplace");
14508 assert_eq!(Op::AbsInplace.short_name(), "AbsInplace");
14509 assert_eq!(Op::SqrInplace.short_name(), "SqrInplace");
14510 assert_eq!(Op::SqrtInplace.short_name(), "SqrtInplace");
14511 assert_eq!(Op::RsqrtInplace.short_name(), "RsqrtInplace");
14512 assert_eq!(Op::RecipInplace.short_name(), "RecipInplace");
14513 assert_eq!(Op::ExpInplace.short_name(), "ExpInplace");
14514 assert_eq!(Op::LogInplace.short_name(), "LogInplace");
14515 assert_eq!(Op::SinInplace.short_name(), "SinInplace");
14516 assert_eq!(Op::CosInplace.short_name(), "CosInplace");
14517 assert_eq!(Op::SignInplace.short_name(), "SignInplace");
14518 assert_eq!(Op::FloorInplace.short_name(), "FloorInplace");
14519 assert_eq!(Op::CeilInplace.short_name(), "CeilInplace");
14520 assert_eq!(Op::RoundInplace.short_name(), "RoundInplace");
14521 assert_eq!(Op::ErfInplace.short_name(), "ErfInplace");
14522 assert_eq!(Op::GeluInplace.short_name(), "GeluInplace");
14523 assert_eq!(
14524 Op::ClampInplace { min: 0.0, max: 1.0 }.short_name(),
14525 "ClampInplace"
14526 );
14527 assert_eq!(Op::PowIInplace(3).short_name(), "PowIInplace");
14528 }
14529
14530 #[test]
14531 fn inplace_affine_fused_op_destructive_input_is_zero() {
14532 let op = Op::Fused(
14533 crate::registry::FusedOps::INPLACE_AFFINE,
14534 crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 },
14535 );
14536 assert_eq!(op.destructive_input(), Some(0));
14537 }
14538
14539 #[test]
14540 fn destructive_input_for_fused_is_registry_declared() {
14541 // GAP-076: a fused op's destructiveness is a MANDATORY declared field on
14542 // its registry entry, and `Op::destructive_input` reads that field via
14543 // `default_registry()` rather than a hardcoded id match that could drift
14544 // out of sync. This locks BOTH directions of the declaration plus the
14545 // routing that reads it. Regression lock, not a born-red: no op was
14546 // misclassified before the fix — its value is that a future wrong
14547 // declaration (or a reverted routing) reddens HERE instead of surfacing
14548 // as an intermittent scheduler data race that points nowhere near this
14549 // code. The exhaustive match in `Op::destructive_input` and the
14550 // mandatory struct field are the compile-time seams; this is the belt.
14551 use crate::registry::{FusedOps, default_registry};
14552 let reg = default_registry();
14553 assert_eq!(
14554 reg.entry(FusedOps::INPLACE_AFFINE)
14555 .expect("INPLACE_AFFINE is registered")
14556 .destructive_input,
14557 Some(0),
14558 "InplaceAffine must declare itself destructive on input 0",
14559 );
14560 assert_eq!(
14561 reg.entry(FusedOps::SOFTMAX_LAST_DIM)
14562 .expect("SOFTMAX_LAST_DIM is registered")
14563 .destructive_input,
14564 None,
14565 "a functional fused op must declare itself non-destructive",
14566 );
14567 // Routing reads the declared field (not a hardcoded id match).
14568 let op = Op::Fused(
14569 FusedOps::INPLACE_AFFINE,
14570 crate::registry::FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 },
14571 );
14572 assert_eq!(op.destructive_input(), Some(0));
14573 }
14574
14575 #[test]
14576 fn inplace_affine_params_key_dedupe_on_same_mul_add() {
14577 // Two `InplaceAffine` params with identical (mul, add) hash to the
14578 // same key; differing values produce distinct keys. Lets CSE / the
14579 // existing op_key infrastructure collapse identical in-place affines
14580 // (when callers wire them through the equivalent graph machinery).
14581 let a = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14582 let b = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14583 let c = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 0.5 };
14584 assert_eq!(a.key(), b.key(), "identical mul/add must dedupe");
14585 assert_ne!(a.key(), c.key(), "different add must produce distinct key");
14586 }
14587
14588 // ---- Phase 4 — autograd through in-place ops ----
14589 //
14590 // The view-aware `derive_ordering` (Phase 4a) ensures backward
14591 // grad nodes that read forward inputs run BEFORE any in-place
14592 // mutation of those inputs. The backward arms in
14593 // `NodeHandle::backward` (Phase 4b) emit the same gradient graph as
14594 // the non-inplace cousins. These tests prove that calling
14595 // `.backward()` through an in-place node:
14596 // (1) does NOT panic (was previously guarded by the Phase 1
14597 // defensive panic);
14598 // (2) emits the same gradient-node structure as the non-inplace
14599 // cousin (matching node counts + op types as a structural
14600 // proxy for numerical equivalence — the actual numerics are
14601 // exercised by the live oracle tests in fuel-storage).
14602
14603 #[test]
14604 fn backward_through_relu_inplace_does_not_panic() {
14605 // y = x.relu_inplace(); loss = y.sum_all(); loss.backward()
14606 // Phase 1's defensive panic is removed; backward emits
14607 // Op::Step(x) + Op::Mul(upstream, step) — same as Op::Relu.
14608 let x =
14609 NodeHandle::from_f32(vec![1.0, -2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14610 let y = x.relu_inplace();
14611 let loss = y.sum_all();
14612 let grads = loss.backward();
14613 let g_x = grads.get(&x).expect("gradient for x should be present");
14614 // Same structural form as Op::Relu's backward: gradient node
14615 // is an Op::Mul (upstream × step(x)).
14616 let g_node = g_x.graph().read().unwrap().node(g_x.id()).clone();
14617 assert!(
14618 matches!(g_node.op, Op::Mul),
14619 "relu backward grad is Mul; got {:?}",
14620 g_node.op
14621 );
14622 }
14623
14624 #[test]
14625 fn backward_through_sigmoid_inplace_does_not_panic() {
14626 let x = NodeHandle::from_f32(vec![0.5, -0.5], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14627 let y = x.sigmoid_inplace();
14628 let loss = y.sum_all();
14629 let grads = loss.backward();
14630 let g_x = grads.get(&x);
14631 assert!(g_x.is_some());
14632 }
14633
14634 #[test]
14635 fn backward_through_tanh_inplace_does_not_panic() {
14636 let x =
14637 NodeHandle::from_f32(vec![0.1, 0.2, 0.3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14638 let y = x.tanh_inplace();
14639 let loss = y.sum_all();
14640 let grads = loss.backward();
14641 let g_x = grads.get(&x);
14642 assert!(g_x.is_some());
14643 }
14644
14645 #[test]
14646 fn backward_through_silu_inplace_does_not_panic() {
14647 let x = NodeHandle::from_f32(vec![0.1, 0.2], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14648 let y = x.silu_inplace();
14649 let loss = y.sum_all();
14650 let grads = loss.backward();
14651 let g_x = grads.get(&x);
14652 assert!(g_x.is_some());
14653 }
14654
14655 /// The reverse walk has hand-written arms for some fused ids and lowers the
14656 /// rest through their total `decompose` first; WHICH ids take the second path
14657 /// is whatever the registry declares as `BackwardKind::Decompose`. Pin that
14658 /// set so adding or flipping one is a deliberate change that also adds its
14659 /// finite-difference test (SSM recipes: `fuel-tensor` scan tests;
14660 /// FusedSoftmaxCrossEntropy: `fuel-training`; NF4/AWQ matmul and causal
14661 /// conv1d: `fuel-tensor` `*_gradient_matches_finite_difference`).
14662 #[test]
14663 fn decompose_declared_fused_ops_are_exactly_the_tested_set() {
14664 use crate::registry::{BackwardKind, FusedOps, default_registry};
14665 let declared: Vec<_> = default_registry()
14666 .entries_iter()
14667 .filter(|e| e.backward == BackwardKind::Decompose)
14668 .map(|e| e.id)
14669 .collect();
14670 let expected = [
14671 FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
14672 FusedOps::SELECTIVE_SCAN,
14673 FusedOps::SSD_CHUNK_SCAN,
14674 FusedOps::NF4_MATMUL,
14675 FusedOps::AWQ_MATMUL,
14676 FusedOps::CAUSAL_CONV1D,
14677 ];
14678 assert_eq!(declared.len(), expected.len(), "declared: {declared:?}");
14679 for id in expected {
14680 assert!(declared.contains(&id), "{id:?} lost its Decompose backward");
14681 assert!(
14682 lowers_for_backward(id),
14683 "{id:?} not lowered by the pre-pass"
14684 );
14685 }
14686 // Control: a hand-armed op is not lowered.
14687 assert!(!lowers_for_backward(FusedOps::SOFTMAX_LAST_DIM));
14688 }
14689
14690 #[test]
14691 fn backward_through_gelu_tanh_inplace_does_not_panic() {
14692 // Numerics are checked against finite differences in fuel-tensor
14693 // (`gelu_tanh_inplace_backward_matches_finite_difference`).
14694 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14695 let y = x.gelu_tanh_inplace();
14696 let loss = y.sum_all();
14697 let grads = loss.backward();
14698 assert!(grads.get(&x).is_some());
14699 }
14700
14701 #[test]
14702 fn backward_through_gelu_tanh_does_not_panic() {
14703 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14704 let loss = x.gelu_tanh().sum_all();
14705 let grads = loss.backward();
14706 assert!(grads.get(&x).is_some());
14707 }
14708
14709 #[test]
14710 fn backward_through_relu_inplace_emits_same_graph_shape_as_functional() {
14711 // Structural parity: relu_inplace backward emits the same node
14712 // count + same op variants as relu backward, since the
14713 // gradient formula is identical.
14714 let x_inp =
14715 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14716 let y_inp = x_inp.relu_inplace();
14717 let loss_inp = y_inp.sum_all();
14718 let nodes_before_inp = loss_inp.graph().read().unwrap().len();
14719 let _ = loss_inp.backward();
14720 let added_inp = loss_inp.graph().read().unwrap().len() - nodes_before_inp;
14721
14722 let x_fn =
14723 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14724 let y_fn = x_fn.relu();
14725 let loss_fn = y_fn.sum_all();
14726 let nodes_before_fn = loss_fn.graph().read().unwrap().len();
14727 let _ = loss_fn.backward();
14728 let added_fn = loss_fn.graph().read().unwrap().len() - nodes_before_fn;
14729
14730 assert_eq!(
14731 added_inp, added_fn,
14732 "ReluInplace backward should add the same number of nodes as Relu backward ({added_fn}), got {added_inp}",
14733 );
14734 }
14735
14736 #[test]
14737 fn relu_inplace_builder_emits_op_reluinplace() {
14738 let x = NodeHandle::from_f32(
14739 vec![1.0_f32, -1.0, 2.0, -2.0],
14740 Shape::from_dims(&[4]),
14741 cpu_dev(),
14742 )
14743 .unwrap();
14744 let y = x.relu_inplace();
14745 let g = y.graph().read().unwrap();
14746 let node = g.node(y.id());
14747 assert!(matches!(node.op, Op::ReluInplace));
14748 assert_eq!(node.inputs, vec![x.id()]);
14749 assert_eq!(node.shape.dims(), &[4]);
14750 assert_eq!(node.dtype, DType::F32);
14751 }
14752
14753 #[test]
14754 fn affine_inplace_builder_emits_fused_inplace_affine() {
14755 let x = NodeHandle::from_f32(
14756 vec![1.0_f32, 2.0, 3.0, 4.0],
14757 Shape::from_dims(&[4]),
14758 cpu_dev(),
14759 )
14760 .unwrap();
14761 let y = x.affine_inplace(2.0, 0.5);
14762 let g = y.graph().read().unwrap();
14763 let node = g.node(y.id());
14764 match &node.op {
14765 Op::Fused(id, crate::registry::FusedOpParams::InplaceAffine { mul, add }) => {
14766 assert_eq!(*id, crate::registry::FusedOps::INPLACE_AFFINE);
14767 assert_eq!(*mul, 2.0);
14768 assert_eq!(*add, 0.5);
14769 }
14770 other => panic!("expected Op::Fused(INPLACE_AFFINE, InplaceAffine), got {other:?}"),
14771 }
14772 assert_eq!(node.inputs, vec![x.id()]);
14773 assert_eq!(node.shape.dims(), &[4]);
14774 }
14775
14776 #[test]
14777 fn all_inplace_unary_builders_round_trip_through_op_variants() {
14778 // One smoke per variant — each builder emits exactly the
14779 // matching `Op::*Inplace` variant, single input, shape +
14780 // dtype unchanged.
14781 let x = NodeHandle::from_f32(vec![0.5_f32; 8], Shape::from_dims(&[8]), cpu_dev()).unwrap();
14782 fn check(y: NodeHandle, x_id: NodeId, expect: fn(&Op) -> bool) {
14783 let g = y.graph().read().unwrap();
14784 let node = g.node(y.id());
14785 assert!(expect(&node.op), "wrong Op variant: {:?}", node.op);
14786 assert_eq!(node.inputs, vec![x_id]);
14787 assert_eq!(node.shape.dims(), &[8]);
14788 assert_eq!(node.dtype, DType::F32);
14789 }
14790 check(x.relu_inplace(), x.id(), |o| matches!(o, Op::ReluInplace));
14791 check(x.silu_inplace(), x.id(), |o| matches!(o, Op::SiluInplace));
14792 check(x.gelu_tanh_inplace(), x.id(), |o| {
14793 matches!(o, Op::GeluTanhInplace)
14794 });
14795 check(x.tanh_inplace(), x.id(), |o| matches!(o, Op::TanhInplace));
14796 check(x.sigmoid_inplace(), x.id(), |o| {
14797 matches!(o, Op::SigmoidInplace)
14798 });
14799 check(x.neg_inplace(), x.id(), |o| matches!(o, Op::NegInplace));
14800 check(x.abs_inplace(), x.id(), |o| matches!(o, Op::AbsInplace));
14801 check(x.sqr_inplace(), x.id(), |o| matches!(o, Op::SqrInplace));
14802 check(x.sqrt_inplace(), x.id(), |o| matches!(o, Op::SqrtInplace));
14803 check(x.rsqrt_inplace(), x.id(), |o| matches!(o, Op::RsqrtInplace));
14804 check(x.recip_inplace(), x.id(), |o| matches!(o, Op::RecipInplace));
14805 check(x.exp_inplace(), x.id(), |o| matches!(o, Op::ExpInplace));
14806 check(x.log_inplace(), x.id(), |o| matches!(o, Op::LogInplace));
14807 check(x.sin_inplace(), x.id(), |o| matches!(o, Op::SinInplace));
14808 check(x.cos_inplace(), x.id(), |o| matches!(o, Op::CosInplace));
14809 check(x.sign_inplace(), x.id(), |o| matches!(o, Op::SignInplace));
14810 check(x.floor_inplace(), x.id(), |o| matches!(o, Op::FloorInplace));
14811 check(x.ceil_inplace(), x.id(), |o| matches!(o, Op::CeilInplace));
14812 check(x.round_inplace(), x.id(), |o| matches!(o, Op::RoundInplace));
14813 check(x.erf_inplace(), x.id(), |o| matches!(o, Op::ErfInplace));
14814 check(x.gelu_inplace(), x.id(), |o| matches!(o, Op::GeluInplace));
14815 check(x.clamp_inplace(-1.0, 1.0), x.id(), |o| {
14816 matches!(o, Op::ClampInplace { .. })
14817 });
14818 check(x.powi_inplace(3), x.id(), |o| {
14819 matches!(o, Op::PowIInplace(3))
14820 });
14821 }
14822
14823 /// Backward smoke for the expanded in-place op family — each variant
14824 /// (except zero-grad ones) must produce a gradient node for x without
14825 /// panicking. Zero-grad variants (Sign/Floor/Ceil/Round) drop the
14826 /// gradient entirely (no entry in the GradMap), mirroring their
14827 /// non-inplace cousins.
14828 #[test]
14829 fn backward_through_expanded_inplace_unary_emits_grad() {
14830 fn check_emits_grad(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14831 let x =
14832 NodeHandle::from_f32(vec![0.5_f32, 1.5, 2.5], Shape::from_dims(&[3]), cpu_dev())
14833 .unwrap();
14834 let y = make(&x);
14835 let loss = y.sum_all();
14836 let grads = loss.backward();
14837 assert!(grads.get(&x).is_some(), "backward must emit gradient for x");
14838 }
14839 check_emits_grad(|x| x.neg_inplace());
14840 check_emits_grad(|x| x.abs_inplace());
14841 check_emits_grad(|x| x.sqr_inplace());
14842 check_emits_grad(|x| x.sqrt_inplace());
14843 check_emits_grad(|x| x.rsqrt_inplace());
14844 check_emits_grad(|x| x.recip_inplace());
14845 check_emits_grad(|x| x.exp_inplace());
14846 check_emits_grad(|x| x.log_inplace());
14847 check_emits_grad(|x| x.sin_inplace());
14848 check_emits_grad(|x| x.cos_inplace());
14849 check_emits_grad(|x| x.erf_inplace());
14850 check_emits_grad(|x| x.gelu_inplace());
14851 check_emits_grad(|x| x.clamp_inplace(-1.0, 2.0));
14852 check_emits_grad(|x| x.powi_inplace(3));
14853 }
14854
14855 #[test]
14856 fn backward_through_zero_grad_inplace_drops_gradient() {
14857 fn check_drops(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14858 let x =
14859 NodeHandle::from_f32(vec![1.5_f32, 2.5, -3.5], Shape::from_dims(&[3]), cpu_dev())
14860 .unwrap();
14861 let y = make(&x);
14862 let loss = y.sum_all();
14863 let grads = loss.backward();
14864 assert!(
14865 grads.get(&x).is_none(),
14866 "zero-grad in-place op must not emit gradient"
14867 );
14868 }
14869 check_drops(|x| x.sign_inplace());
14870 check_drops(|x| x.floor_inplace());
14871 check_drops(|x| x.ceil_inplace());
14872 check_drops(|x| x.round_inplace());
14873 }
14874
14875 #[test]
14876 fn inplace_unary_derives_ordering_after_non_destructive_readers() {
14877 // Graph:
14878 // x = const f32 [4]
14879 // y_a = x.relu() (non-destructive reader of x)
14880 // y_b = manually-pushed Op::ReluInplace on x (destructive)
14881 // Expected: y_b must run after y_a.
14882 let x = NodeHandle::from_f32(
14883 vec![1.0_f32, -1.0, 2.0, -2.0],
14884 Shape::from_dims(&[4]),
14885 cpu_dev(),
14886 )
14887 .unwrap();
14888 let y_a = x.relu();
14889 let y_b_id = x.graph().write().unwrap().push(Node {
14890 op: Op::ReluInplace,
14891 inputs: vec![x.id()],
14892 shape: Shape::from_dims(&[4]),
14893 dtype: DType::F32,
14894 });
14895 let ord = crate::opt::derive_ordering(&x.graph().read().unwrap(), &[y_a.id(), y_b_id]);
14896 let deps = ord.deps_of(y_b_id);
14897 assert_eq!(deps.len(), 1, "in-place unary should have one ordering dep");
14898 assert_eq!(
14899 deps[0],
14900 y_a.id(),
14901 "in-place unary must run after the non-destructive reader"
14902 );
14903 }
14904
14905 // ------------------------------------------------------------------
14906 // Multi-output nodes (Option C, Session 1)
14907 // ------------------------------------------------------------------
14908
14909 use fuel_backend_contract::storage::Storage as CoreStorage;
14910 use fuel_ir::storage::OutputView;
14911
14912 /// Build a real CPU `Storage` of `n` F32 zeros so `Storage`-level
14913 /// tests can attach + read bundle metadata against a live backend
14914 /// allocator. The dtype is fixed at F32 because every existing
14915 /// `OutputView` test below uses F32 for slot 0; bundle dtype is
14916 /// validated at `with_bundle` time against this primary dtype.
14917 fn cpu_f32_storage(n: usize) -> CoreStorage {
14918 let dev = cpu_dev();
14919 let buf = fuel_ir::HostBuffer::F32(vec![0.0_f32; n]);
14920 let inner = dev
14921 .storage_from_host_buffer_owned_dyn(buf)
14922 .expect("test fixture: F32 storage_from_host_buffer_owned_dyn failed");
14923 CoreStorage::from_dyn(inner)
14924 }
14925
14926 /// Build a 2-slot bundle: slot 0 `[2, 3]` F32 `y`-shape, slot 1
14927 /// `[2, 4]` F32 `last_state`-shape. Returns the views and the
14928 /// total element count (used to size the backing CPU buffer so
14929 /// slot 1's byte range stays inside the bundle's bytes).
14930 fn two_slot_views() -> (Vec<OutputView>, usize) {
14931 let s0 = Shape::from_dims(&[2, 3]);
14932 let s1 = Shape::from_dims(&[2, 4]);
14933 let v0 = OutputView {
14934 byte_offset: 0,
14935 len_elements: s0.elem_count(),
14936 dtype: DType::F32,
14937 shape: s0.clone(),
14938 layout: Layout::contiguous(s0),
14939 name: Some("y"),
14940 };
14941 let v1 = OutputView {
14942 byte_offset: v0.len_bytes(),
14943 len_elements: s1.elem_count(),
14944 dtype: DType::F32,
14945 shape: s1.clone(),
14946 layout: Layout::contiguous(s1),
14947 name: Some("last_state"),
14948 };
14949 let total = v0.len_elements + v1.len_elements;
14950 (vec![v0, v1], total)
14951 }
14952
14953 /// `Storage::is_bundled` is false by default; `slot_count` is 1;
14954 /// `bundle` / `bundle_arc` / `slot_view` / `slot_dtype` all return
14955 /// `None` for the non-multi-output case.
14956 #[test]
14957 fn storage_single_output_defaults() {
14958 let s = cpu_f32_storage(8);
14959 assert!(!s.is_bundled());
14960 assert_eq!(s.slot_count(), 1);
14961 assert!(s.bundle().is_none());
14962 assert!(s.bundle_arc().is_none());
14963 assert!(s.slot_view(0).is_none());
14964 assert_eq!(s.slot_dtype(0), None);
14965 assert_eq!(s.primary_dtype(), DType::F32);
14966 assert_eq!(s.dtype(), DType::F32);
14967 }
14968
14969 /// `Storage::with_bundle` attaches the side-table and per-slot
14970 /// lookups report the declared shape/dtype.
14971 #[test]
14972 fn storage_with_bundle_attaches_views() {
14973 let (views, total) = two_slot_views();
14974 let s = cpu_f32_storage(total)
14975 .with_bundle(views.clone().into())
14976 .expect("with_bundle should accept matching slot-0 dtype");
14977 assert!(s.is_bundled());
14978 assert_eq!(s.slot_count(), 2);
14979 let slot0 = s.slot_view(0).unwrap();
14980 assert_eq!(slot0.shape, Shape::from_dims(&[2, 3]));
14981 assert_eq!(slot0.dtype, DType::F32);
14982 assert_eq!(slot0.byte_offset, 0);
14983 assert_eq!(slot0.name, Some("y"));
14984 let slot1 = s.slot_view(1).unwrap();
14985 assert_eq!(slot1.shape, Shape::from_dims(&[2, 4]));
14986 assert_eq!(slot1.byte_offset, 24); // 6 F32s = 24 bytes
14987 assert_eq!(slot1.name, Some("last_state"));
14988 // Out-of-range slot reads `None`, doesn't panic.
14989 assert!(s.slot_view(2).is_none());
14990 assert_eq!(s.slot_dtype(2), None);
14991 }
14992
14993 /// `Storage::with_bundle` rejects an empty bundle slice (a
14994 /// zero-slot bundle is a contract bug — use a single-output
14995 /// Storage if there's nothing to project).
14996 #[test]
14997 fn storage_with_bundle_rejects_empty() {
14998 let s = cpu_f32_storage(1);
14999 let empty: Arc<[OutputView]> = Arc::from(Vec::<OutputView>::new().into_boxed_slice());
15000 let err = s
15001 .with_bundle(empty)
15002 .expect_err("empty bundle slice must error");
15003 let msg = format!("{err}");
15004 assert!(msg.contains("non-empty"), "error message: {msg}");
15005 }
15006
15007 /// `Storage::with_bundle` rejects slot 0 dtype that disagrees with
15008 /// the inner backend dtype — the bundle invariant "slot 0 dtype ==
15009 /// primary_dtype()" must hold.
15010 #[test]
15011 fn storage_with_bundle_rejects_dtype_mismatch() {
15012 let s = cpu_f32_storage(8);
15013 let bad = OutputView {
15014 byte_offset: 0,
15015 len_elements: 4,
15016 dtype: DType::F64,
15017 shape: Shape::from_dims(&[2, 2]),
15018 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15019 name: None,
15020 };
15021 let err = s
15022 .with_bundle(Arc::from(vec![bad].into_boxed_slice()))
15023 .expect_err("slot 0 dtype mismatch must error");
15024 let msg = format!("{err}");
15025 assert!(msg.contains("dtype"), "error message: {msg}");
15026 }
15027
15028 /// `Graph::output_views` is `None` for ordinary single-output
15029 /// nodes; `multi_output_count` is 0.
15030 #[test]
15031 fn graph_output_views_defaults() {
15032 let mut g = Graph::new();
15033 let id = g.push(Node {
15034 op: Op::Const,
15035 inputs: vec![],
15036 shape: Shape::from_dims(&[2, 3]),
15037 dtype: DType::F32,
15038 });
15039 assert!(g.output_views(id).is_none());
15040 assert!(!g.is_multi_output(id));
15041 assert_eq!(g.multi_output_count(), 0);
15042 }
15043
15044 /// `Graph::set_output_views` round-trips: read returns what was
15045 /// written; `is_multi_output` flips.
15046 #[test]
15047 fn graph_set_output_views_roundtrip() {
15048 let mut g = Graph::new();
15049 let id = g.push(Node {
15050 op: Op::Const,
15051 inputs: vec![],
15052 shape: Shape::from_dims(&[2, 3]),
15053 dtype: DType::F32,
15054 });
15055 let (views, _) = two_slot_views();
15056 g.set_output_views(id, views.clone().into())
15057 .expect("valid 2-slot specs");
15058 assert!(g.is_multi_output(id));
15059 assert_eq!(g.multi_output_count(), 1);
15060 let read = g.output_views(id).expect("entry present");
15061 assert_eq!(read.len(), 2);
15062 assert_eq!(read[1].shape, Shape::from_dims(&[2, 4]));
15063 }
15064
15065 /// `Graph::set_output_views` rejects slot 0 dtype/shape that
15066 /// disagree with the producer node's primary shape/dtype.
15067 #[test]
15068 fn graph_set_output_views_validates_primary() {
15069 let mut g = Graph::new();
15070 let id = g.push(Node {
15071 op: Op::Const,
15072 inputs: vec![],
15073 shape: Shape::from_dims(&[2, 3]),
15074 dtype: DType::F32,
15075 });
15076 // dtype mismatch on slot 0
15077 let bad_dtype = OutputView {
15078 byte_offset: 0,
15079 len_elements: 6,
15080 dtype: DType::F64,
15081 shape: Shape::from_dims(&[2, 3]),
15082 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15083 name: None,
15084 };
15085 let err = g
15086 .set_output_views(id, vec![bad_dtype].into())
15087 .expect_err("primary dtype mismatch must error");
15088 let msg = format!("{err}");
15089 assert!(msg.contains("dtype"), "error message: {msg}");
15090 // shape mismatch on slot 0
15091 let bad_shape = OutputView {
15092 byte_offset: 0,
15093 len_elements: 4,
15094 dtype: DType::F32,
15095 shape: Shape::from_dims(&[2, 2]),
15096 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15097 name: None,
15098 };
15099 let err = g
15100 .set_output_views(id, vec![bad_shape].into())
15101 .expect_err("primary shape mismatch must error");
15102 let msg = format!("{err}");
15103 assert!(msg.contains("shape"), "error message: {msg}");
15104 }
15105
15106 /// `NodeHandle::view(slot)` against a producer that hasn't been
15107 /// declared multi-output returns Err — fails fast at build time.
15108 #[test]
15109 fn tensor_view_on_non_multi_output_errors() {
15110 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15111 let id = graph.write().unwrap().push(Node {
15112 op: Op::Const,
15113 inputs: vec![],
15114 shape: Shape::from_dims(&[2, 3]),
15115 dtype: DType::F32,
15116 });
15117 let producer = NodeHandle::from_existing(Arc::clone(&graph), id);
15118 let err = producer
15119 .view(0)
15120 .expect_err("view on non-multi-output producer must error");
15121 let msg = format!("{err}");
15122 assert!(msg.contains("multi-output"), "error message: {msg}");
15123 }
15124
15125 /// `NodeHandle::view(slot)` with slot OOB returns Err.
15126 #[test]
15127 fn tensor_view_oob_slot_errors() {
15128 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15129 let producer_id = {
15130 let mut g = graph.write().unwrap();
15131 let id = g.push(Node {
15132 op: Op::Const,
15133 inputs: vec![],
15134 shape: Shape::from_dims(&[2, 3]),
15135 dtype: DType::F32,
15136 });
15137 let (views, _) = two_slot_views();
15138 g.set_output_views(id, views.into())
15139 .expect("valid 2-slot specs");
15140 id
15141 };
15142 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15143 let err = producer
15144 .view(2)
15145 .expect_err("slot 2 of a 2-slot producer must error");
15146 let msg = format!("{err}");
15147 assert!(msg.contains("out of range"), "error message: {msg}");
15148 }
15149
15150 /// `NodeHandle::view(slot)` produces a tensor whose shape/dtype match
15151 /// the slot spec; producer's primary shape stays as slot 0's. The
15152 /// View node holds the producer in `inputs[0]`.
15153 #[test]
15154 fn tensor_view_shape_dtype_from_slot() {
15155 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15156 let producer_id = {
15157 let mut g = graph.write().unwrap();
15158 let id = g.push(Node {
15159 op: Op::Const,
15160 inputs: vec![],
15161 shape: Shape::from_dims(&[2, 3]),
15162 dtype: DType::F32,
15163 });
15164 let (views, _) = two_slot_views();
15165 g.set_output_views(id, views.into())
15166 .expect("valid 2-slot specs");
15167 id
15168 };
15169 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15170 let v0 = producer.view(0).expect("slot 0 view");
15171 assert_eq!(v0.shape(), Shape::from_dims(&[2, 3]));
15172 assert_eq!(v0.dtype(), DType::F32);
15173 let v1 = producer.view(1).expect("slot 1 view");
15174 assert_eq!(v1.shape(), Shape::from_dims(&[2, 4]));
15175 assert_eq!(v1.dtype(), DType::F32);
15176 // View node carries the producer in inputs[0] and the slot
15177 // index in the Op variant — verify the Graph state directly.
15178 let g = graph.read().unwrap();
15179 let v1_node = g.node(v1.id());
15180 assert_eq!(v1_node.inputs, vec![producer_id]);
15181 assert!(matches!(v1_node.op, Op::View { slot: 1 }));
15182 // Slot 0 starts at byte_offset 0 + contiguous → layout
15183 // matches Layout::contiguous(slot0.shape) → no side-table
15184 // entry (the contiguous fallback covers it).
15185 assert!(!g.has_explicit_layout(v0.id()));
15186 // Slot 1 starts at byte_offset 24 (= 6 F32 elements past
15187 // slot 0). Session 4 bakes that into the layout's
15188 // start_offset so a downstream kernel reading the producer's
15189 // bytes as F32 elements lands on slot 1's first byte. Side-
15190 // table entry is mandatory.
15191 assert!(g.has_explicit_layout(v1.id()));
15192 let l1 = g.layout(v1.id());
15193 assert_eq!(
15194 l1.start_offset(),
15195 6,
15196 "slot 1 byte_offset 24 / 4 = 6 F32 elements"
15197 );
15198 assert_eq!(l1.shape(), &Shape::from_dims(&[2, 4]));
15199 }
15200
15201 /// `NodeHandle::view(slot)` over a slot whose layout is non-contiguous
15202 /// (strided) populates the Graph's layout side-table with the
15203 /// slot's layout — so downstream consumers see the strided view.
15204 #[test]
15205 fn tensor_view_propagates_non_contiguous_slot_layout() {
15206 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15207 let strided_shape = Shape::from_dims(&[2, 3]);
15208 let strided_layout = Layout::contiguous(strided_shape.clone())
15209 .transpose(0, 1)
15210 .expect("transpose [2,3] -> [3,2]");
15211 // Slot 0 = primary (contiguous, matches producer's Node shape).
15212 let s0 = OutputView {
15213 byte_offset: 0,
15214 len_elements: strided_shape.elem_count(),
15215 dtype: DType::F32,
15216 shape: strided_shape.clone(),
15217 layout: Layout::contiguous(strided_shape.clone()),
15218 name: Some("primary"),
15219 };
15220 // Slot 1 = strided projection. Same byte range as slot 0; the
15221 // shape after transpose is [3, 2]; layout's start offset stays
15222 // within the slot.
15223 let s1 = OutputView {
15224 byte_offset: 0,
15225 len_elements: strided_shape.elem_count(),
15226 dtype: DType::F32,
15227 shape: Shape::from_dims(&[3, 2]),
15228 layout: strided_layout.clone(),
15229 name: Some("strided_view"),
15230 };
15231 let producer_id = {
15232 let mut g = graph.write().unwrap();
15233 let id = g.push(Node {
15234 op: Op::Const,
15235 inputs: vec![],
15236 shape: strided_shape.clone(),
15237 dtype: DType::F32,
15238 });
15239 g.set_output_views(id, vec![s0, s1].into())
15240 .expect("valid 2-slot strided spec");
15241 id
15242 };
15243 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15244 let v1 = producer.view(1).expect("strided slot view");
15245 let g = graph.read().unwrap();
15246 assert!(
15247 g.has_explicit_layout(v1.id()),
15248 "strided slot must populate Graph::layouts side-table",
15249 );
15250 let read_layout = g.layout(v1.id());
15251 assert_eq!(read_layout.shape(), strided_layout.shape());
15252 assert_eq!(read_layout.stride(), strided_layout.stride());
15253 }
15254
15255 /// `NodeHandle::view_owned(slot)` produces the same shape/dtype as
15256 /// `NodeHandle::view(slot)` but its output layout is ALWAYS contiguous
15257 /// — the forward memcpy produces a fresh standalone buffer, so
15258 /// the slot's (possibly strided) layout is not propagated.
15259 #[test]
15260 fn tensor_view_owned_layout_is_contiguous() {
15261 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15262 let strided_shape = Shape::from_dims(&[2, 3]);
15263 let strided_layout = Layout::contiguous(strided_shape.clone())
15264 .transpose(0, 1)
15265 .expect("transpose [2,3] -> [3,2]");
15266 let s0 = OutputView {
15267 byte_offset: 0,
15268 len_elements: strided_shape.elem_count(),
15269 dtype: DType::F32,
15270 shape: strided_shape.clone(),
15271 layout: Layout::contiguous(strided_shape.clone()),
15272 name: None,
15273 };
15274 let s1 = OutputView {
15275 byte_offset: 0,
15276 len_elements: strided_shape.elem_count(),
15277 dtype: DType::F32,
15278 shape: Shape::from_dims(&[3, 2]),
15279 layout: strided_layout,
15280 name: None,
15281 };
15282 let producer_id = {
15283 let mut g = graph.write().unwrap();
15284 let id = g.push(Node {
15285 op: Op::Const,
15286 inputs: vec![],
15287 shape: strided_shape,
15288 dtype: DType::F32,
15289 });
15290 g.set_output_views(id, vec![s0, s1].into())
15291 .expect("valid 2-slot specs");
15292 id
15293 };
15294 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15295 let v1 = producer.view_owned(1).expect("ViewOwned slot 1");
15296 assert_eq!(v1.shape(), Shape::from_dims(&[3, 2]));
15297 assert_eq!(v1.dtype(), DType::F32);
15298 let g = graph.read().unwrap();
15299 // ViewOwned is a fresh allocation — no explicit layout entry,
15300 // contiguous layout falls through.
15301 assert!(!g.has_explicit_layout(v1.id()));
15302 let owned_node = g.node(v1.id());
15303 assert!(matches!(owned_node.op, Op::ViewOwned { slot: 1 }));
15304 }
15305
15306 // ------------------------------------------------------------------
15307 // Session 2: bundled allocator + FusedOpEntry::output_views +
15308 // View-vs-ViewOwned planner pass. The tests use the bundled
15309 // storage allocator and a synthetic 2-output FusedOp entry — no
15310 // real fused-op author migrates in Session 2; the
15311 // selective-scan-ssd-chunk-multi-output-followup session lights
15312 // up the first real consumer.
15313 // ------------------------------------------------------------------
15314
15315 use fuel_backend_contract::storage::allocate_bundled_storage;
15316 use fuel_ir::storage::OutputViewSpec;
15317
15318 /// `allocate_bundled_storage` allocates one Storage on the device,
15319 /// attaches the bundle, and slot lookups report the spec-derived
15320 /// byte_offsets.
15321 #[test]
15322 fn allocate_bundled_storage_two_slot_roundtrip() {
15323 let dev = cpu_dev();
15324 let specs = vec![
15325 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15326 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15327 ];
15328 let s =
15329 allocate_bundled_storage(dev.as_ref(), &specs).expect("two-slot F32 alloc succeeds");
15330 assert!(s.is_bundled());
15331 assert_eq!(s.slot_count(), 2);
15332 assert_eq!(s.primary_dtype(), DType::F32);
15333 let v0 = s.slot_view(0).unwrap();
15334 let v1 = s.slot_view(1).unwrap();
15335 assert_eq!(v0.byte_offset, 0);
15336 assert_eq!(v0.shape, Shape::from_dims(&[2, 3]));
15337 assert_eq!(v1.byte_offset, 24);
15338 assert_eq!(v1.shape, Shape::from_dims(&[2, 4]));
15339 }
15340
15341 /// `allocate_bundled_storage` handles mixed F32 + F64 slots — slot
15342 /// 0 is primary (F32), slot 1's bytes are aligned to its F64
15343 /// boundary, and the underlying allocation has enough flat F32
15344 /// elements to cover the total bundle bytes.
15345 #[test]
15346 fn allocate_bundled_storage_mixed_dtype() {
15347 let dev = cpu_dev();
15348 let specs = vec![
15349 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[6])),
15350 OutputViewSpec::contiguous(DType::F64, Shape::from_dims(&[3])),
15351 ];
15352 let s = allocate_bundled_storage(dev.as_ref(), &specs).expect("mixed-dtype alloc succeeds");
15353 assert_eq!(s.primary_dtype(), DType::F32);
15354 let v0 = s.slot_view(0).unwrap();
15355 let v1 = s.slot_view(1).unwrap();
15356 assert_eq!(v0.dtype, DType::F32);
15357 assert_eq!(v1.dtype, DType::F64);
15358 assert_eq!(v0.byte_offset, 0);
15359 // F32[6] = 24 bytes; 24 is already multiple of 8, so v1
15360 // starts at 24 without further padding.
15361 assert_eq!(v1.byte_offset, 24);
15362 }
15363
15364 /// `allocate_bundled_storage` propagates compose_bundle errors —
15365 /// an empty spec list errors out before touching the device.
15366 #[test]
15367 fn allocate_bundled_storage_rejects_empty() {
15368 let dev = cpu_dev();
15369 let err = allocate_bundled_storage(dev.as_ref(), &[]).expect_err("empty specs error");
15370 assert!(format!("{err}").contains("non-empty"));
15371 }
15372
15373 /// The two SelectiveScan / SsdChunkScan migrations from item 3
15374 /// (2026-06-01) are the first `default_registry` entries to
15375 /// declare `output_views`. Any new multi-output op author should
15376 /// extend the expected set here.
15377 #[test]
15378 fn default_registry_multi_output_entries() {
15379 let reg = crate::registry::default_registry();
15380 let mut multi_out_names: Vec<&'static str> = reg
15381 .entries_iter()
15382 .filter(|e| e.output_views.is_some())
15383 .map(|e| e.name)
15384 .collect();
15385 multi_out_names.sort();
15386 assert_eq!(
15387 multi_out_names,
15388 vec!["SelectiveScan", "SsdChunkScan"],
15389 "the multi-output registry set should match the item-3 \
15390 migrations (SelectiveScan + SsdChunkScan); add new \
15391 multi-output ops to this list as they migrate",
15392 );
15393 }
15394
15395 /// Authoring-contract invariant: for every multi-output entry in
15396 /// the process-wide registry, `shape_rule(inputs)` MUST equal
15397 /// `output_views(inputs)[0].shape` and `dtype_rule(inputs)` MUST
15398 /// equal `output_views(inputs)[0].dtype`. Slot 0 is the primary
15399 /// and the bundled-allocation contract assumes the producer's
15400 /// `Node.shape`/`Node.dtype` reflect it.
15401 #[test]
15402 fn multi_output_entries_slot_0_matches_primary_rules() {
15403 use crate::registry::FusedOpParams;
15404 let reg = crate::registry::default_registry();
15405
15406 // Each multi-output entry needs a representative input batch
15407 // (shapes + dtypes + params) that satisfies its
15408 // shape_rule/dtype_rule preconditions. The check below runs
15409 // once per entry using these fixtures.
15410 struct Fixture {
15411 shapes: Vec<Shape>,
15412 dtypes: Vec<DType>,
15413 params: FusedOpParams,
15414 }
15415 fn selective_scan_fixture() -> Fixture {
15416 Fixture {
15417 shapes: vec![
15418 Shape::from_dims(&[2, 4, 8]), // u: [batch, seqlen, dim]
15419 Shape::from_dims(&[2, 4, 8]), // delta: same
15420 Shape::from_dims(&[8, 16]), // a: [dim, dstate]
15421 Shape::from_dims(&[2, 4, 16]), // b: [batch, seqlen, dstate]
15422 Shape::from_dims(&[2, 4, 16]), // c: same
15423 ],
15424 dtypes: vec![DType::F32; 5],
15425 params: FusedOpParams::SelectiveScan {
15426 delta_softplus: false,
15427 },
15428 }
15429 }
15430 fn ssd_chunk_scan_fixture() -> Fixture {
15431 Fixture {
15432 shapes: vec![
15433 Shape::from_dims(&[2, 4, 3, 8]), // x: [batch, seqlen, heads, head_dim]
15434 Shape::from_dims(&[2, 4, 3]), // dt: [batch, seqlen, heads]
15435 Shape::from_dims(&[3]), // a: [heads]
15436 Shape::from_dims(&[2, 4, 3, 16]), // b: [batch, seqlen, heads, state_dim]
15437 Shape::from_dims(&[2, 4, 3, 16]), // c: same
15438 ],
15439 dtypes: vec![DType::F32; 5],
15440 params: FusedOpParams::SsdChunkScan { chunk_size: 4 },
15441 }
15442 }
15443
15444 for entry in reg.entries_iter().filter(|e| e.output_views.is_some()) {
15445 let fx = match entry.name {
15446 "SelectiveScan" => selective_scan_fixture(),
15447 "SsdChunkScan" => ssd_chunk_scan_fixture(),
15448 other => panic!(
15449 "multi_output_entries_slot_0_matches_primary_rules: \
15450 no fixture for new multi-output entry {other:?}. \
15451 Add one to this test as you register a new op.",
15452 ),
15453 };
15454 let primary_shape = (entry.shape_rule)(&fx.shapes, &fx.params);
15455 let primary_dtype = (entry.dtype_rule)(&fx.dtypes, &fx.params);
15456 let specs = entry.output_views.unwrap()(&fx.shapes, &fx.dtypes, &fx.params);
15457 assert!(
15458 !specs.is_empty(),
15459 "{}: output_views returned empty Vec (multi-output ops \
15460 must have ≥ 1 slot)",
15461 entry.name,
15462 );
15463 assert_eq!(
15464 specs[0].shape, primary_shape,
15465 "{}: output_views[0].shape {:?} must equal shape_rule \
15466 {:?} (slot 0 is the primary; Node::shape reflects it)",
15467 entry.name, specs[0].shape, primary_shape,
15468 );
15469 assert_eq!(
15470 specs[0].dtype, primary_dtype,
15471 "{}: output_views[0].dtype {:?} must equal dtype_rule \
15472 {:?} (slot 0 is the primary; Node::dtype reflects it)",
15473 entry.name, specs[0].dtype, primary_dtype,
15474 );
15475 // Layout-shape coherence: each slot's layout shape must
15476 // equal its declared shape (the same invariant
15477 // set_output_views enforces at graph-build time).
15478 for (i, spec) in specs.iter().enumerate() {
15479 assert_eq!(
15480 spec.layout.shape(),
15481 &spec.shape,
15482 "{}: slot {i} layout.shape() {:?} disagrees with \
15483 declared spec.shape {:?}",
15484 entry.name,
15485 spec.layout.shape(),
15486 spec.shape,
15487 );
15488 }
15489 }
15490 }
15491
15492 /// Build a synthetic multi-output `FusedOpEntry` to exercise the
15493 /// authoring contract end-to-end without polluting the production
15494 /// registry. The output_views fn returns a 2-slot spec list whose
15495 /// slot 0 matches shape_rule / dtype_rule (the primary).
15496 fn synthetic_two_output_entry() -> crate::registry::FusedOpEntry {
15497 fn shape(_: &[Shape], _: &crate::registry::FusedOpParams) -> Shape {
15498 Shape::from_dims(&[2, 3])
15499 }
15500 fn dtype(_: &[DType], _: &crate::registry::FusedOpParams) -> DType {
15501 DType::F32
15502 }
15503 fn ovs(
15504 _: &[Shape],
15505 _: &[DType],
15506 _: &crate::registry::FusedOpParams,
15507 ) -> Vec<OutputViewSpec> {
15508 vec![
15509 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15510 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15511 ]
15512 }
15513 crate::registry::FusedOpEntry {
15514 destructive_input: None,
15515 id: crate::registry::FusedOps::SOFTMAX_LAST_DIM, // any id; not registered
15516 name: "<synthetic-2-output>",
15517 family: crate::registry::FusedOpFamily::Forward,
15518 pattern: crate::registry::SubgraphPattern::Callable(|_g, _id| None),
15519 decompose: |_g, id, _p| id,
15520 backward: crate::registry::BackwardKind::NotDifferentiable,
15521 shape_rule: shape,
15522 dtype_rule: dtype,
15523 output_views: Some(ovs),
15524 }
15525 }
15526
15527 /// The synthetic entry's `output_views` matches the
15528 /// `shape_rule`/`dtype_rule` contract on slot 0.
15529 #[test]
15530 fn synthetic_entry_output_views_matches_primary_contract() {
15531 let entry = synthetic_two_output_entry();
15532 let ovs_fn = entry.output_views.expect("synthetic entry is multi-output");
15533 let specs = ovs_fn(&[], &[], &crate::registry::FusedOpParams::SoftmaxLastDim);
15534 assert_eq!(specs.len(), 2);
15535 assert_eq!(
15536 specs[0].dtype,
15537 (entry.dtype_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15538 );
15539 assert_eq!(
15540 specs[0].shape,
15541 (entry.shape_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15542 );
15543 }
15544
15545 /// Build a producer Const node and declare it multi-output via
15546 /// `Graph::set_output_views`. Returns the producer's NodeId and a
15547 /// SharedGraph handle.
15548 fn multi_output_producer(slots: Vec<OutputView>) -> (SharedGraph, NodeId) {
15549 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15550 let id = {
15551 let mut g = graph.write().unwrap();
15552 let id = g.push(Node {
15553 op: Op::Const,
15554 inputs: vec![],
15555 shape: slots[0].shape.clone(),
15556 dtype: slots[0].dtype,
15557 });
15558 g.set_output_views(id, slots.into())
15559 .expect("valid synthetic specs");
15560 id
15561 };
15562 (graph, id)
15563 }
15564
15565 /// Two slots, both consumed at the same topo depth → planner does
15566 /// nothing (symmetric lifetimes, bundle drops naturally).
15567 #[test]
15568 fn promote_views_symmetric_lifetimes_is_noop() {
15569 let slot_specs = vec![
15570 OutputView {
15571 byte_offset: 0,
15572 len_elements: 6,
15573 dtype: DType::F32,
15574 shape: Shape::from_dims(&[2, 3]),
15575 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15576 name: Some("y"),
15577 },
15578 OutputView {
15579 byte_offset: 24,
15580 len_elements: 8,
15581 dtype: DType::F32,
15582 shape: Shape::from_dims(&[2, 4]),
15583 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15584 name: Some("state"),
15585 },
15586 ];
15587 let (graph, producer_id) = multi_output_producer(slot_specs);
15588 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15589 // Each slot has exactly one View, consumed at the same depth
15590 // (a no-op Relu downstream of each).
15591 let v0 = producer.view(0).expect("slot 0 view");
15592 let v1 = producer.view(1).expect("slot 1 view");
15593 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15594 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15595 let roots = {
15596 let mut g = graph.write().unwrap();
15597 let r0 = g.push(Node {
15598 op: Op::Relu,
15599 inputs: vec![v0_id],
15600 shape: v0_shape,
15601 dtype: v0_dtype,
15602 });
15603 let r1 = g.push(Node {
15604 op: Op::Relu,
15605 inputs: vec![v1_id],
15606 shape: v1_shape,
15607 dtype: v1_dtype,
15608 });
15609 vec![r0, r1]
15610 };
15611 let promotions = {
15612 let mut g = graph.write().unwrap();
15613 crate::opt::promote_views_for_liveness(&mut g, &roots)
15614 };
15615 assert_eq!(
15616 promotions, 0,
15617 "symmetric lifetimes shouldn't promote anything"
15618 );
15619 }
15620
15621 /// Asymmetric lifetimes: slot 0 consumed early, slot 1 consumed
15622 /// late → planner promotes slot 1's View to ViewOwned.
15623 #[test]
15624 fn promote_views_asymmetric_promotes_long_lived_slot() {
15625 let slot_specs = vec![
15626 OutputView {
15627 byte_offset: 0,
15628 len_elements: 6,
15629 dtype: DType::F32,
15630 shape: Shape::from_dims(&[2, 3]),
15631 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15632 name: Some("y"),
15633 },
15634 OutputView {
15635 byte_offset: 24,
15636 len_elements: 6,
15637 dtype: DType::F32,
15638 shape: Shape::from_dims(&[2, 3]),
15639 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15640 name: Some("state"),
15641 },
15642 ];
15643 let (graph, producer_id) = multi_output_producer(slot_specs);
15644 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15645 let v_y = producer.view(0).expect("slot 0 view");
15646 let v_state = producer.view(1).expect("slot 1 view");
15647 // Slot 0 ("y") consumed at depth 1 (single Relu).
15648 // Slot 1 ("state") consumed at a much deeper chain — Relu →
15649 // Relu → Relu. Topo positions push state's last-use later
15650 // than y's, triggering promotion of state's View.
15651 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15652 let (v_state_id, v_state_shape, v_state_dtype) =
15653 (v_state.id(), v_state.shape(), v_state.dtype());
15654 let roots = {
15655 let mut g = graph.write().unwrap();
15656 let y_relu = g.push(Node {
15657 op: Op::Relu,
15658 inputs: vec![v_y_id],
15659 shape: v_y_shape,
15660 dtype: v_y_dtype,
15661 });
15662 let s1 = g.push(Node {
15663 op: Op::Relu,
15664 inputs: vec![v_state_id],
15665 shape: v_state_shape.clone(),
15666 dtype: v_state_dtype,
15667 });
15668 let s2 = g.push(Node {
15669 op: Op::Relu,
15670 inputs: vec![s1],
15671 shape: v_state_shape.clone(),
15672 dtype: v_state_dtype,
15673 });
15674 let s3 = g.push(Node {
15675 op: Op::Relu,
15676 inputs: vec![s2],
15677 shape: v_state_shape,
15678 dtype: v_state_dtype,
15679 });
15680 vec![y_relu, s3]
15681 };
15682 let promotions = {
15683 let mut g = graph.write().unwrap();
15684 crate::opt::promote_views_for_liveness(&mut g, &roots)
15685 };
15686 assert_eq!(
15687 promotions, 1,
15688 "exactly the long-lived slot 1 View should promote"
15689 );
15690 // Slot 1's consumer (the first Relu in the long chain) now
15691 // reads a fresh Op::ViewOwned node, not the old Op::View.
15692 let g = graph.read().unwrap();
15693 // Find the new ViewOwned node — it was pushed AFTER the
15694 // existing nodes, so it's the last node in the arena. Its op
15695 // must be Op::ViewOwned { slot: 1 } and its input must be the
15696 // producer.
15697 let last_id = NodeId(g.len() - 1);
15698 let last_node = g.node(last_id);
15699 assert!(matches!(last_node.op, Op::ViewOwned { slot: 1 }));
15700 assert_eq!(last_node.inputs, vec![producer_id]);
15701 // The slot 0 View is untouched — still Op::View.
15702 let v_y_node = g.node(v_y_id);
15703 assert!(matches!(v_y_node.op, Op::View { slot: 0 }));
15704 // The old slot 1 View stays in the arena (orphaned). No
15705 // consumer points at it anymore.
15706 let v_state_node = g.node(v_state_id);
15707 assert!(matches!(v_state_node.op, Op::View { slot: 1 }));
15708 }
15709
15710 /// Running the pass twice on the same graph promotes nothing on
15711 /// the second call — `Op::ViewOwned` is a fixpoint (skipped by
15712 /// the planner because `is_owned` is true).
15713 #[test]
15714 fn promote_views_idempotent() {
15715 let slot_specs = vec![
15716 OutputView {
15717 byte_offset: 0,
15718 len_elements: 4,
15719 dtype: DType::F32,
15720 shape: Shape::from_dims(&[2, 2]),
15721 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15722 name: None,
15723 },
15724 OutputView {
15725 byte_offset: 16,
15726 len_elements: 4,
15727 dtype: DType::F32,
15728 shape: Shape::from_dims(&[2, 2]),
15729 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15730 name: None,
15731 },
15732 ];
15733 let (graph, producer_id) = multi_output_producer(slot_specs);
15734 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15735 let v_y = producer.view(0).expect("slot 0 view");
15736 let v_state = producer.view(1).expect("slot 1 view");
15737 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15738 let (v_state_id, v_state_shape, v_state_dtype) =
15739 (v_state.id(), v_state.shape(), v_state.dtype());
15740 let roots = {
15741 let mut g = graph.write().unwrap();
15742 let y_r = g.push(Node {
15743 op: Op::Relu,
15744 inputs: vec![v_y_id],
15745 shape: v_y_shape,
15746 dtype: v_y_dtype,
15747 });
15748 let s1 = g.push(Node {
15749 op: Op::Relu,
15750 inputs: vec![v_state_id],
15751 shape: v_state_shape.clone(),
15752 dtype: v_state_dtype,
15753 });
15754 let s2 = g.push(Node {
15755 op: Op::Relu,
15756 inputs: vec![s1],
15757 shape: v_state_shape,
15758 dtype: v_state_dtype,
15759 });
15760 vec![y_r, s2]
15761 };
15762 let first = {
15763 let mut g = graph.write().unwrap();
15764 crate::opt::promote_views_for_liveness(&mut g, &roots)
15765 };
15766 let second = {
15767 let mut g = graph.write().unwrap();
15768 crate::opt::promote_views_for_liveness(&mut g, &roots)
15769 };
15770 assert_eq!(first, 1, "first call promotes the long-lived slot");
15771 assert_eq!(
15772 second, 0,
15773 "second call is idempotent — no further promotions"
15774 );
15775 }
15776
15777 /// Graph with no multi-output producers: pass returns 0 and
15778 /// touches nothing.
15779 #[test]
15780 fn promote_views_noop_on_graph_without_multi_output() {
15781 let mut g = Graph::new();
15782 let a = g.push(Node {
15783 op: Op::Const,
15784 inputs: vec![],
15785 shape: Shape::from_dims(&[2, 3]),
15786 dtype: DType::F32,
15787 });
15788 let r = g.push(Node {
15789 op: Op::Relu,
15790 inputs: vec![a],
15791 shape: Shape::from_dims(&[2, 3]),
15792 dtype: DType::F32,
15793 });
15794 let n_before = g.len();
15795 let promotions = crate::opt::promote_views_for_liveness(&mut g, &[r]);
15796 assert_eq!(promotions, 0);
15797 assert_eq!(g.len(), n_before, "no node should have been added");
15798 }
15799
15800 // ------------------------------------------------------------------
15801 // Session 3: scheduler / destructive-cleanup integration —
15802 // bundle-aware liveness. A destructive op on a multi-output
15803 // producer (or any of its Views) must run after every reader of
15804 // every other View, because all Views share the bundle's storage
15805 // Arc. Op::ViewOwned is excluded — it forks a fresh standalone
15806 // Storage at execute time.
15807 // ------------------------------------------------------------------
15808
15809 /// Helper: build two contiguous slot specs for a producer of
15810 /// `Node::shape = [2, 3] F32`. Slot 0 is the primary (matches the
15811 /// producer's Node::shape/dtype, required by set_output_views);
15812 /// slot 1 carries a sibling shape that doesn't collide with the
15813 /// primary.
15814 fn two_slot_views_2x3_and_2x4() -> Vec<OutputView> {
15815 vec![
15816 OutputView {
15817 byte_offset: 0,
15818 len_elements: 6,
15819 dtype: DType::F32,
15820 shape: Shape::from_dims(&[2, 3]),
15821 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15822 name: Some("y"),
15823 },
15824 OutputView {
15825 byte_offset: 24,
15826 len_elements: 8,
15827 dtype: DType::F32,
15828 shape: Shape::from_dims(&[2, 4]),
15829 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15830 name: Some("state"),
15831 },
15832 ]
15833 }
15834
15835 /// Op::Release targeting a multi-output producer pins after every
15836 /// consumer of any View of that producer. Without bundle-aware
15837 /// aliasing the Views' downstream Relu nodes would be missed and
15838 /// could race the Release.
15839 #[test]
15840 fn derive_ordering_release_of_bundled_producer_pins_after_view_consumers() {
15841 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15842 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15843 let v0 = producer.view(0).expect("slot 0 view");
15844 let v1 = producer.view(1).expect("slot 1 view");
15845 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15846 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15847 let (r0, r1, release_id) = {
15848 let mut g = graph.write().unwrap();
15849 let r0 = g.push(Node {
15850 op: Op::Relu,
15851 inputs: vec![v0_id],
15852 shape: v0_shape,
15853 dtype: v0_dtype,
15854 });
15855 let r1 = g.push(Node {
15856 op: Op::Relu,
15857 inputs: vec![v1_id],
15858 shape: v1_shape,
15859 dtype: v1_dtype,
15860 });
15861 let release = g.push(Node {
15862 op: Op::Release,
15863 inputs: vec![producer_id],
15864 shape: Shape::from_dims(&[0]),
15865 dtype: DType::F32,
15866 });
15867 (r0, r1, release)
15868 };
15869 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r0, r1, release_id]);
15870 let deps = ord.deps_of(release_id);
15871 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15872 assert!(
15873 dep_set.contains(&r0),
15874 "Release must run after the slot-0 View's consumer (r0)",
15875 );
15876 assert!(
15877 dep_set.contains(&r1),
15878 "Release must run after the slot-1 View's consumer (r1) — \
15879 both Views share the bundle Arc",
15880 );
15881 }
15882
15883 /// Destructive op targeting one of a bundle's Op::View nodes
15884 /// pins after every sibling View's consumers too — every View
15885 /// of the producer shares the bundle's Arc, so writing through
15886 /// one of them clobbers the bytes the others read.
15887 #[test]
15888 fn derive_ordering_destructive_on_view_pins_sibling_view_consumers() {
15889 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15890 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15891 let v0 = producer.view(0).expect("slot 0 view");
15892 let v1 = producer.view(1).expect("slot 1 view");
15893 let (v0_id, _v0_shape, _v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15894 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15895 // Destructive op (Release) targets v0 directly — its
15896 // alias set must reach v1's consumer via the producer-sibling
15897 // hop in collect_alias_set.
15898 let (r1, release_id) = {
15899 let mut g = graph.write().unwrap();
15900 let r1 = g.push(Node {
15901 op: Op::Relu,
15902 inputs: vec![v1_id],
15903 shape: v1_shape,
15904 dtype: v1_dtype,
15905 });
15906 let release = g.push(Node {
15907 op: Op::Release,
15908 inputs: vec![v0_id],
15909 shape: Shape::from_dims(&[0]),
15910 dtype: DType::F32,
15911 });
15912 (r1, release)
15913 };
15914 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r1, release_id]);
15915 let deps = ord.deps_of(release_id);
15916 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15917 assert!(
15918 dep_set.contains(&r1),
15919 "Release targeting slot-0 View must pin after sibling slot-1 \
15920 View's consumer (r1) — both share the bundle's storage Arc",
15921 );
15922 }
15923
15924 /// Op::ViewOwned does NOT extend the alias set: its forward
15925 /// memcpy produces an independent Storage. derive_ordering must
15926 /// still pin Release after the ViewOwned itself (via the standard
15927 /// data-dependency: ViewOwned consumes the producer), but
15928 /// downstream consumers of the ViewOwned are NOT in the alias
15929 /// set's reader sweep — they read independent bytes and may run
15930 /// freely after the Release.
15931 #[test]
15932 fn derive_ordering_view_owned_is_not_alias_extending() {
15933 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15934 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15935 // Slot 0 → View (shared Arc); slot 1 → ViewOwned (independent).
15936 let v_view = producer.view(0).expect("slot 0 view");
15937 let v_owned = producer.view_owned(1).expect("slot 1 viewowned");
15938 let (v_view_id, _, _) = (v_view.id(), v_view.shape(), v_view.dtype());
15939 let (v_owned_id, v_owned_shape, v_owned_dtype) =
15940 (v_owned.id(), v_owned.shape(), v_owned.dtype());
15941 let (consumer_of_owned, release_id) = {
15942 let mut g = graph.write().unwrap();
15943 let consumer = g.push(Node {
15944 op: Op::Relu,
15945 inputs: vec![v_owned_id],
15946 shape: v_owned_shape,
15947 dtype: v_owned_dtype,
15948 });
15949 let release = g.push(Node {
15950 op: Op::Release,
15951 inputs: vec![producer_id],
15952 shape: Shape::from_dims(&[0]),
15953 dtype: DType::F32,
15954 });
15955 (consumer, release)
15956 };
15957 let ord =
15958 crate::opt::derive_ordering(&graph.read().unwrap(), &[consumer_of_owned, release_id]);
15959 let deps = ord.deps_of(release_id);
15960 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15961 // Release MUST wait for ViewOwned to run (ViewOwned reads
15962 // the producer's bytes during its memcpy).
15963 assert!(
15964 dep_set.contains(&v_owned_id),
15965 "Release must pin after ViewOwned — ViewOwned reads the \
15966 producer's bundle during its memcpy phase",
15967 );
15968 // Release must NOT depend on the ViewOwned's downstream
15969 // consumer — that consumer reads ViewOwned's independent
15970 // bytes, not the producer's bundle.
15971 assert!(
15972 !dep_set.contains(&consumer_of_owned),
15973 "Release must NOT pin after consumers of ViewOwned — \
15974 ViewOwned forks a fresh Storage; its consumers don't \
15975 read the producer's bundle",
15976 );
15977 // Op::View's consumers stay reached via the alias chain; here
15978 // there are none (v_view has no consumer), so v_view itself
15979 // is the only alias-set entry beyond the producer.
15980 let _ = v_view_id;
15981 }
15982
15983 /// Long-tail bundle-aware schedule: a producer with three Views,
15984 /// each consumed by a chain of different depth, and a destructive
15985 /// Release on the producer. The Release must end up after every
15986 /// terminal consumer of every chain — bundle-as-single-eviction-
15987 /// unit semantics fall out of derive_ordering's alias-set walk
15988 /// reaching each chain's leaf via the producer-then-View hop.
15989 #[test]
15990 fn derive_ordering_bundle_release_pins_after_all_chains() {
15991 // Build a 3-slot bundle. Slot 0 primary [2,3] F32 satisfies
15992 // the producer's Node::shape/dtype constraint; slots 1 + 2
15993 // add sibling shapes.
15994 let slot_specs = vec![
15995 OutputView {
15996 byte_offset: 0,
15997 len_elements: 6,
15998 dtype: DType::F32,
15999 shape: Shape::from_dims(&[2, 3]),
16000 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
16001 name: Some("a"),
16002 },
16003 OutputView {
16004 byte_offset: 24,
16005 len_elements: 4,
16006 dtype: DType::F32,
16007 shape: Shape::from_dims(&[2, 2]),
16008 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
16009 name: Some("b"),
16010 },
16011 OutputView {
16012 byte_offset: 40,
16013 len_elements: 8,
16014 dtype: DType::F32,
16015 shape: Shape::from_dims(&[2, 4]),
16016 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
16017 name: Some("c"),
16018 },
16019 ];
16020 let (graph, producer_id) = multi_output_producer(slot_specs);
16021 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16022 let v0 = producer.view(0).unwrap();
16023 let v1 = producer.view(1).unwrap();
16024 let v2 = producer.view(2).unwrap();
16025 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
16026 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
16027 let (v2_id, v2_shape, v2_dtype) = (v2.id(), v2.shape(), v2.dtype());
16028 let (leaf_a, leaf_b, leaf_c, release_id) = {
16029 let mut g = graph.write().unwrap();
16030 let leaf_a = g.push(Node {
16031 op: Op::Relu,
16032 inputs: vec![v0_id],
16033 shape: v0_shape,
16034 dtype: v0_dtype,
16035 });
16036 let b1 = g.push(Node {
16037 op: Op::Relu,
16038 inputs: vec![v1_id],
16039 shape: v1_shape.clone(),
16040 dtype: v1_dtype,
16041 });
16042 let leaf_b = g.push(Node {
16043 op: Op::Relu,
16044 inputs: vec![b1],
16045 shape: v1_shape,
16046 dtype: v1_dtype,
16047 });
16048 let c1 = g.push(Node {
16049 op: Op::Relu,
16050 inputs: vec![v2_id],
16051 shape: v2_shape.clone(),
16052 dtype: v2_dtype,
16053 });
16054 let c2 = g.push(Node {
16055 op: Op::Relu,
16056 inputs: vec![c1],
16057 shape: v2_shape.clone(),
16058 dtype: v2_dtype,
16059 });
16060 let leaf_c = g.push(Node {
16061 op: Op::Relu,
16062 inputs: vec![c2],
16063 shape: v2_shape,
16064 dtype: v2_dtype,
16065 });
16066 let release = g.push(Node {
16067 op: Op::Release,
16068 inputs: vec![producer_id],
16069 shape: Shape::from_dims(&[0]),
16070 dtype: DType::F32,
16071 });
16072 (leaf_a, leaf_b, leaf_c, release)
16073 };
16074 let ord = crate::opt::derive_ordering(
16075 &graph.read().unwrap(),
16076 &[leaf_a, leaf_b, leaf_c, release_id],
16077 );
16078 let deps = ord.deps_of(release_id);
16079 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
16080 // The direct readers of any View are the FIRST relu in each
16081 // chain — those are the nodes that read the bundle's bytes.
16082 // Every consumer further down reads its predecessor's
16083 // standalone output Storage, so they aren't in the alias-set
16084 // reader sweep. Verify the Release pins on the direct
16085 // readers — sufficient for bundle-single-eviction safety
16086 // because the chains are themselves data-dep ordered after
16087 // their direct readers.
16088 assert!(
16089 dep_set.contains(&leaf_a),
16090 "single-Relu chain a: leaf is the direct reader",
16091 );
16092 // For the b/c chains, the direct readers are the first Relus
16093 // (b1 / c1), not the leaves. The Release must include those.
16094 // Find them by walking inputs from leaves.
16095 let g = graph.read().unwrap();
16096 let b1 = g.node(leaf_b).inputs[0];
16097 let (c2, c1) = {
16098 let c2 = g.node(leaf_c).inputs[0];
16099 let c1 = g.node(c2).inputs[0];
16100 (c2, c1)
16101 };
16102 let _ = c2;
16103 assert!(
16104 dep_set.contains(&b1),
16105 "two-Relu chain b: first Relu is the direct bundle reader",
16106 );
16107 assert!(
16108 dep_set.contains(&c1),
16109 "three-Relu chain c: first Relu is the direct bundle reader",
16110 );
16111 }
16112
16113 // ------------------------------------------------------------------
16114 // Item 4 — Op::View / Op::ViewOwned autograd emits Op::ScatterIntoSlot
16115 // ------------------------------------------------------------------
16116
16117 /// The View's backward arm pushes an `Op::ScatterIntoSlot { slot }`
16118 /// node into the gradient graph as the producer's input gradient.
16119 /// Synthetic test: build a 2-slot producer + Op::View(slot 1) +
16120 /// a Relu downstream + invoke NodeHandle::backward + walk the produced
16121 /// gradient graph and assert a ScatterIntoSlot was emitted.
16122 #[test]
16123 fn op_view_backward_emits_scatter_into_slot() {
16124 let producer_t =
16125 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
16126 let graph: SharedGraph = Arc::clone(producer_t.graph());
16127 let producer_id = producer_t.id();
16128 let view_id = {
16129 let mut g = graph.write().unwrap();
16130 let specs = two_slot_views_2x3_and_2x4();
16131 g.set_output_views(producer_id, specs.into())
16132 .expect("output_views");
16133 drop(g);
16134 let v1 = producer_t.view(1).expect("slot 1 view");
16135 v1.id()
16136 };
16137 // Build a tiny tape-tracked loss = sum(relu(v1)).
16138 let v1_tensor = NodeHandle::from_existing(Arc::clone(&graph), view_id);
16139 let relu_t = v1_tensor.relu();
16140 let loss_t = relu_t.sum_all();
16141
16142 // Take backward — exercises the View's backward arm.
16143 let grads = loss_t.backward();
16144
16145 // The producer's input gradient should be reachable via a
16146 // chain that includes an Op::ScatterIntoSlot { slot: 1 } node.
16147 let producer_tensor = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16148 let grad_for_producer = grads
16149 .get(&producer_tensor)
16150 .expect("producer has an accumulated gradient");
16151 let grad_id = grad_for_producer.id();
16152 let g = graph.read().unwrap();
16153 let scatter_present = matches!(g.node(grad_id).op, Op::ScatterIntoSlot { slot: 1 }) || {
16154 // Walk one hop back through `Op::Add` accumulations
16155 // if any.
16156 let n = g.node(grad_id);
16157 n.inputs
16158 .iter()
16159 .any(|inp| matches!(g.node(*inp).op, Op::ScatterIntoSlot { slot: 1 }))
16160 };
16161 assert!(
16162 scatter_present,
16163 "View(slot=1) backward must emit an Op::ScatterIntoSlot {{ slot: 1 }} \
16164 into the gradient graph; got grad node op = {:?}",
16165 g.node(grad_id).op,
16166 );
16167 }
16168
16169 // ----- Op::Branch inert scaffold (Phase A PR-A0 of the
16170 // "plan IS the graph" rebuild) -----
16171
16172 /// Back-compat by construction: a graph with ZERO `Op::Branch`
16173 /// nodes builds with exactly the arena it had before the variant
16174 /// existed. The locked design guarantees "a graph with zero
16175 /// Op::Branch nodes is exactly today's single-route graph" — this
16176 /// test pins that: the same builder calls produce the same node
16177 /// count, the same topo order, and not a single `Op::Branch` node.
16178 /// GAP-003 STEP 1: the panic IS reachable from the public API today.
16179 ///
16180 /// `NodeHandle::from_f32` returns `Self`, so a length/shape mismatch has
16181 /// nowhere to go but `assert_eq!` inside `from_host_buffer_on`. This test
16182 /// PASSES today and is deleted by the fix -- it exists to prove the defect
16183 /// is live from a caller's seat, not merely present in the source.
16184 /// GAP-003: a length/shape mismatch DECLINES instead of panicking.
16185 ///
16186 /// ⚠️ This started life as a `#[should_panic]` probe proving the defect was
16187 /// reachable from the public API. The bulk `.unwrap()` pass then appended
16188 /// `.unwrap()` to it, and it KEPT PASSING -- for the wrong reason: unwrapping
16189 /// an `Err` panics, and the `Err` message contains the expected substring, so
16190 /// the assertion could no longer tell "the API panics" from "I unwrapped a
16191 /// Result". A vacuous green produced by the very edit that fixed the defect.
16192 ///
16193 /// It now asserts the `Err` DIRECTLY, with no `unwrap`, and matches on the
16194 /// LENGTH-MISMATCH message specifically -- not merely on `is_err()`. That
16195 /// distinction is load-bearing: `from_host_buffer_on` has a second failure
16196 /// path (`storage_from_host_buffer_owned_dyn`), so a bare `is_err()` could
16197 /// not tell this decline from that one.
16198 #[test]
16199 fn gap003_from_f32_declines_a_length_mismatch() {
16200 // 2 elements declared as a 3-element shape.
16201 let err = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[3]), cpu_dev())
16202 .expect_err("a length/shape mismatch must DECLINE, not construct");
16203 let msg = err.to_string();
16204 assert!(
16205 msg.contains("does not match shape element count"),
16206 "the decline must name the LENGTH MISMATCH specifically, got: {msg}"
16207 );
16208 assert!(
16209 msg.contains('2') && msg.contains('3'),
16210 "and both operands: {msg}"
16211 );
16212
16213 // CONTROL: a MATCHING length still constructs, so the guard is not
16214 // "this constructor always fails".
16215 assert!(
16216 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).is_ok()
16217 );
16218 }
16219
16220 #[test]
16221 fn zero_branch_graph_builds_unchanged() {
16222 // Build: c = (a + b) * a — the same DAG the topo-order tests
16223 // use, exercised here purely to prove the arena is untouched by
16224 // the new variant.
16225 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
16226 let b = a
16227 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
16228 .unwrap();
16229 let sum = a.add(&b);
16230 let c = sum.mul(&a);
16231
16232 let g = c.graph();
16233 let guard = g.read().unwrap();
16234
16235 // Exactly four nodes (a, b, sum, c) — no implicit Branch
16236 // anywhere.
16237 assert_eq!(
16238 guard.len(),
16239 4,
16240 "zero-Branch graph must have the same node count as before"
16241 );
16242
16243 // Topo order is unchanged and contains zero Branch nodes.
16244 let order = topo_order(&guard, c.id());
16245 assert_eq!(order.len(), 4);
16246 let branch_count = order
16247 .iter()
16248 .filter(|&&id| matches!(guard.node(id).op, Op::Branch { .. }))
16249 .count();
16250 assert_eq!(branch_count, 0, "no builder constructs Op::Branch in PR-A0");
16251
16252 // The ops are exactly the ones the builders emitted (no
16253 // structural rewrite slipped in a merge node).
16254 assert!(matches!(guard.node(a.id()).op, Op::Const));
16255 assert!(matches!(guard.node(b.id()).op, Op::Const));
16256 assert!(matches!(guard.node(sum.id()).op, Op::Add));
16257 assert!(matches!(guard.node(c.id()).op, Op::Mul));
16258 }
16259
16260 /// The variant exists and its infallible accessor behaves: a
16261 /// hand-constructed `Op::Branch` reports `short_name() == "Branch"`,
16262 /// and the multi-path encoding (arms = `inputs`, explicit
16263 /// `reconverge_at`) round-trips through the arena. This is the only
16264 /// place in PR-A0 that constructs the variant — the production
16265 /// builders land in PR-A1.
16266 #[test]
16267 fn branch_variant_exists_and_short_name_works() {
16268 // short_name / the Op::short_name() facade both return the
16269 // stable "Branch" constant.
16270 let reconverge = NodeId(7);
16271 let branch_op = Op::Branch {
16272 reconverge_at: reconverge,
16273 };
16274 assert_eq!(branch_op.short_name(), "Branch");
16275 assert_eq!(op_short_name(&branch_op), "Branch");
16276
16277 // Structural nodes carry no destructive input (matches the
16278 // other structural ops: Const / View / ScatterIntoSlot).
16279 assert_eq!(branch_op.destructive_input(), None);
16280
16281 // Encode a 2-arm merge directly on the arena: two route exits
16282 // as `inputs`, the reconvergence node named explicitly. Prove
16283 // the encoding survives a push + read-back unchanged.
16284 let mut g = Graph::new();
16285 let arm0 = g.push(Node {
16286 op: Op::Const,
16287 inputs: vec![],
16288 shape: Shape::from_dims(&[2]),
16289 dtype: DType::F32,
16290 });
16291 let arm1 = g.push(Node {
16292 op: Op::Const,
16293 inputs: vec![],
16294 shape: Shape::from_dims(&[2]),
16295 dtype: DType::F32,
16296 });
16297 let merged = g.push(Node {
16298 op: Op::Const,
16299 inputs: vec![],
16300 shape: Shape::from_dims(&[2]),
16301 dtype: DType::F32,
16302 });
16303 let branch = g.push(Node {
16304 op: Op::Branch {
16305 reconverge_at: merged,
16306 },
16307 inputs: vec![arm0, arm1],
16308 shape: Shape::from_dims(&[2]),
16309 dtype: DType::F32,
16310 });
16311
16312 let node = g.node(branch);
16313 assert_eq!(node.op.short_name(), "Branch");
16314 // Arms are the node's inputs (each input = one route's exit).
16315 assert_eq!(node.inputs, vec![arm0, arm1]);
16316 // The explicit reconvergence node is carried on the op.
16317 match node.op {
16318 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, merged),
16319 ref other => panic!("expected Op::Branch, got {other:?}"),
16320 }
16321 }
16322
16323 // ----- Op::Branch builders + build-time validation
16324 // (Phase A PR-A1 of the "plan IS the graph" rebuild) -----
16325
16326 /// Hand-build a 2-arm diamond directly on the arena and return the
16327 /// pieces the branch builders will stitch together:
16328 /// `diverge` → {`arm0`, `arm1`} → `reconverge`. The reconverge node
16329 /// already reads arm0 as input 0, which is exactly the runnability
16330 /// invariant the builders must preserve (a finalized-but-unpicked
16331 /// branch still realizes on arm 0). Every node is `[2] f32` so the
16332 /// cast-to-uniform check has agreeing shape/dtype across arms.
16333 fn diamond_2arm() -> (Graph, NodeId, NodeId, NodeId, NodeId) {
16334 let mut g = Graph::new();
16335 let diverge = g.push(Node {
16336 op: Op::Const,
16337 inputs: vec![],
16338 shape: Shape::from_dims(&[2]),
16339 dtype: DType::F32,
16340 });
16341 // arm0 = relu(diverge), arm1 = silu(diverge): two interior nodes,
16342 // each reachable only through its own arm from the diverge point.
16343 let arm0 = g.push(Node {
16344 op: Op::Relu,
16345 inputs: vec![diverge],
16346 shape: Shape::from_dims(&[2]),
16347 dtype: DType::F32,
16348 });
16349 let arm1 = g.push(Node {
16350 op: Op::Silu,
16351 inputs: vec![diverge],
16352 shape: Shape::from_dims(&[2]),
16353 dtype: DType::F32,
16354 });
16355 // reconverge reads arm0 (runnability: arm 0 is always input 0).
16356 let reconverge = g.push(Node {
16357 op: Op::Relu,
16358 inputs: vec![arm0],
16359 shape: Shape::from_dims(&[2]),
16360 dtype: DType::F32,
16361 });
16362 (g, diverge, arm0, arm1, reconverge)
16363 }
16364
16365 /// (a) A 2-arm diamond round-trips through
16366 /// `open_branch`/`add_arm`/`finalize_branches`: it produces exactly
16367 /// one valid `Op::Branch` node whose `inputs` are the arm exits in
16368 /// order and whose `reconverge_at` is the named merge node.
16369 #[test]
16370 fn two_arm_diamond_round_trips_to_branch_node() {
16371 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16372 let before = g.len();
16373
16374 let mut b = g.open_branch(diverge);
16375 b.add_arm(arm0);
16376 b.add_arm(arm1);
16377 let branch = b
16378 .finalize_branches(&mut g, reconverge)
16379 .expect("well-formed 2-arm branch must finalize")
16380 .expect("2 arms survive — not collapsed to a single arm");
16381
16382 // Exactly one node was appended (the Branch); no orphan debris.
16383 assert_eq!(g.len(), before + 1);
16384
16385 let node = g.node(branch);
16386 assert!(matches!(node.op, Op::Branch { .. }));
16387 // Arms are the node's inputs, in add order: arm0 first.
16388 assert_eq!(node.inputs, vec![arm0, arm1]);
16389 match node.op {
16390 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, reconverge),
16391 ref other => panic!("expected Op::Branch, got {other:?}"),
16392 }
16393 // The merge node still carries arm0's shape/dtype (cast-to-uniform
16394 // validated, not rewritten).
16395 assert_eq!(node.shape, g.node(arm0).shape);
16396 assert_eq!(node.dtype, g.node(arm0).dtype);
16397 }
16398
16399 /// (b) A `reconverge_at` that is NOT a descendant of the diverge
16400 /// point returns `Error::InvalidBranch` — never a panic.
16401 #[test]
16402 fn reconverge_not_descendant_of_diverge_is_typed_err() {
16403 let (mut g, diverge, arm0, arm1, _reconverge) = diamond_2arm();
16404 // A sibling node that does NOT descend from `diverge`.
16405 let unrelated = g.push(Node {
16406 op: Op::Const,
16407 inputs: vec![],
16408 shape: Shape::from_dims(&[2]),
16409 dtype: DType::F32,
16410 });
16411
16412 let mut b = g.open_branch(diverge);
16413 b.add_arm(arm0);
16414 b.add_arm(arm1);
16415 let err = b
16416 .finalize_branches(&mut g, unrelated)
16417 .expect_err("reconverge that doesn't descend from diverge must be rejected");
16418 assert!(
16419 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16420 "expected InvalidBranch, got {err:?}",
16421 );
16422 }
16423
16424 /// (c) A non-disjoint arm — an arm interior node reachable from
16425 /// outside that arm (shared with the rest of the graph) — returns
16426 /// `Error::InvalidBranch`.
16427 #[test]
16428 fn non_disjoint_arm_is_typed_err() {
16429 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16430 // Add a reader OUTSIDE the branch that consumes arm0's interior.
16431 // arm0 is now reachable from a node that isn't part of the merge,
16432 // so the arm is not internally disjoint.
16433 let _external_reader = g.push(Node {
16434 op: Op::Relu,
16435 inputs: vec![arm0],
16436 shape: Shape::from_dims(&[2]),
16437 dtype: DType::F32,
16438 });
16439
16440 let mut b = g.open_branch(diverge);
16441 b.add_arm(arm0);
16442 b.add_arm(arm1);
16443 let err = b
16444 .finalize_branches(&mut g, reconverge)
16445 .expect_err("an arm interior read from outside the branch must be rejected");
16446 assert!(
16447 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16448 "expected InvalidBranch, got {err:?}",
16449 );
16450 }
16451
16452 /// (c') Arms that disagree on shape/dtype at their exits violate
16453 /// cast-to-uniform and return `Error::InvalidBranch` (validate-and-Err
16454 /// — no implicit Cast insertion in PR-A1).
16455 #[test]
16456 fn arms_disagreeing_on_dtype_is_typed_err() {
16457 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16458 // A second arm with a DIFFERENT dtype than arm0.
16459 let arm1_f16 = g.push(Node {
16460 op: Op::Silu,
16461 inputs: vec![diverge],
16462 shape: Shape::from_dims(&[2]),
16463 dtype: DType::F16,
16464 });
16465
16466 let mut b = g.open_branch(diverge);
16467 b.add_arm(arm0);
16468 b.add_arm(arm1_f16);
16469 let err = b
16470 .finalize_branches(&mut g, reconverge)
16471 .expect_err("arms with mismatched dtype must be rejected (cast-to-uniform)");
16472 assert!(
16473 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16474 "expected InvalidBranch, got {err:?}",
16475 );
16476 }
16477
16478 /// (d) `finalize_branches` drops a single-arm branch: with only one
16479 /// surviving arm there is no real decision point, so no `Op::Branch`
16480 /// node is emitted (`Ok(None)`), the arena is left untouched, and the
16481 /// graph collapses back to that arm.
16482 #[test]
16483 fn single_arm_branch_is_dropped() {
16484 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16485 let before = g.len();
16486
16487 let mut b = g.open_branch(diverge);
16488 b.add_arm(arm0);
16489 let result = b
16490 .finalize_branches(&mut g, reconverge)
16491 .expect("a single-arm branch is valid — it just collapses");
16492 assert!(
16493 result.is_none(),
16494 "single-arm branch must NOT emit an Op::Branch"
16495 );
16496 // No node appended: the lone arm is the graph, unchanged.
16497 assert_eq!(
16498 g.len(),
16499 before,
16500 "dropping a single-arm branch leaves the arena untouched"
16501 );
16502 let branch_count = (0..g.len())
16503 .filter(|&i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }))
16504 .count();
16505 assert_eq!(branch_count, 0);
16506 }
16507
16508 /// (e) The runnability invariant: the emitted `Op::Branch`'s inputs
16509 /// always include arm-0's exit as input 0, so a finalized-but-not-yet-
16510 /// route-picked graph still realizes on arm 0 (a graph with a
16511 /// finalized branch must still be executable). The named reconverge
16512 /// node reads arm-0's exit, so realizing on arm 0 alone produces a
16513 /// defined value at the merge.
16514 #[test]
16515 fn finalized_branch_preserves_arm0_runnability() {
16516 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16517
16518 let mut b = g.open_branch(diverge);
16519 b.add_arm(arm0);
16520 b.add_arm(arm1);
16521 let branch = b
16522 .finalize_branches(&mut g, reconverge)
16523 .expect("well-formed branch finalizes")
16524 .expect("2 arms survive");
16525
16526 // arm 0 is input 0 of the Branch — the always-realizable route.
16527 assert_eq!(g.node(branch).inputs.first().copied(), Some(arm0));
16528 // And the named reconverge node reads arm0, so realizing on
16529 // arm 0 alone produces a defined value at the merge.
16530 assert!(
16531 g.node(reconverge).inputs.contains(&arm0),
16532 "reconverge must read arm-0's exit so the unpicked graph runs on arm 0",
16533 );
16534 }
16535
16536 // ===================================================================
16537 // PR-B4: required compaction of the append-only arena.
16538 // ===================================================================
16539
16540 use crate::run::{extract_runs, lower_runs_arm0};
16541
16542 /// Build the same 2-arm diamond the run.rs tests use, finalized into a
16543 /// real `Op::Branch`. Returns `(g, diverge, arm0, arm1, reconverge,
16544 /// branch, post)`. `post` reads `reconverge`, so the post-merge region
16545 /// is a non-empty run and `post` is a stable root.
16546 fn diamond_with_branch_b4() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
16547 let mk = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
16548 g.push(Node {
16549 op,
16550 inputs,
16551 shape: Shape::from_dims(&[2]),
16552 dtype: DType::F32,
16553 })
16554 };
16555 let mut g = Graph::new();
16556 let pre = mk(&mut g, Op::Const, vec![]);
16557 let diverge = mk(&mut g, Op::Relu, vec![pre]);
16558 let arm0 = mk(&mut g, Op::Silu, vec![diverge]);
16559 let arm1 = mk(&mut g, Op::GeluTanh, vec![diverge]);
16560 let reconverge = mk(&mut g, Op::Relu, vec![arm0]);
16561 let mut b = g.open_branch(diverge);
16562 b.add_arm(arm0);
16563 b.add_arm(arm1);
16564 let branch = b
16565 .finalize_branches(&mut g, reconverge)
16566 .expect("well-formed 2-arm branch finalizes")
16567 .expect("2 arms survive");
16568 let post = mk(&mut g, Op::Tanh, vec![reconverge]);
16569 (g, diverge, arm0, arm1, reconverge, branch, post)
16570 }
16571
16572 /// PR-D1 storage-class substrate: the op-inferred class is correct
16573 /// (`Op::Const` → Shared, `Op::WriteSlice` → SessionState, other →
16574 /// Transient), an explicit override beats the inferred default (a
16575 /// KV-cache placeholder `Op::Const` marked SessionState), and `compact`
16576 /// carries the override to the node's new id while inferred defaults
16577 /// still hold. Born-red: fails if classification, override precedence,
16578 /// or the compaction remap is wrong.
16579 #[test]
16580 fn storage_class_inference_override_and_compaction() {
16581 let mut g = Graph::new();
16582 // A shared weight Const, a session-state KV placeholder Const, a
16583 // transient activation, and an in-place cache-write target.
16584 let weight = g.push(Node {
16585 op: Op::Const,
16586 inputs: vec![],
16587 shape: Shape::from_dims(&[2]),
16588 dtype: DType::F32,
16589 });
16590 let kv = g.push(Node {
16591 op: Op::Const,
16592 inputs: vec![],
16593 shape: Shape::from_dims(&[2]),
16594 dtype: DType::F32,
16595 });
16596 let act = g.push(Node {
16597 op: Op::Relu,
16598 inputs: vec![weight],
16599 shape: Shape::from_dims(&[2]),
16600 dtype: DType::F32,
16601 });
16602 let write = g.push(Node {
16603 op: Op::WriteSlice {
16604 ranges: vec![(0, 2)],
16605 dyn_offset: None,
16606 },
16607 inputs: vec![kv, act],
16608 shape: Shape::from_dims(&[2]),
16609 dtype: DType::F32,
16610 });
16611
16612 // Op-inferred defaults.
16613 assert_eq!(
16614 g.storage_class(weight),
16615 StorageClass::Shared,
16616 "Const → Shared"
16617 );
16618 assert_eq!(
16619 g.storage_class(act),
16620 StorageClass::Transient,
16621 "activation → Transient"
16622 );
16623 assert_eq!(
16624 g.storage_class(write),
16625 StorageClass::SessionState,
16626 "WriteSlice → SessionState"
16627 );
16628 // No overrides set yet.
16629 assert_eq!(
16630 g.storage_class(kv),
16631 StorageClass::Shared,
16632 "KV placeholder Const infers Shared before override"
16633 );
16634 assert!(!g.has_storage_class_override(kv));
16635 assert_eq!(g.storage_class_override_count(), 0);
16636
16637 // Explicit override: the KV placeholder is session state, not a
16638 // shared weight.
16639 g.set_storage_class(kv, StorageClass::SessionState);
16640 assert_eq!(
16641 g.storage_class(kv),
16642 StorageClass::SessionState,
16643 "override beats inferred default"
16644 );
16645 assert!(g.has_storage_class_override(kv));
16646 assert_eq!(g.storage_class_override_count(), 1);
16647
16648 // Compaction carries the override to the new id; inferred defaults
16649 // (no side-table entry) still resolve from the op.
16650 let remap = compact(&mut g, &[write]);
16651 let n_kv = remap.get(kv).expect("kv survives (input of write)");
16652 let n_weight = remap
16653 .get(weight)
16654 .expect("weight survives (transitively under act)");
16655 let n_write = remap.get(write).expect("write is the root");
16656 assert_eq!(
16657 g.storage_class(n_kv),
16658 StorageClass::SessionState,
16659 "override remapped by compact"
16660 );
16661 assert!(g.has_storage_class_override(n_kv));
16662 assert_eq!(
16663 g.storage_class_override_count(),
16664 1,
16665 "exactly the one override survives"
16666 );
16667 assert_eq!(
16668 g.storage_class(n_weight),
16669 StorageClass::Shared,
16670 "inferred Shared still holds post-compact"
16671 );
16672 assert_eq!(
16673 g.storage_class(n_write),
16674 StorageClass::SessionState,
16675 "inferred SessionState still holds post-compact"
16676 );
16677 assert!(g.verify_no_dangling().is_ok());
16678 }
16679
16680 /// (a) A deliberately-orphaned node (pushed, referenced by nothing) is
16681 /// dropped by `compact`; the node count shrinks by exactly the orphan
16682 /// count, and every still-reachable node survives.
16683 #[test]
16684 fn compact_drops_orphan_debris() {
16685 let mut g = Graph::new();
16686 let a = g.push(Node {
16687 op: Op::Const,
16688 inputs: vec![],
16689 shape: Shape::from_dims(&[2]),
16690 dtype: DType::F32,
16691 });
16692 let b = g.push(Node {
16693 op: Op::Relu,
16694 inputs: vec![a],
16695 shape: Shape::from_dims(&[2]),
16696 dtype: DType::F32,
16697 });
16698 let c = g.push(Node {
16699 op: Op::Silu,
16700 inputs: vec![b],
16701 shape: Shape::from_dims(&[2]),
16702 dtype: DType::F32,
16703 });
16704 // Two pieces of exploration debris: reachable from nothing in the
16705 // live structure (no root, no side-effect, no branch references them).
16706 let _orphan0 = g.push(Node {
16707 op: Op::Const,
16708 inputs: vec![],
16709 shape: Shape::from_dims(&[2]),
16710 dtype: DType::F32,
16711 });
16712 let _orphan1 = g.push(Node {
16713 op: Op::Tanh,
16714 inputs: vec![_orphan0],
16715 shape: Shape::from_dims(&[2]),
16716 dtype: DType::F32,
16717 });
16718
16719 let before = g.len();
16720 let remap = compact(&mut g, &[c]);
16721
16722 assert_eq!(
16723 g.len(),
16724 before - 2,
16725 "compaction drops exactly the two orphan-debris nodes",
16726 );
16727 // The three reachable nodes all survived (have new ids).
16728 assert!(remap.get(a).is_some());
16729 assert!(remap.get(b).is_some());
16730 assert!(remap.get(c).is_some());
16731 // The orphans are gone.
16732 assert!(remap.get(_orphan0).is_none());
16733 assert!(remap.get(_orphan1).is_none());
16734 // The surviving chain still resolves: c' reads b' reads a'.
16735 let (na, nb, nc) = (
16736 remap.get(a).unwrap(),
16737 remap.get(b).unwrap(),
16738 remap.get(c).unwrap(),
16739 );
16740 assert_eq!(g.node(nc).inputs, vec![nb]);
16741 assert_eq!(g.node(nb).inputs, vec![na]);
16742 assert_eq!(g.node(na).inputs, Vec::<NodeId>::new());
16743 assert_no_dangling(&g);
16744 }
16745
16746 /// (b) Branches preserved: a graph with a finalized `Op::Branch` keeps
16747 /// every arm + `reconverge_at` after compaction (remapped), and the
16748 /// arm-0 lowering yields the same logical route.
16749 #[test]
16750 fn compact_preserves_branch_arms_and_reconverge() {
16751 let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch_b4();
16752
16753 // Inject orphan debris so compaction has something to drop and the
16754 // surviving-branch claim is non-trivial.
16755 let _debris = g.push(Node {
16756 op: Op::Const,
16757 inputs: vec![],
16758 shape: Shape::from_dims(&[2]),
16759 dtype: DType::F32,
16760 });
16761
16762 // Baseline arm-0 route over old ids, mapped to the op sequence.
16763 let before_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16764 .iter()
16765 .map(|&id| g.node(id).op.short_name())
16766 .collect();
16767
16768 let remap = compact(&mut g, &[post]);
16769
16770 // Every branch participant survived.
16771 let narm0 = remap.get(arm0).expect("arm0 survives");
16772 let narm1 = remap
16773 .get(arm1)
16774 .expect("arm1 (the non-fallback arm) survives");
16775 let nrecon = remap.get(reconverge).expect("reconverge survives");
16776 let nbranch = remap.get(branch).expect("the Branch node itself survives");
16777 let npost = remap.get(post).expect("post survives");
16778
16779 // The Branch's inputs are the remapped arm exits (arm0 first), and
16780 // its reconverge_at is the remapped reconverge — it still resolves.
16781 let bn = g.node(nbranch);
16782 assert!(matches!(bn.op, Op::Branch { .. }));
16783 assert_eq!(
16784 bn.inputs,
16785 vec![narm0, narm1],
16786 "arm exits remapped, arm0 first"
16787 );
16788 match bn.op {
16789 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, nrecon),
16790 ref other => panic!("expected Op::Branch, got {other:?}"),
16791 }
16792 // reconverge still reads arm0 (runnability preserved through remap).
16793 assert!(g.node(nrecon).inputs.contains(&narm0));
16794 // The arm-0 route is logically identical (same op sequence).
16795 let after_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16796 .iter()
16797 .map(|&id| g.node(id).op.short_name())
16798 .collect();
16799 assert_eq!(before_ops, after_ops, "arm-0 route is logically unchanged");
16800 assert_no_dangling(&g);
16801 }
16802
16803 /// (c) Base map preserved: a branchless, fully-reachable graph compacts
16804 /// to itself — no node dropped; ids may renumber but the structure is
16805 /// identical.
16806 #[test]
16807 fn compact_branchless_reachable_is_identity_in_structure() {
16808 let mut g = Graph::new();
16809 let a = g.push(Node {
16810 op: Op::Const,
16811 inputs: vec![],
16812 shape: Shape::from_dims(&[2]),
16813 dtype: DType::F32,
16814 });
16815 let b = g.push(Node {
16816 op: Op::Relu,
16817 inputs: vec![a],
16818 shape: Shape::from_dims(&[2]),
16819 dtype: DType::F32,
16820 });
16821 let c = g.push(Node {
16822 op: Op::Silu,
16823 inputs: vec![b],
16824 shape: Shape::from_dims(&[2]),
16825 dtype: DType::F32,
16826 });
16827 let d = g.push(Node {
16828 op: Op::Tanh,
16829 inputs: vec![c],
16830 shape: Shape::from_dims(&[2]),
16831 dtype: DType::F32,
16832 });
16833
16834 let before_ops: Vec<&'static str> = extract_runs(&g, d)
16835 .iter()
16836 .flat_map(|r| {
16837 r.members
16838 .iter()
16839 .map(|&id| g.node(id).op.short_name())
16840 .collect::<Vec<_>>()
16841 })
16842 .collect();
16843 let before_len = g.len();
16844
16845 let remap = compact(&mut g, &[d]);
16846
16847 assert_eq!(g.len(), before_len, "a fully-reachable graph drops nothing");
16848 for n in [a, b, c, d] {
16849 assert!(remap.get(n).is_some(), "every node survives");
16850 }
16851 // Structure identical: same op sequence over the compacted graph.
16852 let nd = remap.get(d).unwrap();
16853 let after_ops: Vec<&'static str> = extract_runs(&g, nd)
16854 .iter()
16855 .flat_map(|r| {
16856 r.members
16857 .iter()
16858 .map(|&id| g.node(id).op.short_name())
16859 .collect::<Vec<_>>()
16860 })
16861 .collect();
16862 assert_eq!(before_ops, after_ops);
16863 assert_no_dangling(&g);
16864 }
16865
16866 /// (d) No dangling + round-trip: after `compact`, NO NodeId reference
16867 /// (node inputs, op-carried `reconverge_at`, or any side-table) points
16868 /// outside the new arena, AND `extract_runs` / arm-0 lowering on the
16869 /// compacted graph yields the identical logical result, including for
16870 /// graphs carrying every side-table (placements, target_backends,
16871 /// layouts, storage_map, node_output_views, side_effect_roots).
16872 #[test]
16873 fn compact_no_dangling_and_round_trip_with_side_tables() {
16874 let (mut g, diverge, arm0, _arm1, reconverge, _branch, post) = diamond_with_branch_b4();
16875
16876 // Populate side-tables on surviving nodes so the remap must carry
16877 // them. (target_backend on a couple nodes; placement on one.)
16878 g.set_target_backend(arm0, BackendId::Cpu);
16879 g.set_target_backend(reconverge, BackendId::Cpu);
16880 g.set_placement(diverge, DeviceLocation::Cpu);
16881 // A side-effect root that is itself orphan-from-roots: a Release-like
16882 // op the executor must keep even though no output reads it.
16883 let se = g.push(Node {
16884 op: Op::Const,
16885 inputs: vec![post],
16886 shape: Shape::from_dims(&[2]),
16887 dtype: DType::F32,
16888 });
16889 g.add_side_effect_root(se);
16890
16891 // Orphan debris (referenced by nothing live) to force a real drop.
16892 let _debris = g.push(Node {
16893 op: Op::Const,
16894 inputs: vec![],
16895 shape: Shape::from_dims(&[2]),
16896 dtype: DType::F32,
16897 });
16898
16899 let before_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16900 .iter()
16901 .map(|&id| g.node(id).op.short_name())
16902 .collect();
16903
16904 let remap = compact(&mut g, &[post]);
16905
16906 // No dangling references anywhere.
16907 assert_no_dangling(&g);
16908
16909 // The side-effect root survived (a side-effect-only node is a
16910 // reachability seed) and its side-table entry was remapped.
16911 let nse = remap.get(se).expect("side-effect root survives compaction");
16912 assert!(
16913 g.side_effect_roots().contains(&nse),
16914 "the remapped side-effect root is registered post-compaction",
16915 );
16916 // The surviving target_backend side-table is keyed by the new ids.
16917 assert_eq!(
16918 g.target_backend(remap.get(arm0).unwrap()),
16919 Some(BackendId::Cpu)
16920 );
16921 assert_eq!(
16922 g.target_backend(remap.get(reconverge).unwrap()),
16923 Some(BackendId::Cpu)
16924 );
16925 assert_eq!(
16926 g.placement(remap.get(diverge).unwrap()),
16927 Some(DeviceLocation::Cpu)
16928 );
16929
16930 // Round-trip: the arm-0 route is logically identical.
16931 let npost = remap.get(post).unwrap();
16932 let after_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16933 .iter()
16934 .map(|&id| g.node(id).op.short_name())
16935 .collect();
16936 assert_eq!(
16937 before_run_ops, after_run_ops,
16938 "compaction preserves the realized arm-0 route exactly",
16939 );
16940 }
16941
16942 /// Helper: assert NO NodeId reference in the graph points outside the
16943 /// arena. Covers node `inputs`, the op-carried `Op::Branch.reconverge_at`,
16944 /// every NodeId-keyed side-table, and the `side_effect_roots` vec — the
16945 /// exhaustive no-dangling safety net for a missed remap.
16946 fn assert_no_dangling(g: &Graph) {
16947 let n = g.len();
16948 let ok = |id: NodeId| id.0 < n;
16949 for i in 0..n {
16950 let node = g.node(NodeId(i));
16951 for &inp in &node.inputs {
16952 assert!(ok(inp), "Node#{i} input {:?} dangles (len={n})", inp);
16953 }
16954 if let Op::Branch { reconverge_at } = node.op {
16955 assert!(
16956 ok(reconverge_at),
16957 "Node#{i} Branch.reconverge_at {:?} dangles (len={n})",
16958 reconverge_at
16959 );
16960 }
16961 }
16962 for &r in g.side_effect_roots() {
16963 assert!(ok(r), "side_effect_root {:?} dangles (len={n})", r);
16964 }
16965 // Use the graph's own verification entry point as the load-bearing
16966 // assert (it covers every side-table by reading the private fields).
16967 assert!(
16968 g.verify_no_dangling().is_ok(),
16969 "Graph::verify_no_dangling found a dangling reference: {:?}",
16970 g.verify_no_dangling().err(),
16971 );
16972 }
16973
16974 #[test]
16975 fn scan_variants_construct_and_name() {
16976 use crate::{Graph, Node, Op, ScanEmit, ScanPredicate, ScanRole};
16977 use fuel_ir::{DType, Shape};
16978 let mut g = Graph::new();
16979 let s = Shape::from_dims(&[1, 1, 1]);
16980 let carry = g.push(Node {
16981 op: Op::Const,
16982 inputs: vec![],
16983 shape: s.clone(),
16984 dtype: DType::F32,
16985 });
16986 // A ScanPlaceholder leaf (the per-step carry hole).
16987 let hole = g.push(Node {
16988 op: Op::ScanPlaceholder {
16989 role: ScanRole::Carry,
16990 index: 0,
16991 },
16992 inputs: vec![],
16993 shape: s.clone(),
16994 dtype: DType::F32,
16995 });
16996 // A trivial body: new_carry = hole (identity); body_y = hole.
16997 // Op::Scan node: inputs = [init_carry, <no xs>, <no consts>, body_new_carry, body_y].
16998 let scan = g.push(Node {
16999 op: Op::Scan {
17000 n_carries: 1,
17001 n_xs: 0,
17002 bound: 1,
17003 emit: ScanEmit::All,
17004 early_exit: None,
17005 },
17006 inputs: vec![carry, hole, hole],
17007 shape: s.clone(),
17008 dtype: DType::F32,
17009 });
17010 assert_eq!(g.node(scan).op.short_name(), "Scan");
17011 assert_eq!(g.node(hole).op.short_name(), "ScanPlaceholder");
17012 // early_exit is constructible (guarded elsewhere) but never Some on a live path.
17013 let _guarded = Op::Scan {
17014 n_carries: 1,
17015 n_xs: 0,
17016 bound: 1,
17017 emit: ScanEmit::Final,
17018 early_exit: Some(ScanPredicate),
17019 };
17020 // derive_view_output_layout: Scan is NOT a view op -> Err (handled by the catch-all).
17021 let lay = fuel_ir::Layout::contiguous(s.clone());
17022 let derived = crate::derive_view_output_layout(
17023 &Op::Scan {
17024 n_carries: 1,
17025 n_xs: 0,
17026 bound: 1,
17027 emit: ScanEmit::All,
17028 early_exit: None,
17029 },
17030 &lay,
17031 );
17032 assert!(
17033 derived.is_err(),
17034 "Op::Scan must not be treated as a view op"
17035 );
17036 let _ = scan;
17037 }
17038
17039 #[test]
17040 fn scan_builder_all_and_final_shapes() {
17041 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17042 use fuel_ir::{DType, Shape};
17043 use std::sync::{Arc, RwLock};
17044 let graph = Arc::new(RwLock::new(Graph::new()));
17045 let cs = Shape::from_dims(&[2]); // carry shape
17046 let ys = Shape::from_dims(&[2]); // per-step y shape
17047 let (carry, hole, new_carry, body_y) = {
17048 let mut g = graph.write().unwrap();
17049 let carry = g.push(Node {
17050 op: Op::Const,
17051 inputs: vec![],
17052 shape: cs.clone(),
17053 dtype: DType::F32,
17054 });
17055 let hole = g.push(Node {
17056 op: Op::ScanPlaceholder {
17057 role: ScanRole::Carry,
17058 index: 0,
17059 },
17060 inputs: vec![],
17061 shape: cs.clone(),
17062 dtype: DType::F32,
17063 });
17064 let new_carry = g.push(Node {
17065 op: Op::MulScalar(2.0),
17066 inputs: vec![hole],
17067 shape: cs.clone(),
17068 dtype: DType::F32,
17069 });
17070 let body_y = g.push(Node {
17071 op: Op::AddScalar(1.0),
17072 inputs: vec![new_carry],
17073 shape: ys.clone(),
17074 dtype: DType::F32,
17075 });
17076 (carry, hole, new_carry, body_y)
17077 };
17078 let t = |id| NodeHandle {
17079 graph: graph.clone(),
17080 id,
17081 }; // same-crate access to private fields
17082 let init = t(carry);
17083 let (nc, by) = (t(new_carry), t(body_y));
17084 let bound = 4usize;
17085
17086 let all = init
17087 .scan(&[], &[], &nc, &by, bound, ScanEmit::All)
17088 .expect("scan All");
17089 assert_eq!(
17090 all.shape().dims(),
17091 &[bound, 2],
17092 "emit=All -> [bound] ++ body_y"
17093 );
17094
17095 // Structural guard (Task-2 review finding): the Op::Scan node's
17096 // inputs MUST end with [.., body_new_carry, body_y] in that
17097 // order — base_map_hash recurses into the last two inputs to
17098 // hash the body, so a reordering would silently hash the wrong
17099 // subgraph. `all` is a View(0) over the producer; its own
17100 // single input is the producer NodeId.
17101 {
17102 let g = graph.read().unwrap();
17103 let producer_id = g.node(all.id()).inputs[0];
17104 let producer_inputs = &g.node(producer_id).inputs;
17105 assert_eq!(
17106 producer_inputs[producer_inputs.len() - 2],
17107 nc.id(),
17108 "Op::Scan inputs[len-2] must be body_new_carry",
17109 );
17110 assert_eq!(
17111 producer_inputs[producer_inputs.len() - 1],
17112 by.id(),
17113 "Op::Scan inputs[len-1] must be body_y",
17114 );
17115 }
17116
17117 let fin = init
17118 .scan(&[], &[], &nc, &by, bound, ScanEmit::Final)
17119 .expect("scan Final");
17120 assert_eq!(fin.shape().dims(), &[2], "emit=Final -> carry shape");
17121 let _ = hole;
17122 }
17123
17124 #[test]
17125 fn scan_builder_rejects_zero_bound() {
17126 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17127 use fuel_ir::{DType, Shape};
17128 use std::sync::{Arc, RwLock};
17129 let graph = Arc::new(RwLock::new(Graph::new()));
17130 let cs = Shape::from_dims(&[1]);
17131 let (carry, new_carry, body_y) = {
17132 let mut g = graph.write().unwrap();
17133 let carry = g.push(Node {
17134 op: Op::Const,
17135 inputs: vec![],
17136 shape: cs.clone(),
17137 dtype: DType::F32,
17138 });
17139 let hole = g.push(Node {
17140 op: Op::ScanPlaceholder {
17141 role: ScanRole::Carry,
17142 index: 0,
17143 },
17144 inputs: vec![],
17145 shape: cs.clone(),
17146 dtype: DType::F32,
17147 });
17148 let nc = g.push(Node {
17149 op: Op::MulScalar(2.0),
17150 inputs: vec![hole],
17151 shape: cs.clone(),
17152 dtype: DType::F32,
17153 });
17154 (carry, nc, nc)
17155 };
17156 let t = |id| NodeHandle {
17157 graph: graph.clone(),
17158 id,
17159 };
17160 let r = t(carry).scan(&[], &[], &t(new_carry), &t(body_y), 0, ScanEmit::All);
17161 assert!(r.is_err(), "bound == 0 must be a typed Err, not a panic");
17162 }
17163
17164 /// Task 5 (C6): every "opt-in" classifier/dispatch site over `Op` must
17165 /// treat the new `Op::Scan` / `Op::ScanPlaceholder` variants via its
17166 /// existing safe-conservative wildcard/allow-list — no site should need
17167 /// a bespoke Scan arm in Phase 1. This is a regression LOCK, not a
17168 /// born-red test: every assertion here is expected to pass immediately
17169 /// because the wildcards already exist; a red assertion means that site
17170 /// silently mishandles Scan and needs a conservative arm added.
17171 ///
17172 /// Also confirms reachability: `Op::Scan`'s body lives in its own
17173 /// `inputs` (like `Op::Branch`'s arms), so the ordinary input-closure
17174 /// walk (`topo_order_multi`) sees body nodes for free — no
17175 /// `effective_roots` / `live_set` edit is needed.
17176 #[test]
17177 fn scan_opt_in_sites_are_safe_defaults() {
17178 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
17179 use fuel_ir::{DType, Shape};
17180 let scan = Op::Scan {
17181 n_carries: 1,
17182 n_xs: 0,
17183 bound: 2,
17184 emit: ScanEmit::All,
17185 early_exit: None,
17186 };
17187 let hole = Op::ScanPlaceholder {
17188 role: ScanRole::Carry,
17189 index: 0,
17190 };
17191 // Classifier defaults.
17192 assert_eq!(scan.destructive_input(), None);
17193 assert_eq!(hole.destructive_input(), None);
17194 assert!(!scan.is_view_op());
17195 assert!(!hole.is_view_op());
17196 assert_eq!(
17197 crate::infer_storage_class(&scan),
17198 crate::StorageClass::Transient
17199 );
17200 assert_eq!(crate::jit::op_to_tag(&scan), None);
17201 // Reachability: build a graph with an Op::Scan whose body references a hole;
17202 // the hole (a body node) is reachable from the Scan via inputs, no seeding.
17203 let mut g = Graph::new();
17204 let s = Shape::from_dims(&[1]);
17205 let carry = g.push(Node {
17206 op: Op::Const,
17207 inputs: vec![],
17208 shape: s.clone(),
17209 dtype: DType::F32,
17210 });
17211 let h = g.push(Node {
17212 op: hole.clone(),
17213 inputs: vec![],
17214 shape: s.clone(),
17215 dtype: DType::F32,
17216 });
17217 let nc = g.push(Node {
17218 op: Op::MulScalar(2.0),
17219 inputs: vec![h],
17220 shape: s.clone(),
17221 dtype: DType::F32,
17222 });
17223 let sc = g.push(Node {
17224 op: scan.clone(),
17225 inputs: vec![carry, nc, nc],
17226 shape: Shape::from_dims(&[2, 1]),
17227 dtype: DType::F32,
17228 });
17229 let reachable = crate::topo_order_multi(&g, &[sc]);
17230 assert!(
17231 reachable.contains(&nc) && reachable.contains(&h),
17232 "body nodes must be reachable from Op::Scan via inputs (no effective_roots edit needed)"
17233 );
17234 }
17235}