fuel_graph/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! # fuel-graph
3//!
4//! Lazy computation graph for Phase 6 of the fuel ML framework.
5//!
6//! ## Role
7//!
8//! Phase 6 transitions fuel from eager execution to a lazy computation graph
9//! with an autonomous router. This crate holds the minimal vocabulary that
10//! makes that transition possible:
11//!
12//! - [`Op`] — a closed enum describing every operation that can appear in a
13//! graph node. New ops are added here and consumed by every backend.
14//! - [`Graph`] — an arena of [`Node`]s. Nodes are immutable once added and
15//! referenced by index. The arena grows; it never shrinks.
16//! - [`NodeHandle`] — a cheaply-cloneable handle to a `(graph, node_id)` pair.
17//! Users build computations by calling methods on `NodeHandle`; each method
18//! appends a node to the underlying graph and returns a new handle.
19//!
20//! Execution is deliberately not implemented here. A separate executor —
21//! `fuel-dispatch`'s `PipelinedExecutor`, dispatching to the per-backend
22//! kernels (`fuel-cpu-backend`, `fuel-cuda-backend`, `fuel-vulkan-backend`) —
23//! walks a `Graph` and produces concrete outputs. (The retired
24//! `fuel-reference-backend` textbook walker was the original executor; the
25//! CPU backend's bit-stable kernels are the correctness oracle now.)
26//!
27//! ## Scope of the MVP
28//!
29//! This is the first landing of the graph types. It is deliberately minimal:
30//!
31//! - Four float dtypes: `f32`, `f64`, `bf16`, `f16`. Integer dtypes will be
32//! added alongside the reference backend's integer op coverage, not
33//! speculatively here.
34//! - A small starter `Op` catalog: `Const`, `Add`, `Mul`, `MatMul`,
35//! `Transpose`, `Relu`, `Sqr`, `Exp`. More ops are added as validation
36//! tests for them land.
37//! - Unfused backward autograd: [`NodeHandle::backward`] walks the forward
38//! graph in reverse, applies per-op gradient rules, and emits new graph
39//! nodes for the gradient of every leaf. Fused backward and symbolic
40//! graph rewriting are deferred to Phase 6d.
41//! - No fusion, no planner. Those belong to later sub-phases of Phase 6.
42//! - Thread-safe. The graph is wrapped in `Arc<RwLock<_>>` so that
43//! `fuel_graph::NodeHandle` — the lazy build handle — and any handle that
44//! embeds it are `Send + Sync`. Borrow access goes through
45//! `read().unwrap()` / `write().unwrap()`.
46
47pub mod grad;
48pub mod jit;
49pub mod opt;
50pub mod registry;
51pub mod run;
52pub mod runtime_fused;
53pub mod scan;
54mod shape;
55
56#[doc(inline)]
57pub use run::{
58 FEWNESS_THRESHOLD, PickedRoute, Run, branch_density, branch_density_multi,
59 branches_in_topo_order, device_alternating_order, effective_roots, extract_runs,
60 extract_runs_multi, lower_picked_route, lower_picked_route_streaming, lower_run,
61 lower_runs_arm0, passes_fewness_gate, walk_picked_route_streaming,
62};
63
64pub use shape::primitive_shape;
65
66use crate::registry::{FusedOpId, FusedOpParams};
67use fuel_backend_contract::Storage;
68use fuel_ir::{DType, DeviceLocation, DynScalar, Layout, Scalar, Shape, SymId, probe::BackendId};
69use half::{bf16, f16};
70use std::collections::{HashMap, HashSet};
71use std::sync::{Arc, RwLock};
72
73/// Compute the topological order of every node reachable from `root`.
74///
75/// The returned order places inputs before the nodes that depend on them,
76/// so iterating the list and caching each result as you go guarantees every
77/// dependency is available when its dependents are computed. Uses an
78/// explicit stack iterative post-order DFS — no recursion, so arbitrarily
79/// deep graphs are safe.
80///
81/// This is the utility an executor walks to realize a tensor, and the
82/// utility [`NodeHandle::backward`] walks in reverse to construct the backward
83/// graph.
84pub fn topo_order(graph: &Graph, root: NodeId) -> Vec<NodeId> {
85 topo_order_multi(graph, &[root])
86}
87
88/// Compute the topological order of every node reachable from ANY of the
89/// given roots. Each node appears in the output exactly once; the order
90/// still satisfies the dependency-before-dependent property, so walking
91/// it and caching results as you go computes every input before any node
92/// that depends on it.
93///
94/// Used by the multi-output `realize_many` entry points in executors:
95/// KV-cached inference wants the per-step logits AND the updated K/V
96/// tensors for every layer as outputs of a single forward pass. Asking
97/// the executor for them via `topo_order_multi` walks the graph exactly
98/// once for the combined dependency set, then the executor reads each
99/// requested root out of the cache.
100pub fn topo_order_multi(graph: &Graph, roots: &[NodeId]) -> Vec<NodeId> {
101 let mut order = Vec::new();
102 let mut visited: HashSet<NodeId> = HashSet::new();
103 // Each stack entry is (node, processed). `processed = false` means
104 // "push children then revisit me"; `processed = true` means "all my
105 // children are already in `order`, add me now."
106 let mut stack: Vec<(NodeId, bool)> = roots.iter().map(|&r| (r, false)).collect();
107 while let Some((id, processed)) = stack.pop() {
108 if processed {
109 order.push(id);
110 continue;
111 }
112 if visited.contains(&id) {
113 continue;
114 }
115 visited.insert(id);
116 stack.push((id, true));
117 for &child in &graph.node(id).inputs {
118 if !visited.contains(&child) {
119 stack.push((child, false));
120 }
121 }
122 }
123 order
124}
125
126/// A node ID in the arena. Stable for the lifetime of the [`Graph`].
127#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
128pub struct NodeId(pub usize);
129
130/// Quantization block format for the `QMatMul` fused op
131/// ([`crate::registry::FusedOpParams::QMatMul`]). Matches the
132/// GGML/GGUF block layouts; each variant implies a fixed bytes-per-block
133/// and elements-per-block. Only variants for which a backend has a
134/// fused dequant-in-kernel matmul are currently exposed.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub enum QuantType {
137 /// 32-element block = 2 bytes f16 scale + 16 bytes packed u4 quants.
138 Q4_0,
139 /// 32-element block = 2 bytes f16 d + 2 bytes f16 m + 16 bytes packed u4 quants.
140 Q4_1,
141 /// 32-element block = 2 bytes f16 d + 4 bytes high-bit + 16 bytes packed u4 quants.
142 Q5_0,
143 /// 32-element block = 2 bytes f16 d + 2 bytes f16 m + 4 bytes high-bit + 16 bytes packed u4.
144 Q5_1,
145 /// 32-element block = 2 bytes f16 scale + 32 bytes i8 quants.
146 Q8_0,
147 /// 32-element block = 2 bytes f16 d + 2 bytes f16 s + 32 bytes i8 quants.
148 Q8_1,
149 /// 256-element super-block = scales + 64-byte 2-bit packed quants + 4 bytes f16 d/dmin.
150 Q2K,
151 /// 256-element super-block = hmask + 64-byte 2-bit packed quants + 12-byte scales + 2 bytes f16 d.
152 Q3K,
153 /// 256-element super-block = 2 bytes f16 d + 2 bytes f16 dmin +
154 /// 12 bytes of 6-bit-packed sub-block scales/mins + 128 bytes
155 /// of 4-bit-packed quants. GGML k-quant "medium" format.
156 #[expect(
157 non_camel_case_types,
158 reason = "GGML k-quant spec identifier (Q4_K_M = 4-bit K-quant Medium); matches the upstream / on-disk format name -- external convention over internal casing"
159 )]
160 Q4_K_M,
161 /// 256-element super-block = d + dmin + 12-byte scales + 32-byte hmask + 128-byte qs.
162 Q5K,
163 /// 256-element super-block = 128-byte ql + 64-byte qh + 16-byte i8 scales + 2 bytes f16 d.
164 Q6K,
165}
166
167impl QuantType {
168 /// Bytes per quantization block. Mirrors `std::mem::size_of::<BlockQ*>()`.
169 pub fn bytes_per_block(self) -> usize {
170 match self {
171 QuantType::Q4_0 => 18,
172 QuantType::Q4_1 => 20,
173 QuantType::Q5_0 => 22,
174 QuantType::Q5_1 => 24,
175 QuantType::Q8_0 => 34,
176 QuantType::Q8_1 => 36,
177 QuantType::Q2K => 84,
178 QuantType::Q3K => 110,
179 QuantType::Q4_K_M => 144,
180 QuantType::Q5K => 176,
181 QuantType::Q6K => 210,
182 }
183 }
184 /// Elements per quantization block.
185 pub fn elements_per_block(self) -> usize {
186 match self {
187 QuantType::Q4_0
188 | QuantType::Q4_1
189 | QuantType::Q5_0
190 | QuantType::Q5_1
191 | QuantType::Q8_0
192 | QuantType::Q8_1 => 32,
193 QuantType::Q2K
194 | QuantType::Q3K
195 | QuantType::Q4_K_M
196 | QuantType::Q5K
197 | QuantType::Q6K => 256,
198 }
199 }
200}
201
202/// Fill mode for [`Op::Pad`]. Only [`PadMode::Constant`] is
203/// implemented in the v1 cut; the other variants are accepted at
204/// the IR level so the enum is forward-stable, but the executor
205/// returns a clean error until they ship.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub enum PadMode {
208 /// Fill padded slots with the constant `value` parameter on
209 /// the [`Op::Pad`] variant.
210 Constant,
211 /// Reflect input around the padded edges (without repeating the
212 /// edge value). Not yet implemented.
213 Reflect,
214 /// Repeat the edge value into the padded region. Not yet
215 /// implemented.
216 Replicate,
217}
218
219/// The closed enum of operations a graph node can represent.
220///
221/// This is the API contract between the graph layer and every backend.
222/// Adding a new op means (1) adding a variant here, (2) teaching every
223/// backend how to execute it, and (3) teaching the reference backend how
224/// to compute its textbook answer.
225// EXHAUSTIVE-BY-DESIGN: `Op` is the CLOSED graph vocabulary; `OpKind`
226// (fuel-ir/src/dispatch.rs) is the deliberately-`#[non_exhaustive]` EXTENSIBLE
227// dispatch key. This marker makes that split — currently stated only in the doc
228// above — explicit and machine-checkable. The forcing functions are in-crate and
229// exhaustive: `op_short_name` (below) and the autograd `backward` match; adding a
230// variant fails to compile until both get an arm, which is the intended
231// enforcement (a new op with no gradient rule must not compile silently). Because
232// those live in fuel-graph, `-p fuel-graph` DOES catch a variant-add here (unlike
233// Scalar/DType, whose exhaustive consumers are cross-crate) — but do NOT add
234// `#[non_exhaustive]`: it would falsely advertise Op as open to external
235// consumers, contradicting the "teach every backend" contract. Downstream
236// dispatch/cost/telemetry consumers legitimately PARTIAL-match Op with sound
237// defaults (`None`/`Err`/skip); execution is gated by `op_to_op_kind` returning
238// `None`, so a new op is never silently mis-executed — that is why a plain
239// wildcard is correct THERE and forbidden in the two forcing functions above.
240// A THIRD in-crate forcing function joined the two above (GAP-076):
241// `destructive_input` (this file) is now exhaustive as well — a new primitive
242// must classify itself there (destructive → `Some(idx)`, otherwise `None`), and
243// a new *fused* op declares destructiveness as a mandatory `FusedOpEntry` field
244// that `Op::destructive_input` reads via `default_registry()`. The old
245// `_ => None` there silently read a new destructive op as non-destructive and
246// dropped its scheduler ordering edges (a data race); it is gone. See GAP-049
247// and GAP-076.
248#[derive(Debug, Clone, PartialEq)]
249pub enum Op {
250 // --- leaves ---
251 /// A concrete constant tensor — a leaf with no input nodes. The
252 /// realized bytes live in the graph's `storage_map` slot for this
253 /// node, populated at construction time. The executor's slot-first
254 /// dispatch returns the slot's `Arc<RwLock<Storage>>` directly.
255 /// (Phase 7.5 work item G2 retired the host-side `ConstData`
256 /// payload — the slot is the sole source of bytes.)
257 Const,
258
259 /// Position-index generator — a leaf (no inputs) producing the 1-D
260 /// `F32` sequence `[0.0, 1.0, …, (len-1) as f32]` of shape `[len]`.
261 /// The integer-valued positions are exact in `f32` for any realistic
262 /// sequence length (`< 2^24`). Reshaped + broadcast, it builds the
263 /// row/column indices that express causal / sliding-window masks and
264 /// alibi position biases (e.g. in FlashAttn's decomposition), so those
265 /// ops can lower to primitives instead of being opaque. Non-differentiable
266 /// (a constant generator; backward drops gradient like `Op::Const`).
267 Iota { len: usize },
268
269 // --- element-wise binary ---
270 /// Element-wise addition.
271 Add,
272 /// Element-wise subtraction (`a - b`).
273 Sub,
274 /// Element-wise multiplication.
275 Mul,
276 /// Element-wise division (`a / b`).
277 Div,
278
279 // --- element-wise unary ---
280 /// Element-wise negation (`-x`).
281 Neg,
282 /// Element-wise square (`x * x`).
283 Sqr,
284 /// Element-wise square root.
285 Sqrt,
286 /// Element-wise exponential (`e^x`).
287 Exp,
288 /// Element-wise natural logarithm.
289 Log,
290 /// Element-wise sine.
291 Sin,
292 /// Element-wise cosine.
293 Cos,
294 /// Element-wise hyperbolic tangent.
295 Tanh,
296 /// Element-wise logistic sigmoid.
297 Sigmoid,
298 /// SiLU activation (x · sigmoid(x)), also called Swish.
299 Silu,
300 /// GELU activation (tanh approximation).
301 GeluTanh,
302 /// Rectified linear unit (`max(0, x)`), element-wise.
303 Relu,
304 /// Heaviside step function: `1` where `x > 0`, `0` otherwise. Serves
305 /// as the derivative of `Relu` and as a building block for other
306 /// comparison-based gradients.
307 Step,
308 /// Element-wise reciprocal (`1 / x`). On `x = 0` the IEEE-754 result
309 /// is `±inf`; the kernel matches the obvious `1.0 / x` expression
310 /// rather than treating the input as an error.
311 Recip,
312 /// Element-wise absolute value (`|x|`).
313 Abs,
314
315 // --- in-place elementwise unary (Phase 1 of the in-place ops
316 // infrastructure landed 2026-05-30; see
317 // `docs/session-prompts/in-place-ops-infrastructure.md`) ---
318 //
319 // Each variant mutates input 0 in place; output aliases input 0.
320 // Pinned to run after every non-destructive reader of input 0 by
321 // `opt::derive_ordering` via the `destructive_input() -> Some(0)`
322 // contract. Backward integration deferred to Phase 4 (the
323 // mutation-safety pass auto-clones tape-tracked inputs).
324 /// In-place Relu: `x = max(0, x)`. Same semantics as `Op::Relu`,
325 /// mutates input 0. Not yet wired through autograd.
326 ReluInplace,
327 /// In-place Silu: `x = x * sigmoid(x)`. Same semantics as
328 /// `Op::Silu`, mutates input 0. Not yet wired through autograd.
329 SiluInplace,
330 /// In-place GeluTanh (tanh approximation): mutates input 0 with the
331 /// same formula as `Op::GeluTanh`. Not yet wired through autograd.
332 GeluTanhInplace,
333 /// In-place Tanh: mutates input 0. Same semantics as `Op::Tanh`.
334 /// Not yet wired through autograd.
335 TanhInplace,
336 /// In-place Sigmoid: mutates input 0. Same semantics as
337 /// `Op::Sigmoid`. Not yet wired through autograd.
338 SigmoidInplace,
339
340 // --- in-place elementwise unary, dtype expansion + op family
341 // expansion shipped 2026-05-30. Same `destructive_input() ->
342 // Some(0)` contract as the 5 above; backward emitters mirror
343 // the non-inplace cousin (chain-rule formulas relying on
344 // Phase 4a view-aware ordering for pre-mutation reads of x).
345 /// In-place Neg: `x = -x`. Same semantics as `Op::Neg`.
346 NegInplace,
347 /// In-place Abs: `x = |x|`. Same semantics as `Op::Abs`.
348 AbsInplace,
349 /// In-place Sqr: `x = x²`. Same semantics as `Op::Sqr`.
350 SqrInplace,
351 /// In-place Sqrt: `x = √x`. Same semantics as `Op::Sqrt`.
352 SqrtInplace,
353 /// In-place Rsqrt: `x = 1/√x`. Same semantics as `Op::Rsqrt`.
354 RsqrtInplace,
355 /// In-place Recip: `x = 1/x`. Same semantics as `Op::Recip`.
356 RecipInplace,
357 /// In-place Exp: `x = exp(x)`. Same semantics as `Op::Exp`.
358 ExpInplace,
359 /// In-place Log: `x = ln(x)`. Same semantics as `Op::Log`.
360 LogInplace,
361 /// In-place Sin: `x = sin(x)`. Same semantics as `Op::Sin`.
362 SinInplace,
363 /// In-place Cos: `x = cos(x)`. Same semantics as `Op::Cos`.
364 CosInplace,
365 /// In-place Sign: `x = sign(x)`. Same semantics as `Op::Sign`.
366 /// Backward drops gradient (mirrors `Op::Sign`).
367 SignInplace,
368 /// In-place Floor: `x = ⌊x⌋`. Same semantics as `Op::Floor`.
369 /// Backward drops gradient (mirrors `Op::Floor`).
370 FloorInplace,
371 /// In-place Ceil: `x = ⌈x⌉`. Same semantics as `Op::Ceil`.
372 /// Backward drops gradient (mirrors `Op::Ceil`).
373 CeilInplace,
374 /// In-place Round: `x = round(x)`. Same semantics as `Op::Round`.
375 /// Backward drops gradient (mirrors `Op::Round`).
376 RoundInplace,
377 /// In-place Erf: `x = erf(x)`. Same semantics as `Op::Erf`.
378 ErfInplace,
379 /// In-place exact-GeLU: `x = 0.5 · x · (1 + erf(x/√2))`. Same
380 /// semantics as `Op::Gelu`.
381 GeluInplace,
382 /// In-place clamp: `x = clamp(x, min, max)`. Same semantics as
383 /// `Op::Clamp`. Backward gates the upstream by `(x ≥ min) ∧
384 /// (x ≤ max)` (mirrors Op::Clamp).
385 ClampInplace { min: f64, max: f64 },
386 /// In-place integer-power: `x = x.powi(exp)`. Same semantics as
387 /// `Op::PowI`. Backward emits `exp · upstream · x.powi(exp-1)`
388 /// (mirrors Op::PowI).
389 PowIInplace(i32),
390
391 // --- element-wise comparison (output is Bool mask) ---
392 /// Element-wise equality (`a == b`) producing a `Bool` mask: `1`
393 /// where the inputs are equal, `0` otherwise. Both operands must
394 /// share dtype and shape. NaN follows IEEE-754 (`NaN == NaN` is
395 /// false). Output dtype is always `Bool`, regardless of input dtype
396 /// — the binding-table key is `[T, T, Bool]`.
397 ///
398 /// Non-differentiable: backward returns `None` for both inputs
399 /// (registered via [`crate::grad::NoGradientBinaryRule`]).
400 Equal,
401 /// Element-wise inequality (`a != b`) producing a `Bool` mask: `1`
402 /// where unequal, `0` otherwise. Same shape/dtype contract as
403 /// [`Op::Equal`]. NaN follows IEEE-754 (`NaN != NaN` is true →
404 /// `1`). Non-differentiable.
405 Ne,
406 /// Element-wise strictly-less (`a < b`) producing a `Bool` mask: `1`
407 /// where lhs is strictly less than rhs, `0` otherwise. Same
408 /// shape/dtype contract as [`Op::Equal`]. NaN-on-either-side is
409 /// always `0` (IEEE-754 unordered comparison). Non-differentiable.
410 Lt,
411 /// Element-wise less-or-equal (`a <= b`) producing a `Bool` mask.
412 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
413 /// is always `0`. Non-differentiable.
414 Le,
415 /// Element-wise strictly-greater (`a > b`) producing a `Bool` mask.
416 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
417 /// is always `0`. Non-differentiable.
418 Gt,
419 /// Element-wise greater-or-equal (`a >= b`) producing a `Bool` mask.
420 /// Same shape/dtype contract as [`Op::Equal`]. NaN-on-either-side
421 /// is always `0`. Non-differentiable. Final variant of the
422 /// comparison family (`Equal`, `Ne`, `Lt`, `Le`, `Gt`, `Ge`).
423 Ge,
424
425 // --- rounding family (non-differentiable) ---
426 /// Element-wise floor (`⌊x⌋`). Same dtype as input. Backward is
427 /// the zero distribution almost everywhere; gradient is dropped
428 /// silently (treated like `Op::Step`'s no-grad backward).
429 Floor,
430 /// Element-wise ceiling (`⌈x⌉`). Same dtype as input. Backward
431 /// drops gradient (mirrors [`Op::Floor`]).
432 Ceil,
433 /// Element-wise round-to-nearest with **banker's rounding**
434 /// (round-half-to-even, IEEE 754 roundeven). 0.5 → 0, 1.5 → 2,
435 /// 2.5 → 2 (NOT 3), 3.5 → 4. Matches NumPy/PyTorch defaults and
436 /// differs from C99 `round()` (half-away-from-zero) at exact ties.
437 /// Backward drops gradient (mirrors [`Op::Floor`]).
438 Round,
439 /// Element-wise sign (`-1` / `0` / `1`). `sign(0) = 0` by
440 /// subgradient convention (same convention `Op::Abs`'s backward
441 /// uses). Same dtype as input. Backward drops gradient (zero
442 /// almost everywhere).
443 Sign,
444 /// Element-wise Gauss error function (`erf(x)`). Same dtype as
445 /// input. Differentiable: `d/dx erf(x) = (2/√π) * exp(-x²)`.
446 /// Backward emitted via existing primitives (Sqr → Neg → Exp →
447 /// MulScalar(2/√π) → Mul(upstream, .)).
448 Erf,
449 /// Element-wise GELU activation, **exact erf formulation**:
450 /// `0.5 * x * (1 + erf(x/√2))`. Distinct from [`Op::GeluTanh`]
451 /// (tanh approximation, faster but slightly less accurate).
452 /// Differentiable; backward decomposes into the standard-normal
453 /// CDF + `x * φ(x)` (PDF) chain via primitives.
454 Gelu,
455 /// Element-wise binary power: `out = pow(a, b)` with real `b`.
456 /// Both inputs share dtype `T` and shape. Distinct from
457 /// [`Op::PowI`] (scalar `i32` exponent). Backward:
458 /// d/da pow(a,b) = b * pow(a, b-1)
459 /// d/db pow(a,b) = pow(a,b) * ln(a)
460 /// NaN follows IEEE-754 (`pow(-2, 0.5) = NaN`); ln of negative `a`
461 /// in the d/db term yields NaN at those positions.
462 Pow,
463 /// Element-wise reciprocal square root: `out = 1 / sqrt(x)`.
464 /// Same dtype as input. Distinct from `Sqrt` followed by `Recip`
465 /// (one op instead of two — saves a kernel launch and matches the
466 /// RMSNorm shape `x * rsqrt(mean(x²)+eps)`). Backward:
467 /// d/dx (x^(-1/2)) = -0.5 * x^(-3/2) = -0.5 * y³
468 /// where `y = 1/sqrt(x)` is the forward output (so the chain
469 /// reuses the forward node and never touches `x` directly —
470 /// safe near x=0).
471 Rsqrt,
472 /// Element-wise remainder, **PyTorch convention**:
473 /// `out = a - floor(a / b) * b`. The result has the sign of the
474 /// divisor (matches `torch.remainder`). Distinct from C99 fmod
475 /// (sign of dividend) and `f32::rem_euclid` (always non-negative).
476 /// Backward:
477 /// d/da = 1
478 /// d/db = -floor(a/b)
479 Rem,
480 /// Reverse the order of elements along `dim`. Materializing op
481 /// (not a view) — `Layout`'s strides are `usize` so the
482 /// negative-stride view path isn't representable. Backward is
483 /// `Flip { dim }` itself (involutive).
484 Flip { dim: usize },
485 /// Cyclic shift along `dim` by `shift` positions (positive
486 /// shifts move elements to higher indices, wrapping around).
487 /// Materializing op. Backward is `Roll { dim, -shift }`.
488 Roll { dim: usize, shift: i64 },
489 /// Running cumulative sum along `dim`. Same shape as input.
490 /// Backward: reverse cumsum, expressed as `Flip → CumSum → Flip`
491 /// on the same dim using existing primitives.
492 CumSum { dim: usize },
493 /// Upper triangular: keep `x[..., i, j]` when `j >= i + diagonal`,
494 /// zero otherwise. Operates on the last two dims; leading dims
495 /// are batched. `diagonal` selects which diagonal is the cutoff
496 /// (0 = main diagonal, positive = above, negative = below).
497 /// Same shape as input. Backward is `Triu { diagonal }` itself
498 /// (linear mask; gradient passes through kept positions).
499 Triu { diagonal: i64 },
500 /// Lower triangular: keep `x[..., i, j]` when `j <= i + diagonal`,
501 /// zero otherwise. Operates on the last two dims; leading dims
502 /// are batched. `diagonal` selects which diagonal is the cutoff
503 /// (0 = main diagonal, positive = above, negative = below). The
504 /// canonical causal-attention mask is `tril(diagonal = 0)`.
505 /// Same shape as input. Backward is `Tril { diagonal }` itself.
506 Tril { diagonal: i64 },
507 /// Numerically-stable log-softmax along the last dimension:
508 /// `y_i = x_i - max_j(x_j) - log(sum_j exp(x_j - max_j(x_j)))`.
509 /// Same shape as input. Used in NLL / cross-entropy loss where
510 /// the explicit `log(softmax(x))` decomposition risks
511 /// over/underflow. Backward: see [`Op::LogSoftmaxLastDimBackward`].
512 LogSoftmaxLastDim,
513 /// MaskedFill: `out = where(mask != 0, value, x)`. Inputs:
514 /// `(x, mask)` where `mask` is U8 (any nonzero counts as "fill").
515 /// `value` is a scalar of the same dtype as `x`, stored on the
516 /// op. Output shape == x shape (mask must broadcast to x but the
517 /// simple-shape case requires identical shapes today). Backward
518 /// passes the upstream gradient through `x` at positions where
519 /// `mask == 0`, and contributes zero to `mask` (U8 anyway).
520 MaskedFill { value: Scalar },
521 /// Backward helper for [`Op::Pad`]. Single input is the upstream
522 /// gradient (shape == padded forward output shape); output is the
523 /// gradient with respect to the original input (shape ==
524 /// `in_shape`). Mode determines accumulation behavior:
525 /// - Constant: gradient at padded slots is dropped; the unpadded
526 /// region is the input gradient.
527 /// - Reflect / Replicate: gradient accumulates from output
528 /// positions that map back to each input position via the
529 /// forward index function.
530 ///
531 /// Carries `in_shape` so the kernel can size the output tensor
532 /// (Op output shape isn't enough — Op::Pad's output shape
533 /// derivation needs reversing).
534 PadBackward {
535 in_shape: Shape,
536 padding: Vec<(usize, usize)>,
537 mode: PadMode,
538 },
539
540 /// Multi-dim Pad: per-axis `(before, after)` extends each
541 /// dimension. Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
542 /// `mode` selects the fill behavior; `value` is the fill
543 /// constant for [`PadMode::Constant`] (ignored otherwise — see
544 /// the variant docs for those modes).
545 ///
546 /// Multi-dim shape is the form PyTorch's `F.pad` exposes — a
547 /// single call covers e.g. "pad an image by 1 px on every side"
548 /// (`padding = [(0,0), (0,0), (1,1), (1,1)]` for `[N,C,H,W]`).
549 /// Single-dim is just the special case `padding[i] = (0,0)`
550 /// everywhere except one axis.
551 ///
552 /// Only Constant mode is fully implemented in v1. Reflect /
553 /// Replicate are accepted at the IR level but the executor
554 /// returns a clean "not yet implemented" error.
555 ///
556 /// Backward (Constant): slice along each padded axis to drop
557 /// the padded regions, restoring the input shape.
558 Pad {
559 padding: Vec<(usize, usize)>,
560 mode: PadMode,
561 value: f64,
562 },
563
564 // --- ternary select ---
565 /// Ternary select: `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
566 /// Inputs `(cond, a, b)`: `cond` is `U8` (typically the output of
567 /// a comparison op), `a` and `b` share dtype `T` and shape with
568 /// `cond`. Output dtype = `T`, shape = `cond.shape()`.
569 ///
570 /// Differentiable through `a` and `b` (gradient flows only to
571 /// the picked positions); `cond` is non-differentiable. Backward
572 /// rule expressed via `Op::Cast` + scalar arithmetic on existing
573 /// primitives, registered in [`crate::grad::WhereRule`].
574 Where,
575
576 // --- linear algebra and shape ---
577 /// Rank-2 matrix multiply.
578 MatMul,
579 /// Rank-2 transpose.
580 Transpose,
581 /// N-dimensional permutation. The parameter is the new axis order:
582 /// `out.shape[i] = in.shape[axes[i]]`. For a rank-3 input `[a, b, c]`
583 /// with `axes = [2, 0, 1]`, output shape is `[c, a, b]`. The axes
584 /// vector must be a permutation of `0..rank`.
585 Permute(Vec<usize>),
586
587 // --- dtype, shape, and broadcasting ---
588 /// Convert a tensor to a different dtype. The target dtype is carried
589 /// on the op itself; the source dtype is whatever the input node's
590 /// dtype is.
591 Cast(DType),
592 /// Broadcast a tensor to a larger shape. The input shape must be
593 /// broadcast-compatible with the target (NumPy rules). Used directly
594 /// by user code and as the backward rule for `SumAll`, `MeanAll`,
595 /// and axis reductions.
596 BroadcastTo(Shape),
597 /// Reshape a tensor to a new shape with the same element count. Data
598 /// is unchanged; only the shape metadata is replaced. Serves as the
599 /// general building block for arbitrary shape changes;
600 /// see [`Op::Unsqueeze`] for the metadata-only-view variant that
601 /// inserts a size-1 dim without ever materializing.
602 Reshape(Shape),
603 /// Materialize a contiguous copy of the input. Output shape and
604 /// dtype match the input; only the layout changes (strides become
605 /// row-major, start_offset becomes 0). Zero-cost when the input
606 /// is already contiguous + zero-offset — the executor adopts the
607 /// input's Storage Arc unchanged in that case.
608 ///
609 /// First-class IR concern so the optimizer (Phase 2.2) can insert
610 /// layout-fixups before kernels that don't advertise
611 /// `crate::KernelCaps::strided_input` without overloading
612 /// [`Op::Reshape`]'s "change shape" semantics. The executor
613 /// compiles this to the same `WorkItemKind::ContiguizeOf` arm
614 /// `Op::Reshape` uses; the only difference is that
615 /// `Op::Contiguize`'s output shape equals its input shape, so
616 /// the executor's element-count sanity check is trivial.
617 Contiguize,
618 /// Insert a size-1 dimension at position `dim` (range `0..=rank`,
619 /// where `dim == rank` appends to the end). Strictly more efficient
620 /// than [`Op::Reshape`] for the size-1-insertion case: this is a
621 /// metadata-only view op that shares bytes with its input via the
622 /// Layout side-table, so it preserves any upstream
623 /// strided/transposed/broadcast layout instead of triggering an
624 /// auto-Contiguize.
625 Unsqueeze { dim: usize },
626 /// Drop a size-1 dimension at position `dim` (range `0..rank`).
627 /// Inverse of [`Op::Unsqueeze`]; metadata-only view that shares
628 /// bytes with its input via the Layout side-table. Panics at build
629 /// time if the dim's size isn't 1 (mirrors Unsqueeze's bounds
630 /// check — graph-builder validation, not runtime).
631 Squeeze { dim: usize },
632 /// Sum-reduce a tensor to a smaller shape by summing along any dims
633 /// where the source was broadcast against the target. This is the
634 /// backward rule for `BroadcastTo` and is symmetric with it: both ops
635 /// are each other's gradient. For a source shape `[2, 3, 4]` being
636 /// reduced to `[3, 4]`, the sum is along dim 0; for `[2, 3, 4]` to
637 /// `[2, 1, 4]`, the sum is along dim 1 while keeping the dim.
638 ReduceSumTo(Shape),
639 /// Max-reduce a tensor to a smaller shape, the maximum-symmetric
640 /// counterpart of [`Op::ReduceSumTo`]. The target shape must be
641 /// broadcast-compatible into the source: along any axis where the
642 /// padded target is 1 (or absent), the input is reduced via max;
643 /// other axes carry through. Used by lowering rules (notably
644 /// SoftmaxLastDim's max-subtract step) and as the keepdim form of
645 /// per-axis max reductions.
646 ///
647 /// Backward through max-selection routes the upstream gradient
648 /// only to the argmax position, which requires holding onto the
649 /// original input and recomputing the argmax. PR 3.5 ships this
650 /// op without a backward rule (panics cleanly on `.backward()`,
651 /// matching `Op::ArgMaxDim`'s precedent); add the backward when a
652 /// real consumer needs it.
653 ReduceMaxTo(Shape),
654
655 // --- reductions to a scalar ---
656 /// Sum of every element, producing a rank-0 tensor.
657 SumAll,
658 /// Maximum of every element, producing a rank-0 tensor.
659 MaxAll,
660 /// Minimum of every element, producing a rank-0 tensor.
661 MinAll,
662 /// Arithmetic mean of every element, producing a rank-0 tensor.
663 MeanAll,
664
665 // --- reductions along one dimension ---
666 /// Sum along the given dim; the reduced dim is removed from the output.
667 SumDim(usize),
668 /// Max along the given dim; the reduced dim is removed from the output.
669 MaxDim(usize),
670 /// Min along the given dim; the reduced dim is removed from the output.
671 MinDim(usize),
672 /// Mean along the given dim; the reduced dim is removed from the output.
673 MeanDim(usize),
674
675 // --- compositions ---
676 //
677 // Phase 7.6 step 5 (2026-05-11): the per-fused-op primitive variants
678 // (SoftmaxLastDim, LayerNormLastDim { eps }, RmsNormLastDim { eps },
679 // Rope, Conv2D { … }, FusedLinear) plus the four backward-helper
680 // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
681 // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
682 // The closed primitive set no longer carries fused-op concepts;
683 // every fused op flows through `Op::Fused(FusedOpId, FusedOpParams)`.
684 // See `docs/fused-op-registry.md` for the migration record.
685
686 // Phase 7.6 step 5 (continued, 2026-05-11): `QMatMul {
687 // quant_type, k, n }` dropped — flows through
688 // `Op::Fused(QMATMUL, FusedOpParams::QMatMul { … })`.
689
690 // --- backward helpers ---
691 //
692 // Phase 7.6 step 5 (2026-05-11): the four migrated backward-helper
693 // variants (SoftmaxLastDimBackward, LayerNormLastDimBackward,
694 // RmsNormLastDimBackward, ReduceMaxToBackward) have been dropped.
695 // They flow through `Op::Fused(FusedOpId, FusedOpParams)` per the
696 // registry split. LogSoftmaxLastDimBackward is the only remaining
697 // backward-helper primitive variant — its forward primitive
698 // (`Op::LogSoftmaxLastDim`, not in scope for step 5) hasn't migrated
699 // to the registry yet, so the backward stays primitive too.
700 //
701 /// LogSoftmax-last-dim backward. Inputs: `(forward_log_softmax_output,
702 /// upstream)`. Output: the gradient of the input to log-softmax.
703 /// Formula: `g - exp(y) * sum(g, last_dim, keepdim=true)` where
704 /// `y` is the forward log-softmax output and `g` is the upstream
705 /// gradient. Independent of `Op::SoftmaxLastDimBackward` because
706 /// the closed-form rule uses `exp(y) = softmax(x)` directly, not
707 /// the upstream-times-softmax composition.
708 LogSoftmaxLastDimBackward,
709
710 // --- integer-producing reductions ---
711 //
712 // These reduce a float tensor along one dim and emit a U32 tensor of
713 // indices. Non-differentiable — they exist for classification
714 // prediction and similar discrete workloads, not as part of any
715 // training graph. Backward panics cleanly if a user builds these
716 // inside a graph they then differentiate.
717 /// Index of the maximum along `dim`. Output: U32 with the reduced
718 /// dim removed.
719 ArgMaxDim(usize),
720 /// Index of the minimum along `dim`. Output: U32 with the reduced
721 /// dim removed.
722 ArgMinDim(usize),
723
724 // --- shape manipulation ---
725 /// Concatenate two tensors along `dim`. Both must have the same rank,
726 /// same dtype, and equal sizes in every dim except `dim`.
727 Concat { dim: usize },
728 /// Slice (narrow) a tensor along `dim`: take elements `[start, start+len)`.
729 /// Output shape: same as input but with `dim` shrunk to `len`.
730 Slice {
731 dim: usize,
732 start: usize,
733 len: usize,
734 },
735
736 // --- scalar-by-tensor ops ---
737 //
738 // These exist to avoid building a full-shape const just to add or
739 // multiply by a constant. Stored as f64 on the op and converted to
740 // the target dtype at realize time.
741 /// Add a scalar to every element.
742 AddScalar(f64),
743 /// Multiply every element by a scalar.
744 MulScalar(f64),
745 /// Raise every element to an integer power via repeated multiplication.
746 /// Works without an extra `log`/`exp` pair so it's numerically clean
747 /// for small integer exponents like squaring or cubing.
748 PowI(i32),
749 /// Clamp every element to the inclusive range `[min, max]`.
750 Clamp { min: f64, max: f64 },
751
752 // --- element-wise max/min between two tensors ---
753 /// Element-wise maximum of two tensors with matching shape.
754 Maximum,
755 /// Element-wise minimum of two tensors with matching shape.
756 Minimum,
757
758 // --- indexing ops ---
759 //
760 // These take a "data" tensor (floats) as their first input and an
761 // "index" tensor (integer) as their second input. The executor
762 // reads both operands from the cache, dispatches on the data
763 // tensor's dtype for the output, and uses the index tensor as-is.
764 /// Index-select along a single dimension with a 1-D index vector.
765 /// Output shape: same as input, but with `dim` replaced by
766 /// `indices.elem_count()`.
767 IndexSelect { dim: usize },
768 /// N-dimensional gather along `dim`. Output shape matches the index
769 /// tensor's shape. `out[..., k, ...] = data[..., indices[..., k, ...], ...]`
770 /// with `dim` being the position where the index value substitutes
771 /// for the output coordinate.
772 Gather { dim: usize },
773 /// Index-add: the backward of `IndexSelect`. Takes a base tensor,
774 /// a 1-D `U32` index vector, and a src tensor, and adds src to base
775 /// at the indexed positions along `dim`. `out[..., indices[i], ...] +=
776 /// src[..., i, ...]`. Non-indexed positions of base are copied
777 /// through unchanged. Works functionally (returns a new tensor).
778 IndexAdd { dim: usize },
779 /// Scatter-add: the backward of `Gather`. Takes a base tensor, an
780 /// N-D `U32` index tensor matching the src shape, and a src tensor,
781 /// and accumulates src values into base at positions given by
782 /// substituting `indices` at position `dim`. `out[p with dim ←
783 /// indices[p]] += src[p]`.
784 ScatterAdd { dim: usize },
785
786 /// Data-determined nonzero-index extraction — the keystone primitive
787 /// for **data-dependent dynamic shapes** (SSM autoregressive decode,
788 /// MoE sparse dispatch, MLA compressed-KV). Given an input value
789 /// tensor, produces the flat indices of its nonzero elements over a
790 /// **fixed-capacity buffer** plus the true runtime count, using the
791 /// multi-output bundle mechanism ([12-multi-output]):
792 ///
793 /// - slot 0 (primary): `indices`, shape `[capacity]`, dtype `U32`,
794 /// where `capacity = input.elem_count()` (the static worst-case
795 /// bound). The first `count` entries are the flat (row-major)
796 /// indices of the input's nonzero elements in ascending order; the
797 /// tail `[count..capacity]` is unspecified padding.
798 /// - slot 1: `count`, shape `[1]`, dtype `U32` — the number of
799 /// nonzero elements found.
800 ///
801 /// "Nonzero" means `!= 0` in the input dtype's arithmetic (a `0.0`
802 /// float, an all-zero integer). The runtime `count` is published into
803 /// the per-pass [`SymEnv`](fuel_ir::SymEnv) under `count_sym` by the
804 /// executor *after* this op realizes, so downstream ops consume it as
805 /// a [`DynScalar::Sym`] / dynamic [`Extent`](fuel_ir::shape::Extent) —
806 /// the same host-scalar-extent pattern the KV-cache `cached_len`
807 /// uses. This is the **first op whose output length is determined by
808 /// its input data**, not by build-time shapes (the [`fuel_ir::symbol::SymEnv`] bind is
809 /// the one net-new realize-time seam). Primitive (in the base map by
810 /// construction — no `decompose`). Non-differentiable: discrete
811 /// indices, backward drops gradient like `Op::Gather`'s index path.
812 NonZeroIndices { count_sym: SymId },
813
814 // --- 2-D convolution + fused linear ---
815 //
816 // Phase 7.6 step 5 (2026-05-11): `Conv2D { stride, padding, groups }`
817 // and `FusedLinear` have been dropped — both flow through
818 // `Op::Fused(FusedOpId, FusedOpParams)` per the registry split.
819 // See `fuel-graph/src/registry/{conv2d,fused_linear}.rs` for the
820 // current entry shapes.
821
822 // Phase 7.6 step 5 (continued, 2026-05-11): `FlashAttn`,
823 // `PagedAttn`, and `ConvTranspose2D` dropped — all three flow
824 // through `Op::Fused(<id>, FusedOpParams::<variant>)` per the
825 // registry split. See `fuel-graph/src/registry/{flash_attn,
826 // paged_attn, conv_transpose_2d}.rs`.
827
828 // --- cross-device transfer ---
829 /// Copy the input tensor to a specific device. Source stays
830 /// resident (non-destructive). Source device is implicit from
831 /// `inputs[0]`'s current residency. When source and target
832 /// devices match, the backend is free to turn this into a cheap
833 /// clone; when they differ, the backend must actually transfer
834 /// the data (today: through a host buffer — Phase 3 has no P2P
835 /// fast path yet).
836 ///
837 /// Phase 3 of the unified scheduler work. The scheduler (Phase 4)
838 /// inserts these nodes automatically; users can also construct
839 /// them explicitly via `NodeHandle::copy_to_device`.
840 Copy { target: DeviceLocation },
841
842 /// Release the input tensor's device-resident storage. Produces a
843 /// zero-element marker output (NodeId placeholder for graph
844 /// bookkeeping; no meaningful data). After this op runs, the
845 /// input's device storage is gone; any subsequent reader of the
846 /// input's NodeId must get its data from a different path (a
847 /// sibling Copy output, or re-execution of the producer).
848 ///
849 /// Destructive on `inputs[0]`. Scheduler must pin `Op::Release`
850 /// to run after every other reader of its input via
851 /// [`opt::derive_ordering`].
852 ///
853 /// **Multi-output bundles** (Option C, Session 3): when
854 /// `inputs[0]` is a multi-output producer (its Storage carries a
855 /// [`fuel_ir::storage::OutputView`] bundle), the bundle
856 /// is the single eviction unit — the Release evicts the whole
857 /// bundle, not a single slot. `opt::collect_alias_set` treats
858 /// every `Op::View` of the producer as part of the producer's
859 /// alias set, so `derive_ordering` pins Release after every
860 /// reader of every View; the bundle drops only when the LAST
861 /// View consumer finishes. Op::ViewOwned consumers may run
862 /// freely after Release: their forward memcpy ran before the
863 /// Release fires (data-dep edge), and the resulting standalone
864 /// Storage is independent of the producer's bundle. Per-slot
865 /// eviction (releasing one slot's bytes while another stays
866 /// live) is intentionally a follow-up — v1 keeps the bundle as
867 /// a single unit.
868 Release,
869
870 /// Transfer the input tensor to `target` device, destroying the
871 /// source in the process. Semantically equivalent to
872 /// `Op::Copy { target }` followed by `Op::Release` on the source,
873 /// with the explicit guarantee that backends MAY fast-path the
874 /// fused form as a single transfer (e.g., a zero-copy handoff if
875 /// source and target are the same memory type).
876 ///
877 /// Output is a fresh tensor on `target` with the input's shape
878 /// and dtype. Destructive on `inputs[0]`; the scheduler pins this
879 /// op to run after every non-destructive reader of the source via
880 /// [`opt::derive_ordering`].
881 Move { target: DeviceLocation },
882
883 /// In-place scatter write: copies `inputs[1]`'s bytes into a
884 /// rectangular slab of `inputs[0]`'s storage, defined per-dim by
885 /// `ranges[i] = (start, end)`. After the op runs, `inputs[0]`'s
886 /// bytes inside the slab are replaced; bytes outside the slab are
887 /// untouched.
888 ///
889 /// Shape contract: `inputs[0].rank() == inputs[1].rank() ==
890 /// ranges.len()`. For each axis `i`,
891 /// `inputs[1].dims()[i] == ranges[i].1 - ranges[i].0`, and
892 /// `ranges[i].1 <= inputs[0].dims()[i]`. Dtypes must match.
893 ///
894 /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
895 /// Layout — same shape, same bytes, post-write. Consumers that
896 /// want a sub-extent of the destination compose an explicit
897 /// `Op::Slice` after the write (WriteSlice does not encode
898 /// post-write extents).
899 ///
900 /// Destructive on `inputs[0]` (the destination is consumed; only
901 /// the write op's output NodeId may read its bytes afterward).
902 /// Non-destructive on `inputs[1]`. The scheduler pins this op to
903 /// run after every other reader of the destination via
904 /// [`opt::derive_ordering`].
905 ///
906 /// Phase E.3.2: introduced to back persistent KV-cache writes
907 /// (`InferenceContext` + `KvCache`). Non-differentiable; backward
908 /// panics — KV-cache writes are forward-only.
909 ///
910 /// `dyn_offset` (Phase D symbolic extents): `None` ⇒ fully static
911 /// (`ranges` alone defines the slab — today's behavior). `Some((axis,
912 /// off))` ⇒ the destination start on `axis` is `off.resolve(env)`
913 /// against the per-pass [`fuel_ir::SymEnv`] at realize,
914 /// overriding `ranges[axis].0`; the slab width on that axis stays
915 /// `ranges[axis].1 - ranges[axis].0`. This is the input-determined
916 /// dynamic-offset path (a [`DynScalar`] over the one `SymEnv`),
917 /// distinct from [`Op::WriteSliceRotating`]'s data-determined
918 /// position (a tensor input). It backs the persistent decode
919 /// KV-cache write, whose append offset (`cached_len`) is a per-token
920 /// runtime value over a fixed-capacity buffer, so the graph
921 /// structure stays identical across tokens and the plan is reused.
922 /// Build a node with this set via [`NodeHandle::write_slice_dyn`]; the
923 /// resolved `offset + width` is bounds-checked against the
924 /// destination capacity at realize (a typed error, never a panic).
925 WriteSlice {
926 ranges: Vec<(usize, usize)>,
927 dyn_offset: Option<(usize, DynScalar)>,
928 },
929
930 /// Like [`Op::WriteSlice`] but the `axis` axis wraps modulo
931 /// `modulus`. The dynamic write position comes through `inputs[2]`
932 /// (rank-0 U32); at realize time the kernel computes
933 /// `start = position % modulus` and writes `inputs[1]` into
934 /// `inputs[0]` at the wrapped offset, splitting across the
935 /// boundary if `start + write_len > modulus`.
936 ///
937 /// Inputs:
938 /// - `inputs[0]`: destination tensor (the rotating buffer). Shape
939 /// on `axis` is the full storage extent — typically equal to
940 /// `modulus`.
941 /// - `inputs[1]`: source slice. Shape on non-rotating axes is the
942 /// slab in `ranges`; shape on `axis` is the write length.
943 /// - `inputs[2]`: dynamic write position, rank-0 `U32`. Wrapped
944 /// modulo `modulus` inside the kernel — callers pass the
945 /// monotonic logical position (token index, etc.).
946 ///
947 /// `ranges` describes the destination slab on every axis. For the
948 /// rotating axis `axis`, `ranges[axis].0` is ignored (start is
949 /// dynamic) and `ranges[axis].1 - ranges[axis].0` must equal
950 /// `inputs[1].dims()[axis]` (the write length). For other axes
951 /// the same shape contract as `Op::WriteSlice` applies.
952 ///
953 /// Output is a marker that adopts `inputs[0]`'s Storage Arc and
954 /// Layout, post-write. Destructive on `inputs[0]`; scheduled like
955 /// `Op::WriteSlice`.
956 ///
957 /// Phase C of the eager-NodeHandle retirement program. Backs
958 /// sliding-window KV caches (Mistral / Phi-3 sliding-window /
959 /// sliding-window Qwen). Non-differentiable; backward panics.
960 WriteSliceRotating {
961 axis: usize,
962 modulus: usize,
963 ranges: Vec<(usize, usize)>,
964 },
965
966 /// Like [`Op::WriteSlice`] but the start offset on `axis` is a
967 /// **device-resident** scalar read from `inputs[2]` (rank-0 `I64`)
968 /// at kernel-launch time — NOT host-resolved. This is the CUDA-
969 /// graph-capturable append: under capture, the offset buffer is
970 /// updated by a per-token fixed-address H2D memcpy before each
971 /// replay, so the captured graph is reused across decode steps
972 /// while the write lands at the live position. No modulo wrap
973 /// (unlike [`Op::WriteSliceRotating`]); the offset is the raw
974 /// start (`cached_len`).
975 ///
976 /// Inputs:
977 /// - `inputs[0]`: destination tensor (the fixed-capacity buffer).
978 /// - `inputs[1]`: source slab. Shape on non-`axis` axes is the slab
979 /// in `ranges`; shape on `axis` is the write width.
980 /// - `inputs[2]`: device offset, rank-0 `I64` — the start on `axis`.
981 /// Overrides `ranges[axis].0` (which is a placeholder ignored by
982 /// the kernel).
983 ///
984 /// `ranges` describes the destination slab on every axis. For the
985 /// dynamic axis, `ranges[axis].0` is ignored (start is device-
986 /// resident) and `ranges[axis].1 - ranges[axis].0` must equal
987 /// `inputs[1].dims()[axis]` (the write width). For other axes the
988 /// same shape contract as [`Op::WriteSlice`] applies.
989 ///
990 /// **Bounds are the caller's contract**: the kernel reads the start
991 /// device-side and does NOT clamp (clamping would perturb the index
992 /// math vs the static path). `offset + width <= dest_dims[axis]`
993 /// must hold — guaranteed by the caller sizing the buffer's
994 /// capacity (`DecodeSession` sizes `max_seq`).
995 ///
996 /// Output adopts `inputs[0]`'s Storage Arc + Layout, post-write.
997 /// Destructive on `inputs[0]`; scheduled like `Op::WriteSlice`.
998 /// Non-differentiable; backward panics.
999 ///
1000 /// CapturedRun (the decode-latency lever, 2026-07): the device-
1001 /// resident-offset WriteSlice is form-B of baracuda's
1002 /// `write_slice_*_doff` launchers.
1003 WriteSliceDoff {
1004 axis: usize,
1005 ranges: Vec<(usize, usize)>,
1006 },
1007
1008 /// Allocate a fresh, zero-initialized Storage of the node's shape +
1009 /// dtype on `target`. Zero inputs — `Op::Alloc` is a *source* op
1010 /// like [`Op::Const`], but its bytes are computed (zeros) rather
1011 /// than seeded from the host.
1012 ///
1013 /// Bridge-retirement Phase 3a (post-9c). Replaces the per-device-
1014 /// location match in `fuel-tensor::inference_context::alloc_zeroed_on`
1015 /// with a graph-level node the optimizer can see + the executor's
1016 /// `WorkItemKind::Alloc` arm dispatches per-backend.
1017 ///
1018 /// **Device-handle requirement**: the executor's Alloc arm derives
1019 /// the per-backend handle (e.g. `&CudaDevice`, `&Arc<VulkanBackend>`)
1020 /// by searching the input cache for any Storage already on
1021 /// `target`'s backend. Callers must seed the cache with at least
1022 /// one such storage before realizing an Op::Alloc on a non-CPU
1023 /// target. `fuel-tensor::pipelined_bridge::device_seed_storage` is
1024 /// the canonical seeder.
1025 Alloc { target: DeviceLocation },
1026
1027 /// Fill the input tensor's bytes with zero, in place. Aliases
1028 /// `inputs[0]`'s Storage Arc as the output (same Storage; the
1029 /// bytes are mutated). Destructive on `inputs[0]` — readers of
1030 /// the input's NodeId after this op see post-fill bytes; new
1031 /// readers should use this op's NodeId.
1032 ///
1033 /// Bridge-retirement Phase 3a follow-up. Paired with
1034 /// [`Op::Alloc`] to give the architecturally clean "alloc uninit +
1035 /// explicit zero" pipeline. Backends with native device-side
1036 /// fills (CUDA `cuMemsetD8Async`, Vulkan `vkCmdFillBuffer`)
1037 /// dispatch through their kernels; CPU does an
1038 /// `Arc::make_mut`-style in-place memset.
1039 ///
1040 /// Future extension: an `Op::Fill { value: u8 }` (or `Scalar`)
1041 /// for non-zero patterns. ZeroFill is the only variant today
1042 /// because zero is the only init pattern any current caller
1043 /// needs.
1044 ZeroFill,
1045
1046 /// Phase 7.6 single-arm delegate to the open
1047 /// [`crate::registry::FusedOpRegistry`]. The id selects which
1048 /// fused op (SoftmaxLastDim, RmsNormLastDim, FlashAttn, ...) and
1049 /// the params carry per-instance data. The registry's metadata
1050 /// side (decompose, backward identity, shape/dtype rules) lives in
1051 /// `fuel-graph::registry`; the kernel side (per-backend `KernelRef`
1052 /// + cost + precision) lives in `fuel-storage::fused`.
1053 ///
1054 /// Adding a new fused op is one registry entry plus one kernel
1055 /// function per backend that supports it — no new `Op` variant.
1056 /// Step 3 of Phase 7.6 migrates SoftmaxLastDim through this arm
1057 /// as the proof of concept.
1058 Fused(FusedOpId, FusedOpParams),
1059
1060 /// Project one logical output out of a multi-output producer node.
1061 /// The producer's realized [`Storage`] carries a
1062 /// [`fuel_ir::storage::OutputView`] side-table; this op
1063 /// reads slot `slot` of that side-table and exposes its
1064 /// dtype/shape/layout as the View node's output.
1065 ///
1066 /// Single input (the multi-output producer). Output shares the
1067 /// producer's `Arc<RwLock<Storage>>` — zero bytes copied. The
1068 /// bundle stays alive as long as any View consumer (or the
1069 /// original producer handle) holds a clone.
1070 ///
1071 /// At graph-build time, the View's shape + dtype + layout come
1072 /// from the producer's slot specs recorded via
1073 /// [`Graph::set_output_views`]; building a `View { slot }` over a
1074 /// producer that hasn't declared slot specs is a typed error
1075 /// surfaced by the View-emitting builder helper. The bundle's
1076 /// per-slot dtype is independent of the producer node's own
1077 /// `Node::dtype` (which is the bundle's primary/slot-0 dtype).
1078 ///
1079 /// Backward (see `fuel-graph::grad`): the per-slot upstream
1080 /// gradient is scattered into a zero-filled bundle of the
1081 /// producer's overall byte shape; the producer's own backward
1082 /// rule then sees a "bundle gradient" as its upstream. Until a
1083 /// real multi-output op author exists (Session 2), the backward
1084 /// rule emits an [`Op::Const`] zero of the producer's primary
1085 /// shape — the scatter-into-slot primitive lands alongside the
1086 /// first differentiable multi-output op.
1087 View { slot: u32 },
1088
1089 /// Like [`Op::View`], but copies the slot's bytes into a fresh
1090 /// standalone Storage. Costs one allocation + one slot-sized
1091 /// memcpy; the producer's bundle Arc can drop as soon as every
1092 /// outstanding `Op::View` over the same producer also drops.
1093 ///
1094 /// The planner promotes a `View` to `ViewOwned` when a slot's
1095 /// liveness substantially outlasts the rest of the bundle (the
1096 /// classic case: Mamba's `last_state` slot retained across an
1097 /// autoregressive step while `y` is consumed immediately). v1
1098 /// emits the same dispatch shape as `Op::Copy` — backend-side it's
1099 /// `Copy` with byte offset + length pulled from the slot spec.
1100 ///
1101 /// Same shape/dtype/layout inference path as `View`; same backward
1102 /// shape too (the forward already paid the copy).
1103 ViewOwned { slot: u32 },
1104
1105 /// Multi-output autograd primitive (Option C, item 4). Takes two
1106 /// inputs:
1107 /// - `inputs[0]`: a bundled tensor (typically a zero-bundle)
1108 /// - `inputs[1]`: the slot's gradient
1109 ///
1110 /// Produces a new bundled tensor identical to `inputs[0]` except
1111 /// that slot `slot`'s byte range is overlaid by `inputs[1]`'s
1112 /// bytes. The output is alias-free with respect to `inputs[0]`
1113 /// (a fresh Storage with the new bytes) so multiple
1114 /// `ScatterIntoSlot` operations on the same `bundle_zero` chain
1115 /// sequentially without aliasing pitfalls.
1116 ///
1117 /// Emitted by `Op::View` / `Op::ViewOwned` backward rules: each
1118 /// View consumer scatters its upstream gradient into a fresh
1119 /// zero-bundle, then the producer's backward receives the
1120 /// composed bundle gradient as its upstream.
1121 ///
1122 /// **Status**: IR-level primitive only in this session. No CPU
1123 /// kernel registration yet. The production multi-output SSM ops
1124 /// (SelectiveScan, SsdChunkScan) are now differentiable via the
1125 /// Op::Scan Phase-2 `lower_scans_for_backward` pre-pass (decompose →
1126 /// `Op::Scan` → `unroll_scan` → node-general autograd), which lowers
1127 /// them to primitives BEFORE the reverse walk — so the autograd
1128 /// differentiates the unrolled `View` projections directly and never
1129 /// reaches a `ScatterIntoSlot` realization on the SSM path.
1130 ScatterIntoSlot { slot: u32 },
1131
1132 /// In-place multi-path (phi/merge) node — the arena representation
1133 /// of the optimized form's divergent-then-reconvergent routes.
1134 ///
1135 /// A `Branch` node's divergent "arms" are encoded in the node's
1136 /// existing `inputs: Vec<NodeId>`: each input is the *exit* of one
1137 /// candidate route, and `reconverge_at` names the explicit node at
1138 /// which those routes merge back into a single value. Because the
1139 /// multi-path structure is an arena fact rather than an overlay, it
1140 /// persists, compacts, graph-walks, and path-filters exactly like
1141 /// any other node; a graph with **zero** `Op::Branch` nodes is
1142 /// exactly today's single-route graph (back-compatible by
1143 /// construction).
1144 ///
1145 /// **Inert until PR-A1.** This variant is the PR-A0 scaffold: the
1146 /// closed `Op` enum carries it and every exhaustive match handles
1147 /// it, but nothing constructs it yet. The `open_branch` /
1148 /// `add_arm` / `finalize_branches` builders (with build-time
1149 /// validation: reconverge must descend from the diverge point, arms
1150 /// internally disjoint, cast-to-uniform at reconverge) land in
1151 /// PR-A1. Until then, accessors return a constant ("branch") and
1152 /// fallible paths (shape inference, autograd, lowering) return a
1153 /// descriptive `Err` rather than panicking.
1154 Branch { reconverge_at: NodeId },
1155
1156 /// Fuel's first sub-graph-carrying primitive: a bounded `lax.scan`-shaped
1157 /// recurrence `scan(body, init_carry, xs, consts) -> (final_carry, ys)`.
1158 ///
1159 /// The body is encoded in this node's own `inputs`, exactly like
1160 /// [`Op::Branch`]'s arms. Node layout:
1161 /// `inputs = [ init_carry_0..init_carry_{n_carries-1}, xs_0..xs_{n_xs-1},
1162 /// consts..., body_new_carry_0..body_new_carry_{n_carries-1}, body_y ]`
1163 /// — the two body-exit NodeIds are the LAST two inputs, so `base_map_hash`,
1164 /// `topo_order_multi`, and reachability see the body for free. The body
1165 /// references `Op::ScanPlaceholder{Carry,0}` for the per-step carry and
1166 /// `Op::ScanPlaceholder{Elem,i}` for the per-step slice of `xs[i]`; consts
1167 /// are referenced by real NodeId. `n_carries` carries are threaded; the
1168 /// body references `ScanPlaceholder{Carry,k}` for carry `k` (GAP-303 —
1169 /// `n_carries = 1` is the v1 single-carry model).
1170 ///
1171 /// An optimization/verification-time node: it never reaches the executor
1172 /// un-lowered (the SSM decompose emits it, but the executor dispatches the
1173 /// fused op to its kernel; `unroll_scan` materializes primitives on demand
1174 /// for the verify oracle / kernel-absent fallback). No `LoweringRule`
1175 /// matches it — it is a terminal in the base map, which is correct: it IS
1176 /// the primitive. Always a 2-slot bundle (slot 0 = stacked `ys`, slot 1 =
1177 /// final carry). `early_exit` is Phase-2 (see [`ScanPredicate`]).
1178 Scan {
1179 /// How many recurrent carries this scan threads. Symmetric with
1180 /// `n_xs`: the carry NODES live in `inputs` (a positional block, see
1181 /// the layout above); this field is only their COUNT, exactly as
1182 /// `n_xs` is only the count of the `xs` block.
1183 ///
1184 /// GAP-303: `1` reproduces the v1 single-carry model exactly.
1185 n_carries: usize,
1186 n_xs: usize,
1187 bound: usize,
1188 emit: ScanEmit,
1189 early_exit: Option<ScanPredicate>,
1190 },
1191
1192 /// Inert body-hole leaf for [`Op::Scan`] (no inputs). Substituted by
1193 /// `unroll_scan` per step. Never directly realized.
1194 ScanPlaceholder { role: ScanRole, index: usize },
1195}
1196
1197/// What a [`Op::Scan`] emits. `All` stacks the per-step `body_y` over the
1198/// bound (slot 0); `Final` returns only the final carry (slot 1). The op
1199/// always produces the 2-slot bundle; `emit` selects the builder's default
1200/// projection. (`Op::Reduce` is `Op::Scan { emit: Final }` conceptually —
1201/// no separate variant.)
1202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1203pub enum ScanEmit {
1204 All,
1205 Final,
1206}
1207
1208/// Which body hole a [`Op::ScanPlaceholder`] stands in for. `Carry` is the
1209/// per-step recurrent carry (always index 0 in v1's single-carry model);
1210/// `Elem` is the per-step slice of `xs[index]`.
1211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1212pub enum ScanRole {
1213 Carry,
1214 Elem,
1215}
1216
1217/// Phase-1 placeholder for [`Op::Scan`]'s `early_exit` field. The FIELD is
1218/// defined now so the enum shape is final (one `03-ir` MAJOR bump); the
1219/// data-dependent early-exit MECHANISM is Phase 2. It is never `Some` on any
1220/// live Phase-1 path; if a realize/lowering path sees `Some`, that path
1221/// returns a clear `Err` (a surfaced Phase-2 gap), never a panic.
1222#[derive(Debug, Clone, PartialEq)]
1223pub struct ScanPredicate;
1224
1225impl Op {
1226 /// Index into `inputs` that this op destroys on execution. `None`
1227 /// means the op is non-destructive — every input remains readable
1228 /// after the op completes. Destructive ops need the scheduler to
1229 /// pin them to run after all other readers of the destroyed input,
1230 /// via ordering edges derived by [`opt::derive_ordering`].
1231 pub fn destructive_input(&self) -> Option<usize> {
1232 match self {
1233 // --- Destructive: the op writes through input 0 in place, so every
1234 // reader of input 0 (and its view-aliases) must be scheduled BEFORE
1235 // it (`opt::derive_ordering`). ---
1236 Op::Release
1237 | Op::Move { .. }
1238 | Op::WriteSlice { .. }
1239 | Op::WriteSliceRotating { .. }
1240 | Op::WriteSliceDoff { .. }
1241 | Op::ZeroFill
1242 | Op::ReluInplace
1243 | Op::SiluInplace
1244 | Op::GeluTanhInplace
1245 | Op::TanhInplace
1246 | Op::SigmoidInplace
1247 | Op::NegInplace
1248 | Op::AbsInplace
1249 | Op::SqrInplace
1250 | Op::SqrtInplace
1251 | Op::RsqrtInplace
1252 | Op::RecipInplace
1253 | Op::ExpInplace
1254 | Op::LogInplace
1255 | Op::SinInplace
1256 | Op::CosInplace
1257 | Op::SignInplace
1258 | Op::FloorInplace
1259 | Op::CeilInplace
1260 | Op::RoundInplace
1261 | Op::ErfInplace
1262 | Op::GeluInplace
1263 | Op::ClampInplace { .. }
1264 | Op::PowIInplace(_) => Some(0),
1265
1266 // --- Fused ops declare destructiveness as a MANDATORY
1267 // `FusedOpEntry::destructive_input` field (registry-declared, not
1268 // hardcoded here), so the fact lives with the thing and cannot drift.
1269 // Total by construction: a compile-time fused op cannot be registered
1270 // without the field; a runtime-registered fused id is not in the
1271 // compile-time registry and its region is a functional recipe (the
1272 // PatternNode grammar cannot express a destructive op), so `entry` is
1273 // `None` there and the op is non-destructive. GAP-076. ---
1274 Op::Fused(id, _) => crate::registry::default_registry()
1275 .entry(*id)
1276 .and_then(|e| e.destructive_input),
1277
1278 // --- Non-destructive primitives, listed EXHAUSTIVELY (no wildcard)
1279 // so adding an `Op` variant fails to compile here until it is
1280 // classified (`Op` is EXHAUSTIVE-BY-DESIGN — see the marker on
1281 // `enum Op`). A silent `_ => None` was the GAP-076 hazard: a future
1282 // destructive op would read as non-destructive and the scheduler
1283 // would drop its ordering edges — an intermittent data race that
1284 // points nowhere near this function. ---
1285 Op::Const
1286 | Op::Iota { .. }
1287 | Op::Add
1288 | Op::Sub
1289 | Op::Mul
1290 | Op::Div
1291 | Op::Neg
1292 | Op::Sqr
1293 | Op::Sqrt
1294 | Op::Exp
1295 | Op::Log
1296 | Op::Sin
1297 | Op::Cos
1298 | Op::Tanh
1299 | Op::Sigmoid
1300 | Op::Silu
1301 | Op::GeluTanh
1302 | Op::Relu
1303 | Op::Step
1304 | Op::Recip
1305 | Op::Abs
1306 | Op::Equal
1307 | Op::Ne
1308 | Op::Lt
1309 | Op::Le
1310 | Op::Gt
1311 | Op::Ge
1312 | Op::Where
1313 | Op::Floor
1314 | Op::Ceil
1315 | Op::Round
1316 | Op::Sign
1317 | Op::Erf
1318 | Op::Gelu
1319 | Op::Pow
1320 | Op::Rsqrt
1321 | Op::Rem
1322 | Op::Flip { .. }
1323 | Op::Roll { .. }
1324 | Op::CumSum { .. }
1325 | Op::Triu { .. }
1326 | Op::Tril { .. }
1327 | Op::LogSoftmaxLastDim
1328 | Op::MaskedFill { .. }
1329 | Op::Pad { .. }
1330 | Op::PadBackward { .. }
1331 | Op::MatMul
1332 | Op::Transpose
1333 | Op::Permute(_)
1334 | Op::Cast(_)
1335 | Op::BroadcastTo(_)
1336 | Op::Reshape(_)
1337 | Op::Contiguize
1338 | Op::Unsqueeze { .. }
1339 | Op::Squeeze { .. }
1340 | Op::ReduceSumTo(_)
1341 | Op::ReduceMaxTo(_)
1342 | Op::SumAll
1343 | Op::MaxAll
1344 | Op::MinAll
1345 | Op::MeanAll
1346 | Op::SumDim(_)
1347 | Op::MaxDim(_)
1348 | Op::MinDim(_)
1349 | Op::MeanDim(_)
1350 | Op::LogSoftmaxLastDimBackward
1351 | Op::ArgMaxDim(_)
1352 | Op::ArgMinDim(_)
1353 | Op::Concat { .. }
1354 | Op::Slice { .. }
1355 | Op::AddScalar(_)
1356 | Op::MulScalar(_)
1357 | Op::PowI(_)
1358 | Op::Clamp { .. }
1359 | Op::Maximum
1360 | Op::Minimum
1361 | Op::IndexSelect { .. }
1362 | Op::Gather { .. }
1363 | Op::IndexAdd { .. }
1364 | Op::ScatterAdd { .. }
1365 | Op::NonZeroIndices { .. }
1366 | Op::Copy { .. }
1367 | Op::Alloc { .. }
1368 | Op::View { .. }
1369 | Op::ViewOwned { .. }
1370 | Op::ScatterIntoSlot { .. }
1371 | Op::Branch { .. }
1372 | Op::Scan { .. }
1373 | Op::ScanPlaceholder { .. } => None,
1374 }
1375 }
1376
1377 /// Short human-readable name for this op — used by executor error
1378 /// messages to identify the offending graph node without spilling
1379 /// all of `Debug`'s field contents. Keeps panic messages one-liner-
1380 /// friendly while still telling you which kind of op blew up.
1381 pub fn short_name(&self) -> &'static str {
1382 op_short_name(self)
1383 }
1384
1385 /// Whether this op is a metadata-only view: its output shares bytes
1386 /// with its single input, reinterpreting them through new strides
1387 /// and/or offset. Executors realize these without allocating new
1388 /// storage — they wrap the input's Storage in a fresh Layout.
1389 ///
1390 /// Note that `Op::Reshape` is *not* a view op. Reshape produces
1391 /// contiguous output: zero-copy when its input is contiguous, but
1392 /// it materializes via auto-Contiguize when the input is strided.
1393 /// The other shape-altering ops in this set are always view-shaped
1394 /// regardless of the input layout.
1395 pub fn is_view_op(&self) -> bool {
1396 matches!(
1397 self,
1398 Op::Transpose
1399 | Op::Permute(_)
1400 | Op::BroadcastTo(_)
1401 | Op::Slice { .. }
1402 | Op::Unsqueeze { .. }
1403 | Op::Squeeze { .. }
1404 | Op::Flip { .. }
1405 )
1406 }
1407}
1408
1409/// Compute the output [`Layout`] of a metadata-only view op from its
1410/// input layout + the op variant. Returns `Err` if the op variant
1411/// isn't a view op (caller's contract — typically guarded by
1412/// [`Op::is_view_op`]).
1413///
1414/// Used by [`Graph::push`] to auto-populate the layout side-table for
1415/// view-op nodes at construction time, and by lowering rules in
1416/// [`opt`] that emit view-op nodes and need to populate the side-table
1417/// for them. The compiler reads the resulting layouts via
1418/// [`Graph::layout`] without re-deriving.
1419pub fn derive_view_output_layout(op: &Op, input_layout: &Layout) -> Result<Layout, fuel_ir::Error> {
1420 match op {
1421 Op::Transpose => {
1422 let rank = input_layout.shape().rank();
1423 if rank < 2 {
1424 return Err(fuel_ir::Error::Msg(format!(
1425 "Op::Transpose requires rank >= 2, input rank is {rank}",
1426 ))
1427 .bt());
1428 }
1429 input_layout.transpose(rank - 2, rank - 1)
1430 }
1431 Op::Permute(axes) => input_layout.permute(axes),
1432 Op::BroadcastTo(target_shape) => input_layout.broadcast_as(target_shape.clone()),
1433 Op::Slice { dim, start, len } => input_layout.narrow(*dim, *start, *len),
1434 Op::Unsqueeze { dim } => input_layout.unsqueeze(*dim),
1435 Op::Squeeze { dim } => input_layout.squeeze(*dim),
1436 Op::Flip { dim } => input_layout.flip(*dim),
1437 other => Err(fuel_ir::Error::Msg(format!(
1438 "derive_view_output_layout called with non-view op {other:?}",
1439 ))
1440 .bt()),
1441 }
1442}
1443
1444fn op_short_name(op: &Op) -> &'static str {
1445 match op {
1446 Op::Const => "Const",
1447 Op::Iota { .. } => "Iota",
1448 Op::Add => "Add",
1449 Op::Sub => "Sub",
1450 Op::Mul => "Mul",
1451 Op::Div => "Div",
1452 Op::Neg => "Neg",
1453 Op::Sqr => "Sqr",
1454 Op::Sqrt => "Sqrt",
1455 Op::Exp => "Exp",
1456 Op::Log => "Log",
1457 Op::Sin => "Sin",
1458 Op::Cos => "Cos",
1459 Op::Tanh => "Tanh",
1460 Op::Sigmoid => "Sigmoid",
1461 Op::Silu => "Silu",
1462 Op::GeluTanh => "GeluTanh",
1463 Op::Relu => "Relu",
1464 Op::Step => "Step",
1465 Op::Recip => "Recip",
1466 Op::Abs => "Abs",
1467 Op::ReluInplace => "ReluInplace",
1468 Op::SiluInplace => "SiluInplace",
1469 Op::GeluTanhInplace => "GeluTanhInplace",
1470 Op::TanhInplace => "TanhInplace",
1471 Op::SigmoidInplace => "SigmoidInplace",
1472 Op::NegInplace => "NegInplace",
1473 Op::AbsInplace => "AbsInplace",
1474 Op::SqrInplace => "SqrInplace",
1475 Op::SqrtInplace => "SqrtInplace",
1476 Op::RsqrtInplace => "RsqrtInplace",
1477 Op::RecipInplace => "RecipInplace",
1478 Op::ExpInplace => "ExpInplace",
1479 Op::LogInplace => "LogInplace",
1480 Op::SinInplace => "SinInplace",
1481 Op::CosInplace => "CosInplace",
1482 Op::SignInplace => "SignInplace",
1483 Op::FloorInplace => "FloorInplace",
1484 Op::CeilInplace => "CeilInplace",
1485 Op::RoundInplace => "RoundInplace",
1486 Op::ErfInplace => "ErfInplace",
1487 Op::GeluInplace => "GeluInplace",
1488 Op::ClampInplace { .. } => "ClampInplace",
1489 Op::PowIInplace(_) => "PowIInplace",
1490 Op::Equal => "Equal",
1491 Op::Ne => "Ne",
1492 Op::Lt => "Lt",
1493 Op::Le => "Le",
1494 Op::Gt => "Gt",
1495 Op::Ge => "Ge",
1496 Op::Where => "Where",
1497 Op::Floor => "Floor",
1498 Op::Ceil => "Ceil",
1499 Op::Round => "Round",
1500 Op::Sign => "Sign",
1501 Op::Erf => "Erf",
1502 Op::Gelu => "Gelu",
1503 Op::Pow => "Pow",
1504 Op::Rsqrt => "Rsqrt",
1505 Op::Rem => "Rem",
1506 Op::Flip { .. } => "Flip",
1507 Op::Roll { .. } => "Roll",
1508 Op::CumSum { .. } => "CumSum",
1509 Op::Triu { .. } => "Triu",
1510 Op::Tril { .. } => "Tril",
1511 Op::LogSoftmaxLastDim => "LogSoftmaxLastDim",
1512 Op::MaskedFill { .. } => "MaskedFill",
1513 Op::Pad { .. } => "Pad",
1514 Op::PadBackward { .. } => "PadBackward",
1515 Op::MatMul => "MatMul",
1516 Op::Transpose => "Transpose",
1517 Op::Permute(_) => "Permute",
1518 Op::Cast(_) => "Cast",
1519 Op::BroadcastTo(_) => "BroadcastTo",
1520 Op::Reshape(_) => "Reshape",
1521 Op::Contiguize => "Contiguize",
1522 Op::Unsqueeze { .. } => "Unsqueeze",
1523 Op::Squeeze { .. } => "Squeeze",
1524 Op::ReduceSumTo(_) => "ReduceSumTo",
1525 Op::ReduceMaxTo(_) => "ReduceMaxTo",
1526 Op::SumAll => "SumAll",
1527 Op::MaxAll => "MaxAll",
1528 Op::MinAll => "MinAll",
1529 Op::MeanAll => "MeanAll",
1530 Op::SumDim(_) => "SumDim",
1531 Op::MaxDim(_) => "MaxDim",
1532 Op::MinDim(_) => "MinDim",
1533 Op::MeanDim(_) => "MeanDim",
1534 Op::LogSoftmaxLastDimBackward => "LogSoftmaxLastDimBackward",
1535 Op::ArgMaxDim(_) => "ArgMaxDim",
1536 Op::ArgMinDim(_) => "ArgMinDim",
1537 Op::Concat { .. } => "Concat",
1538 Op::Slice { .. } => "Slice",
1539 Op::AddScalar(_) => "AddScalar",
1540 Op::MulScalar(_) => "MulScalar",
1541 Op::PowI(_) => "PowI",
1542 Op::Clamp { .. } => "Clamp",
1543 Op::Maximum => "Maximum",
1544 Op::Minimum => "Minimum",
1545 Op::IndexSelect { .. } => "IndexSelect",
1546 Op::Gather { .. } => "Gather",
1547 Op::IndexAdd { .. } => "IndexAdd",
1548 Op::ScatterAdd { .. } => "ScatterAdd",
1549 Op::NonZeroIndices { .. } => "NonZeroIndices",
1550 Op::Copy { .. } => "Copy",
1551 Op::Release => "Release",
1552 Op::Move { .. } => "Move",
1553 Op::WriteSlice { .. } => "WriteSlice",
1554 Op::WriteSliceRotating { .. } => "WriteSliceRotating",
1555 Op::WriteSliceDoff { .. } => "WriteSliceDoff",
1556 Op::Alloc { .. } => "Alloc",
1557 Op::ZeroFill => "ZeroFill",
1558 // Phase 7.6: registry-extended fused ops. Step 3 wires per-id
1559 // names through a static lookup; until then, all fused ops
1560 // share one short name. Distinguishing in error messages is
1561 // future work — `id` is in the Debug repr.
1562 Op::Fused(_, _) => "Fused",
1563 Op::View { .. } => "View",
1564 Op::ViewOwned { .. } => "ViewOwned",
1565 Op::ScatterIntoSlot { .. } => "ScatterIntoSlot",
1566 // PR-A0 inert scaffold (the multi-path phi/merge node).
1567 Op::Branch { .. } => "Branch",
1568 Op::Scan { .. } => "Scan",
1569 Op::ScanPlaceholder { .. } => "ScanPlaceholder",
1570 }
1571}
1572
1573/// G2 helper: element count of a `HostBuffer`. Used by NodeHandle's
1574/// constructors to validate that the supplied data matches the
1575/// declared shape's `elem_count` before allocating Storage.
1576fn host_buffer_elem_count(buf: &fuel_ir::HostBuffer) -> usize {
1577 use fuel_ir::HostBuffer;
1578 match buf {
1579 HostBuffer::F32(v) => v.len(),
1580 HostBuffer::F64(v) => v.len(),
1581 HostBuffer::BF16(v) => v.len(),
1582 HostBuffer::F16(v) => v.len(),
1583 HostBuffer::U8(v) => v.len(),
1584 HostBuffer::U32(v) => v.len(),
1585 HostBuffer::I64(v) => v.len(),
1586 other => panic!(
1587 "NodeHandle::from_*: unsupported host-buffer dtype {:?}",
1588 other.dtype(),
1589 ),
1590 }
1591}
1592
1593/// A single node in the graph: an operation and the IDs of its inputs.
1594/// The node also caches its output shape and dtype so downstream builders
1595/// can validate without walking back through the graph.
1596#[derive(Debug, Clone)]
1597pub struct Node {
1598 pub op: Op,
1599 pub inputs: Vec<NodeId>,
1600 pub shape: Shape,
1601 pub dtype: DType,
1602}
1603
1604/// How a node's storage is shared and how long it lives — its **storage
1605/// class** ([03-ir §"Storage classes and sessions"]). A node is a
1606/// structural fact and does not need storage to exist; when storage *is*
1607/// attached, its class governs sharing and lifetime so one optimized graph
1608/// can serve many concurrent sessions (weights shared, session state
1609/// `SessionId`-keyed, activations per-realize scratch).
1610///
1611/// The class is **inferred from the op** ([`infer_storage_class`]) with an
1612/// **explicit override** recorded in the graph's `storage_class` side-table
1613/// — e.g. KV-cache placeholder `Op::Const`s, which are session state, not
1614/// shared weights.
1615///
1616/// Phase D substrate (PR-D1): the classification is recorded but not yet
1617/// consumed by realize. Session keying (D2) and the persistent decode graph
1618/// (D3–D5) build on it.
1619#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1620pub enum StorageClass {
1621 /// Weights / constants: one storage for the whole model, identical
1622 /// across all sessions; keyed by `NodeId`. The op-inferred default for
1623 /// `Op::Const`.
1624 Shared,
1625 /// Per-session durable buffers (KV-caches + explicit cache-write
1626 /// targets): one storage per session, keyed by `(NodeId, SessionId)`.
1627 /// The op-inferred default for the in-place cache-write ops
1628 /// (`Op::WriteSlice` / `Op::WriteSliceRotating`); KV-cache placeholder
1629 /// `Op::Const`s take it via an explicit override.
1630 SessionState,
1631 /// Activations / scratch: ephemeral, allocated per realize and freed
1632 /// after use; never persisted. The op-inferred default for everything
1633 /// else. A transient value may cross devices mid-realize (a D2D
1634 /// `Op::Copy`) but never crosses to disk.
1635 Transient,
1636}
1637
1638/// The op-inferred storage class for a node, **before** any explicit
1639/// override (see [`StorageClass`] and [`Graph::storage_class`]):
1640/// - `Op::Const` → [`StorageClass::Shared`] (weights);
1641/// - `Op::WriteSlice` / `Op::WriteSliceRotating` → [`StorageClass::SessionState`]
1642/// (they write into a per-session durable buffer);
1643/// - everything else → [`StorageClass::Transient`].
1644pub fn infer_storage_class(op: &Op) -> StorageClass {
1645 match op {
1646 Op::Const => StorageClass::Shared,
1647 Op::WriteSlice { .. } | Op::WriteSliceRotating { .. } | Op::WriteSliceDoff { .. } => {
1648 StorageClass::SessionState
1649 }
1650 _ => StorageClass::Transient,
1651 }
1652}
1653
1654/// The graph arena. Stores every node added during a computation-building
1655/// session. Nodes are append-only and indexed by [`NodeId`].
1656///
1657/// Placement metadata (`DeviceLocation` per node) lives in a side-table
1658/// so existing `Node { ... }` construction sites don't need to be
1659/// modified. This is the Phase-1 shape: placements are opt-in, inert
1660/// hints that the executor may validate but does not yet act on.
1661/// `Default` is implemented **manually** (not derived) so that every graph —
1662/// however it is created — mints a fresh [`GraphId`] from the monotonic
1663/// counter. A derived `Default` would hand out a zeroed id, so two
1664/// `Graph::default()` graphs would claim the same identity and affinity
1665/// diagnostics would report nonsense.
1666#[derive(Debug)]
1667pub struct Graph {
1668 nodes: Vec<Node>,
1669 /// Sparse map of per-node placement hints. Entries are only present
1670 /// when explicitly set via [`Graph::set_placement`]. Absent entries
1671 /// mean "inherit from the executor's default device."
1672 placements: HashMap<NodeId, DeviceLocation>,
1673 /// NodeIds the executor must schedule even when their outputs are
1674 /// unreachable from the user's roots. Populated by graph-mutating
1675 /// rules that emit side-effecting ops (e.g. `Op::Release` for
1676 /// residency eviction). See [`Graph::add_side_effect_root`].
1677 side_effect_roots: Vec<NodeId>,
1678 /// Phase 7.5 work item G: graph-owned realized-storage map.
1679 /// Slots are populated for `Op::Const` leaves at construction
1680 /// time and for non-leaf nodes at realize time. Values are
1681 /// `Arc<RwLock<Storage>>` so consumers (NodeHandle handles, executor
1682 /// caches, residency machinery) share Storage cheaply via Arc
1683 /// clones. Lifetime is tied to the Graph; when the graph drops,
1684 /// any slots not held by external Arc clones are freed.
1685 storage_map: HashMap<NodeId, Arc<RwLock<Storage>>>,
1686 /// Phase 7.5 storage-unification B2: per-node dispatch
1687 /// resolution result. Set by the dispatch resolver (Phase B3+)
1688 /// when DAG construction picks which backend will execute the
1689 /// node's op given its inputs' dtype + residency. Sparse like
1690 /// `placements`: absent entries mean "not yet resolved" and the
1691 /// executor falls back to per-op-eval dispatch (today's
1692 /// behavior). After full migration, every Node has an entry.
1693 ///
1694 /// Note: this is a *side-table*, not a `Node` field, so that
1695 /// existing `Node { ... }` constructors don't need to change
1696 /// during the migration. Mirrors the `placements` pattern.
1697 target_backends: HashMap<NodeId, BackendId>,
1698 /// Phase 7.5 storage-unification — Layout-on-Node side-table.
1699 /// Sparse: every Node has a logical [`Layout`], but for the
1700 /// common case (contiguous result of a kernel) we don't store
1701 /// it explicitly — [`Graph::layout`] returns
1702 /// `Layout::contiguous(node.shape)` as the fallback. Entries
1703 /// are written here exclusively by metadata-only view ops
1704 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1705 /// 0-copy `Op::Reshape`) where the output is a strided view
1706 /// over an upstream node's Storage.
1707 ///
1708 /// Coherence rule: if `layouts[id]` is present, its
1709 /// `shape()` must equal `nodes[id].shape` — Layout adds
1710 /// strides + offset; the visible shape is identical.
1711 layouts: HashMap<NodeId, Layout>,
1712 /// Per-node multi-output side-table. Populated only for nodes
1713 /// whose op produces a bundled [`Storage`] with N>1 logical
1714 /// outputs (Session 1 of the multi-output-nodes design — see
1715 /// [`OutputView`](fuel_ir::storage::OutputView)). `Op::View`
1716 /// and `Op::ViewOwned` builders read this side-table to derive
1717 /// their own output shape/dtype/layout from the producer's
1718 /// declared slot specs.
1719 ///
1720 /// Coherence rule: when present, slot 0's `dtype` must equal the
1721 /// producer node's `Node::dtype` (which the multi-output op's
1722 /// allocator also uses as the inner backend storage's dtype).
1723 /// The producer's `Node::shape` reflects slot 0's logical shape
1724 /// for back-compat with single-output infrastructure; non-primary
1725 /// slots may have unrelated shapes and dtypes.
1726 node_output_views: HashMap<NodeId, Arc<[fuel_ir::storage::OutputView]>>,
1727 /// Per-node **storage-class override** ([`StorageClass`]). Sparse:
1728 /// entries are present only where the class differs from the op-inferred
1729 /// default ([`infer_storage_class`]) — chiefly KV-cache placeholder
1730 /// `Op::Const`s, which are session state, not shared weights.
1731 /// [`Graph::storage_class`] returns the override if present, else the
1732 /// inferred default, so every node has a well-defined class.
1733 /// Phase D substrate (PR-D1); not yet consumed by realize.
1734 storage_class: HashMap<NodeId, StorageClass>,
1735 /// Per-node **data-determined matmul row count** — the sparse-MoE
1736 /// capacity-buffer support. Present only on `Op::MatMul` nodes whose
1737 /// M (row count) is a runtime value: the node's `Node::shape` carries
1738 /// the row **capacity**, and this side-table carries the [`DynScalar`]
1739 /// that resolves (at compile if input-determined, else at execute from
1740 /// the producer-bound `SymEnv`) to how many rows to actually compute.
1741 /// Absent ⇒ a normal, static-M matmul. A side-table (not an `Op::MatMul`
1742 /// field) so the dense-matmul enum + its every match arm stay untouched.
1743 node_matmul_row_count: HashMap<NodeId, DynScalar>,
1744 /// Process-unique identity for this graph, minted at construction.
1745 ///
1746 /// Tensors are **graph-affine**: every binary op requires both operands to
1747 /// live on the same `Graph`, checked by `Arc::ptr_eq`. Pointer identity is
1748 /// the right *check* but a useless thing to *report* — so each graph also
1749 /// carries a small monotonic id, letting an affinity failure say "lhs is on
1750 /// graph #1, rhs on graph #2" instead of only that the two differ. That
1751 /// turns an abstract invariant into an observation the caller can act on:
1752 /// *you made two graphs.*
1753 id: GraphId,
1754}
1755
1756/// Process-unique identifier for a [`Graph`], minted monotonically by
1757/// [`Graph::new`]. Exists so affinity diagnostics can name *which* graphs
1758/// disagree; it is not a stable address, an index, or anything to persist.
1759#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1760pub struct GraphId(u64);
1761
1762impl std::fmt::Display for GraphId {
1763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1764 write!(f, "{}", self.0)
1765 }
1766}
1767
1768/// Monotonic source for [`GraphId`]. Starts at 1 so `#0` never appears and a
1769/// zeroed/defaulted id is visibly wrong.
1770static NEXT_GRAPH_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1771
1772impl Default for Graph {
1773 fn default() -> Self {
1774 Self::new()
1775 }
1776}
1777
1778impl Graph {
1779 /// Create an empty graph.
1780 pub fn new() -> Self {
1781 Self {
1782 id: GraphId(NEXT_GRAPH_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)),
1783 nodes: Vec::new(),
1784 placements: HashMap::new(),
1785 side_effect_roots: Vec::new(),
1786 storage_map: HashMap::new(),
1787 target_backends: HashMap::new(),
1788 layouts: HashMap::new(),
1789 node_output_views: HashMap::new(),
1790 storage_class: HashMap::new(),
1791 node_matmul_row_count: HashMap::new(),
1792 }
1793 }
1794
1795 /// This graph's process-unique [`GraphId`]. Used by affinity diagnostics to
1796 /// name *which* graphs disagree; see [`NodeHandle::graph_id`].
1797 pub fn id(&self) -> GraphId {
1798 self.id
1799 }
1800
1801 /// Look up the resolved target backend for a node, if any has
1802 /// been set. Returns `None` if dispatch resolution hasn't
1803 /// happened yet for this node — common during the migration
1804 /// because old op-builder paths don't call the resolver.
1805 ///
1806 /// Phase 7.5 B2.
1807 pub fn target_backend(&self, id: NodeId) -> Option<BackendId> {
1808 self.target_backends.get(&id).copied()
1809 }
1810
1811 /// Record the resolved target backend for `id`. Set once at DAG
1812 /// construction time (or first-realize time, depending on the
1813 /// dispatch policy chosen in Phase B3). Idempotent: calling
1814 /// twice with the same value is fine; calling twice with
1815 /// different values overwrites.
1816 ///
1817 /// Phase 7.5 B2.
1818 pub fn set_target_backend(&mut self, id: NodeId, backend: BackendId) {
1819 assert!(
1820 id.0 < self.nodes.len(),
1821 "set_target_backend: id out of bounds",
1822 );
1823 self.target_backends.insert(id, backend);
1824 }
1825
1826 /// Number of nodes with a resolved target backend. Mostly for
1827 /// tests and diagnostics.
1828 pub fn target_backend_count(&self) -> usize {
1829 self.target_backends.len()
1830 }
1831
1832 /// The storage class of `id`: the explicit override if one was set via
1833 /// [`Graph::set_storage_class`], else the op-inferred default
1834 /// ([`infer_storage_class`]). Every node has a well-defined class.
1835 ///
1836 /// Phase D substrate (PR-D1).
1837 pub fn storage_class(&self, id: NodeId) -> StorageClass {
1838 if let Some(c) = self.storage_class.get(&id).copied() {
1839 return c;
1840 }
1841 infer_storage_class(&self.nodes[id.0].op)
1842 }
1843
1844 /// Record an explicit storage-class override for `id`, replacing the
1845 /// op-inferred default. Used for nodes whose op does not determine the
1846 /// class — chiefly KV-cache placeholder `Op::Const`s, which are session
1847 /// state rather than shared weights.
1848 ///
1849 /// Phase D substrate (PR-D1).
1850 pub fn set_storage_class(&mut self, id: NodeId, class: StorageClass) {
1851 assert!(
1852 id.0 < self.nodes.len(),
1853 "set_storage_class: id out of bounds",
1854 );
1855 self.storage_class.insert(id, class);
1856 }
1857
1858 /// Whether `id` carries an explicit storage-class override (as opposed
1859 /// to relying on the op-inferred default).
1860 pub fn has_storage_class_override(&self, id: NodeId) -> bool {
1861 self.storage_class.contains_key(&id)
1862 }
1863
1864 /// Number of explicit storage-class overrides. Mostly for tests and
1865 /// diagnostics.
1866 pub fn storage_class_override_count(&self) -> usize {
1867 self.storage_class.len()
1868 }
1869
1870 /// The [`Layout`] associated with `id`. If the side-table has
1871 /// no explicit entry, returns `Layout::contiguous(shape)` —
1872 /// every Node logically has a Layout; the side-table is just
1873 /// the sparse storage for the strided / offset cases.
1874 ///
1875 /// Phase 7.5 storage-unification: metadata-only view ops
1876 /// (`Op::Transpose`, `Op::Permute`, `Op::BroadcastTo`,
1877 /// 0-copy `Op::Reshape`) populate this side-table during
1878 /// graph construction. Kernel ops produce contiguous results
1879 /// and rely on the fallback.
1880 pub fn layout(&self, id: NodeId) -> Layout {
1881 if let Some(l) = self.layouts.get(&id) {
1882 return l.clone();
1883 }
1884 Layout::contiguous(self.node(id).shape.clone())
1885 }
1886
1887 /// Record an explicit [`Layout`] for `id`. The Layout's
1888 /// `shape()` must equal `nodes[id].shape` — otherwise the
1889 /// graph becomes incoherent (downstream ops were validated
1890 /// against `node.shape`). Panics in `debug_assertions` mode
1891 /// on mismatch; in release the mismatch is silently kept
1892 /// because the alternative would require this method to
1893 /// return `Result`, which would break call ergonomics in
1894 /// graph-construction code.
1895 ///
1896 /// Set this exactly when an op produces a strided / offset
1897 /// view over upstream Storage. For the common case
1898 /// (contiguous kernel output), don't call this at all —
1899 /// [`Graph::layout`] returns `Layout::contiguous(shape)`
1900 /// as the implicit fallback.
1901 pub fn set_layout(&mut self, id: NodeId, layout: Layout) {
1902 assert!(id.0 < self.nodes.len(), "set_layout: id out of bounds");
1903 debug_assert_eq!(
1904 layout.shape(),
1905 &self.nodes[id.0].shape,
1906 "set_layout: Layout shape disagrees with Node shape \
1907 (Layout sets strides/offset, not the visible shape)",
1908 );
1909 self.layouts.insert(id, layout);
1910 }
1911
1912 /// Whether `id` has an explicit Layout entry in the side-table
1913 /// (i.e. it's a strided / offset view; not the default
1914 /// contiguous case).
1915 pub fn has_explicit_layout(&self, id: NodeId) -> bool {
1916 self.layouts.contains_key(&id)
1917 }
1918
1919 /// Number of nodes with an explicit (non-contiguous) Layout.
1920 /// Mostly for tests and diagnostics.
1921 pub fn explicit_layout_count(&self) -> usize {
1922 self.layouts.len()
1923 }
1924
1925 // -------------------------------------------------------------------
1926 // Multi-output side-table (Op::View / Op::ViewOwned)
1927 // -------------------------------------------------------------------
1928
1929 /// Borrow the per-slot output-view specs for `id`, if it's been
1930 /// declared as a multi-output producer. Returns `None` for
1931 /// single-output nodes (the common case).
1932 ///
1933 /// `Op::View` and `Op::ViewOwned` builders read this to derive
1934 /// the slot's shape/dtype/layout at graph-build time.
1935 pub fn output_views(&self, id: NodeId) -> Option<&[fuel_ir::storage::OutputView]> {
1936 self.node_output_views.get(&id).map(|a| a.as_ref())
1937 }
1938
1939 /// Clone the `Arc` handle to `id`'s per-slot output-view specs.
1940 /// Used by the realization path to attach the same bundle metadata
1941 /// to the realized [`Storage`] without copying the slice.
1942 pub fn output_views_arc(&self, id: NodeId) -> Option<Arc<[fuel_ir::storage::OutputView]>> {
1943 self.node_output_views.get(&id).cloned()
1944 }
1945
1946 /// Declare `id` as a multi-output producer with the given per-slot
1947 /// specs. Validates at graph-build time:
1948 /// 1. `id` is in bounds.
1949 /// 2. `views` is non-empty (a "multi-output" node with zero slots
1950 /// is a contract bug — use single-output if there's nothing to
1951 /// project).
1952 /// 3. Slot 0's dtype equals `nodes[id].dtype` (the bundle's
1953 /// primary dtype convention).
1954 /// 4. Slot 0's shape equals `nodes[id].shape` (slot 0 is the
1955 /// "primary" slot whose shape the single-output infrastructure
1956 /// already sees).
1957 /// 5. Each slot's `layout.shape()` equals the slot's `shape`
1958 /// (Layout adds strides/offset; the visible shape is identical).
1959 ///
1960 /// Idempotent on (id, views). Replacing an existing declaration
1961 /// asserts the new specs are byte-identical to the old in debug
1962 /// builds; in release the last write wins (matches the layouts
1963 /// side-table pattern).
1964 pub fn set_output_views(
1965 &mut self,
1966 id: NodeId,
1967 views: Arc<[fuel_ir::storage::OutputView]>,
1968 ) -> Result<(), fuel_ir::Error> {
1969 if id.0 >= self.nodes.len() {
1970 return Err(fuel_ir::Error::Msg(format!(
1971 "set_output_views: NodeId({}) out of bounds (len={})",
1972 id.0,
1973 self.nodes.len(),
1974 ))
1975 .bt());
1976 }
1977 if views.is_empty() {
1978 return Err(fuel_ir::Error::Msg(
1979 "set_output_views: slot list must be non-empty".into(),
1980 )
1981 .bt());
1982 }
1983 let node = &self.nodes[id.0];
1984 let slot0 = &views[0];
1985 if slot0.dtype != node.dtype {
1986 return Err(fuel_ir::Error::Msg(format!(
1987 "set_output_views: slot 0 dtype {:?} disagrees with \
1988 Node::dtype {:?} on Node#{} (slot 0 is the primary; \
1989 dtypes must match)",
1990 slot0.dtype, node.dtype, id.0,
1991 ))
1992 .bt());
1993 }
1994 if slot0.shape != node.shape {
1995 return Err(fuel_ir::Error::Msg(format!(
1996 "set_output_views: slot 0 shape {:?} disagrees with \
1997 Node::shape {:?} on Node#{} (slot 0 is the primary)",
1998 slot0.shape, node.shape, id.0,
1999 ))
2000 .bt());
2001 }
2002 for (i, v) in views.iter().enumerate() {
2003 if v.layout.shape() != &v.shape {
2004 return Err(fuel_ir::Error::Msg(format!(
2005 "set_output_views: slot {i} layout.shape() = {:?} \
2006 disagrees with declared slot shape {:?}",
2007 v.layout.shape(),
2008 v.shape,
2009 ))
2010 .bt());
2011 }
2012 }
2013 self.node_output_views.insert(id, views);
2014 Ok(())
2015 }
2016
2017 /// Whether `id` has been declared as a multi-output producer.
2018 pub fn is_multi_output(&self, id: NodeId) -> bool {
2019 self.node_output_views.contains_key(&id)
2020 }
2021
2022 /// Number of nodes declared as multi-output producers. Mostly for
2023 /// tests and diagnostics.
2024 pub fn multi_output_count(&self) -> usize {
2025 self.node_output_views.len()
2026 }
2027
2028 /// Whether some node in this graph *produces* (binds mid-realize) the
2029 /// runtime value `sym` — i.e. `sym` is **data-determined**, computed by
2030 /// an op during the pass rather than supplied up front. Used to tell a
2031 /// data-determined `DynScalar::Sym` (which is legitimately unbound in
2032 /// the compile-time `SymEnv` and must be resolved at *execute* time)
2033 /// apart from a caller error (a truly-unbound input-determined sym,
2034 /// which must surface as an error at realize). Today the only producer
2035 /// of a data-determined symbol is [`Op::NonZeroIndices`] (its
2036 /// `count_sym`); extend this match as more data-determined producers
2037 /// land.
2038 pub fn binds_data_determined_sym(&self, sym: SymId) -> bool {
2039 self.nodes.iter().any(|n| match &n.op {
2040 Op::NonZeroIndices { count_sym } => *count_sym == sym,
2041 _ => false,
2042 })
2043 }
2044
2045 /// The next data-determined [`SymId`] not yet used by any producer in
2046 /// this graph — one past the max `Op::NonZeroIndices` `count_sym`, or
2047 /// `SymId(0)` if none exist. Lets a builder that emits several
2048 /// data-determined producers (e.g. one `NonZeroIndices` per MoE expert,
2049 /// across several stacked layers on the same graph) allocate
2050 /// non-colliding count syms without threading an external
2051 /// [`fuel_ir::SymGen`]: each call reflects the producers already added,
2052 /// so successive layers claim strictly higher ranges.
2053 ///
2054 /// This covers the data-determined space (the only producers of which
2055 /// are `NonZeroIndices` nodes). A graph that *also* mixes
2056 /// input-determined symbolic extents in the same low sym range should
2057 /// thread a shared `SymGen` instead — those live in a separate
2058 /// compile-time `SymEnv` this scan does not see.
2059 pub fn next_data_determined_sym(&self) -> SymId {
2060 let max = self
2061 .nodes
2062 .iter()
2063 .filter_map(|n| match &n.op {
2064 Op::NonZeroIndices { count_sym } => Some(count_sym.0),
2065 _ => None,
2066 })
2067 .max();
2068 match max {
2069 Some(m) => SymId(m + 1),
2070 None => SymId(0),
2071 }
2072 }
2073
2074 /// Attach a data-determined row count to an `Op::MatMul` node — the
2075 /// sparse-MoE capacity-buffer support. The node's `Node::shape` stays
2076 /// the row-capacity output shape; `row_count` (a [`DynScalar`]) is how
2077 /// many rows to actually compute. See [`NodeHandle::matmul_dyn_m`].
2078 pub fn set_matmul_row_count(&mut self, id: NodeId, row_count: DynScalar) {
2079 assert!(
2080 id.0 < self.nodes.len(),
2081 "set_matmul_row_count: id out of bounds"
2082 );
2083 self.node_matmul_row_count.insert(id, row_count);
2084 }
2085
2086 /// The data-determined row count for `id`, if it carries one (i.e. it
2087 /// is a dynamic-M matmul). `None` ⇒ an ordinary static-M matmul.
2088 pub fn matmul_row_count(&self, id: NodeId) -> Option<DynScalar> {
2089 self.node_matmul_row_count.get(&id).copied()
2090 }
2091
2092 /// Look up the realized storage for a node, if any has been
2093 /// registered. Returns an Arc clone — the slot stays in the map
2094 /// after this call.
2095 pub fn storage_for(&self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2096 self.storage_map.get(&id).cloned()
2097 }
2098
2099 /// Register a realized-storage slot for `id`. Replaces any
2100 /// existing entry (callers responsible for ensuring this is the
2101 /// intended semantics — e.g. re-realization after eviction).
2102 pub fn set_storage(&mut self, id: NodeId, storage: Arc<RwLock<Storage>>) {
2103 assert!(id.0 < self.nodes.len(), "set_storage: id out of bounds");
2104 self.storage_map.insert(id, storage);
2105 }
2106
2107 /// Convenience: register an owned `Storage` directly. Wraps in
2108 /// `Arc<RwLock<...>>`.
2109 pub fn set_storage_owned(&mut self, id: NodeId, storage: Storage) {
2110 self.set_storage(id, Arc::new(RwLock::new(storage)));
2111 }
2112
2113 /// Remove a slot. Used by eviction / `Op::Release` paths.
2114 /// Returns the Arc if present so callers that want to keep the
2115 /// bytes alive can hold it; otherwise drops on the floor and any
2116 /// outstanding Arc clones still see the bytes.
2117 pub fn remove_storage(&mut self, id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2118 self.storage_map.remove(&id)
2119 }
2120
2121 /// Whether a slot is currently registered for `id`.
2122 pub fn has_storage(&self, id: NodeId) -> bool {
2123 self.storage_map.contains_key(&id)
2124 }
2125
2126 /// Number of registered storage slots.
2127 pub fn storage_len(&self) -> usize {
2128 self.storage_map.len()
2129 }
2130
2131 /// Register a NodeId as a side-effect root — a node whose output
2132 /// isn't reachable from any user-requested root but whose
2133 /// execution the executor must still schedule. Used for
2134 /// destructive ops (e.g. `Op::Release`) emitted by graph-mutating
2135 /// rules: the rule needs Release to run (freeing device memory),
2136 /// but Release's zero-element marker has no consumer.
2137 ///
2138 /// The executor's realize paths walk the user's roots AND these
2139 /// side-effect roots via a single combined `execution_plan` call.
2140 pub fn add_side_effect_root(&mut self, id: NodeId) {
2141 assert!(
2142 id.0 < self.nodes.len(),
2143 "add_side_effect_root: id out of bounds"
2144 );
2145 if !self.side_effect_roots.contains(&id) {
2146 self.side_effect_roots.push(id);
2147 }
2148 }
2149
2150 /// Snapshot the registered side-effect roots. Executor concatenates
2151 /// these with the user's requested roots before computing the plan.
2152 pub fn side_effect_roots(&self) -> &[NodeId] {
2153 &self.side_effect_roots
2154 }
2155
2156 /// The number of nodes currently in the graph.
2157 pub fn len(&self) -> usize {
2158 self.nodes.len()
2159 }
2160
2161 /// Whether the graph has any nodes.
2162 pub fn is_empty(&self) -> bool {
2163 self.nodes.is_empty()
2164 }
2165
2166 /// Borrow a node by ID. Panics if the ID is out of bounds — it should
2167 /// not be possible for a valid `NodeHandle` handle to produce an invalid
2168 /// ID, so any such panic indicates a bug in graph construction.
2169 pub fn node(&self, id: NodeId) -> &Node {
2170 &self.nodes[id.0]
2171 }
2172
2173 /// Produce a one-line human-readable description of a node and its
2174 /// immediate inputs — the identifier string that executor panics
2175 /// prepend so realize-time failures can be localized to the exact
2176 /// graph position that blew up. Format is stable enough for grep
2177 /// but explicitly intended for humans reading panic output, not for
2178 /// parsing.
2179 pub fn describe_node(&self, id: NodeId) -> String {
2180 let n = self.node(id);
2181 // GAP-303: `short_name()` renders every scan as the bare string "Scan",
2182 // so a body built from the WRONG scan was invisible in every dump and
2183 // every executor panic. Baracuda's requirement, adopted verbatim: make
2184 // something PRINT the carry count on the path that constructs the body —
2185 // not assert it. "A control tells you the encoding is sound; only the
2186 // subject's identity tells you what it encoded."
2187 let scan_params = match n.op {
2188 Op::Scan {
2189 n_carries,
2190 n_xs,
2191 bound,
2192 emit,
2193 ref early_exit,
2194 } => format!(
2195 " n_carries={n_carries} n_xs={n_xs} bound={bound} emit={emit:?} early_exit={}",
2196 early_exit.is_some()
2197 ),
2198 Op::ScanPlaceholder { role, index } => format!(" role={role:?} index={index}"),
2199 _ => String::new(),
2200 };
2201 let op_short = n.op.short_name();
2202 if n.inputs.is_empty() {
2203 return format!(
2204 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?})",
2205 id.0, n.shape, n.dtype,
2206 );
2207 }
2208 let inputs: Vec<String> = n
2209 .inputs
2210 .iter()
2211 .map(|&inp| {
2212 let ni = self.node(inp);
2213 let ip = ni.op.short_name();
2214 format!("Node#{}[{ip}, {:?}, {:?}]", inp.0, ni.shape, ni.dtype)
2215 })
2216 .collect();
2217 format!(
2218 "Node#{} ({op_short}{scan_params}, out shape={:?} dtype={:?}, inputs=[{}])",
2219 id.0,
2220 n.shape,
2221 n.dtype,
2222 inputs.join(", "),
2223 )
2224 }
2225
2226 /// Append a node and return its fresh ID. Used by the `NodeHandle`
2227 /// builders, by `opt` passes that canonicalize or rewrite the
2228 /// graph by appending fresh nodes, and by external consumers
2229 /// (fuel-storage's pipelined executor tests, custom-op authors)
2230 /// that need direct graph construction.
2231 ///
2232 /// For metadata-only view ops (`Op::Transpose`, `Op::Permute`,
2233 /// `Op::BroadcastTo`, `Op::Slice`) this also populates the
2234 /// [`layouts`](Self::layout) side-table by deriving the output
2235 /// layout from the input's layout via
2236 /// [`derive_view_output_layout`]. After this call,
2237 /// `graph.layout(new_id)` returns the strided/offset view layout
2238 /// without any further work — the side-table is the single source
2239 /// of truth for layout, with [`Layout::contiguous`] as the
2240 /// fallback for kernel-output nodes.
2241 ///
2242 /// Misuse (malformed Node, dangling input ids, etc.) is caught
2243 /// at execute time as a typed error, not a panic — per project's
2244 /// no-panic-in-production rule.
2245 pub fn push(&mut self, node: Node) -> NodeId {
2246 let id = NodeId(self.nodes.len());
2247 let is_view = node.op.is_view_op();
2248 let view_input = if is_view {
2249 node.inputs.first().copied()
2250 } else {
2251 None
2252 };
2253 let op_for_derive = if is_view { Some(node.op.clone()) } else { None };
2254 self.nodes.push(node);
2255 if let (Some(input_id), Some(op)) = (view_input, op_for_derive)
2256 && input_id.0 < self.nodes.len()
2257 {
2258 let input_layout = self.layout(input_id);
2259 if let Ok(out_layout) = derive_view_output_layout(&op, &input_layout) {
2260 self.set_layout(id, out_layout);
2261 }
2262 }
2263 id
2264 }
2265
2266 /// Rewrite every occurrence of `old_input` in `node`'s input list to
2267 /// `new_input`. In-place mutation — the *only* exception to the
2268 /// otherwise append-only invariant.
2269 ///
2270 /// Callers are responsible for ensuring `new_input` is semantically
2271 /// equivalent to `old_input` at this edge: same shape, same dtype,
2272 /// and produces data the consumer can read without error on the
2273 /// relevant device. Used by transform passes (residency eviction,
2274 /// fusion) that need to redirect a specific consumer's edge.
2275 pub(crate) fn rewrite_input(&mut self, node: NodeId, old_input: NodeId, new_input: NodeId) {
2276 assert!(
2277 node.0 < self.nodes.len(),
2278 "rewrite_input: node out of bounds"
2279 );
2280 let inputs = &mut self.nodes[node.0].inputs;
2281 for inp in inputs.iter_mut() {
2282 if *inp == old_input {
2283 *inp = new_input;
2284 }
2285 }
2286 }
2287
2288 /// **Collapse a decision point to a single baked arm** — the graph-side
2289 /// half of *optimize-time kernel-variant baking* (04-optimization:
2290 /// "kernel-variant choice is largely baked at optimize time"). Given a
2291 /// finalized [`Op::Branch`] and the arm the optimizer chose (`winner_arm`,
2292 /// an index into the branch's `inputs`), this rewrites the graph so the
2293 /// chosen arm is the **realized route** and the branch is no longer a
2294 /// decision point:
2295 ///
2296 /// 1. The `reconverge_at` merge is rewired to read the **winner's exit**
2297 /// (`inputs[winner_arm]`) in place of arm 0's exit (`inputs[0]`). For
2298 /// `winner_arm == 0` this is a no-op (the merge already reads arm 0,
2299 /// the runnability fallback).
2300 /// 2. The branch's `inputs` are reduced to `[winner_exit]` — a **single-arm
2301 /// branch**, which [`run::extract_runs_multi`] / `non_chosen_arm_nodes` /
2302 /// the route picker all treat as *no decision* (`arms.len() < 2`), so the
2303 /// winner's region lowers inline and the non-chosen arms become
2304 /// orphaned (pruned from the reachable set — nothing reads them once the
2305 /// merge is rewired). The arm-0 runnability invariant is preserved:
2306 /// after the reduce, `inputs[0]` is the winner and the merge reads it.
2307 ///
2308 /// This is the "the Branch collapses" resolution the constitution names for
2309 /// same-device **kernel-variant** choices (decomposed-region vs. a fused
2310 /// kernel on the *same* device), as distinct from **placement** choices
2311 /// (arms on *different* devices) which stay live `Op::Branch` decision
2312 /// points for the runtime route picker (06-runtime). The optimizer decides
2313 /// *which* branches are variant branches and computes `winner_arm`; this
2314 /// method only performs the structural collapse.
2315 ///
2316 /// Never-panic: returns [`fuel_ir::Error::InvalidBranch`] on a
2317 /// non-`Op::Branch` node or an out-of-range `winner_arm`, mutating nothing.
2318 /// Idempotent on an already-collapsed (single-arm) branch when
2319 /// `winner_arm == 0`.
2320 pub fn collapse_variant_branch(
2321 &mut self,
2322 branch: NodeId,
2323 winner_arm: usize,
2324 ) -> std::result::Result<(), fuel_ir::Error> {
2325 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2326 if branch.0 >= self.nodes.len() {
2327 return Err(invalid(format!(
2328 "collapse_variant_branch: branch Node#{} is out of bounds \
2329 (graph has {} nodes)",
2330 branch.0,
2331 self.nodes.len(),
2332 )));
2333 }
2334 let reconverge_at = match self.nodes[branch.0].op {
2335 Op::Branch { reconverge_at } => reconverge_at,
2336 ref other => {
2337 return Err(invalid(format!(
2338 "collapse_variant_branch: Node#{} is not an Op::Branch (got \
2339 {other:?})",
2340 branch.0,
2341 )));
2342 }
2343 };
2344 let arms = &self.nodes[branch.0].inputs;
2345 if arms.is_empty() {
2346 return Err(invalid(format!(
2347 "collapse_variant_branch: branch Node#{} has no arms",
2348 branch.0,
2349 )));
2350 }
2351 if winner_arm >= arms.len() {
2352 return Err(invalid(format!(
2353 "collapse_variant_branch: winner_arm {winner_arm} is out of range \
2354 (branch Node#{} has {} arms)",
2355 branch.0,
2356 arms.len(),
2357 )));
2358 }
2359 let old_arm0 = arms[0];
2360 let winner = arms[winner_arm];
2361
2362 // (1) Rewire the merge to read the winner's exit (no-op for arm 0).
2363 if winner != old_arm0 {
2364 self.rewrite_input(reconverge_at, old_arm0, winner);
2365 }
2366 // (2) Reduce the branch to the single winning arm (now arm 0). A
2367 // single-arm branch is inert: the run extractor / picker skip it,
2368 // so the non-chosen arms are pruned and the winner lowers inline.
2369 self.nodes[branch.0].inputs = vec![winner];
2370 Ok(())
2371 }
2372
2373 /// Tag a node with a target device. The executor will validate
2374 /// (post-Phase-1) that the node's op can be evaluated on that
2375 /// device. In Phase 1 the tag is informational only.
2376 pub fn set_placement(&mut self, id: NodeId, loc: DeviceLocation) {
2377 assert!(id.0 < self.nodes.len(), "set_placement: id out of bounds");
2378 self.placements.insert(id, loc);
2379 }
2380
2381 /// Read a node's placement hint, or `None` if the node inherits from
2382 /// the executor default.
2383 pub fn placement(&self, id: NodeId) -> Option<DeviceLocation> {
2384 self.placements.get(&id).copied()
2385 }
2386
2387 /// Open a [`BranchBuilder`] rooted at a shared `diverge` point — the
2388 /// first half of the `open_branch` / `add_arm` / `finalize_branches`
2389 /// trio that constructs an [`Op::Branch`] (phi/merge) node with
2390 /// build-time validation (Phase A PR-A1 of the "plan IS the graph"
2391 /// rebuild).
2392 ///
2393 /// `diverge` names the single node from which every candidate route
2394 /// (arm) departs; each arm's *exit* (added via
2395 /// [`BranchBuilder::add_arm`]) becomes one `inputs[i]` of the emitted
2396 /// `Op::Branch`. The builder borrows nothing — it is a pure
2397 /// accumulator of `NodeId`s — so the graph stays free to keep building
2398 /// arms between `open_branch` and `finalize_branches`. All validation
2399 /// (descendant `reconverge_at`, internally-disjoint arms,
2400 /// cast-to-uniform shape/dtype, arm-0 runnability) happens in
2401 /// [`BranchBuilder::finalize_branches`], which returns a typed
2402 /// [`fuel_ir::error::Error::InvalidBranch`] rather than panicking.
2403 pub fn open_branch(&self, diverge: NodeId) -> BranchBuilder {
2404 BranchBuilder {
2405 diverge,
2406 arms: Vec::new(),
2407 }
2408 }
2409
2410 /// Forward-reachable set (the node and all its transitive *consumers*)
2411 /// from `from`, computed against a precomputed consumer adjacency.
2412 /// Used by branch validation to test descendant-hood and arm
2413 /// containment without re-scanning the whole arena per query.
2414 fn forward_reachable(
2415 consumers: &HashMap<NodeId, Vec<NodeId>>,
2416 from: NodeId,
2417 ) -> HashSet<NodeId> {
2418 let mut seen: HashSet<NodeId> = HashSet::new();
2419 let mut stack = vec![from];
2420 while let Some(n) = stack.pop() {
2421 if !seen.insert(n) {
2422 continue;
2423 }
2424 if let Some(cs) = consumers.get(&n) {
2425 for &c in cs {
2426 if !seen.contains(&c) {
2427 stack.push(c);
2428 }
2429 }
2430 }
2431 }
2432 seen
2433 }
2434
2435 /// Backward-reachable set (the node and all its transitive *inputs*)
2436 /// from `from`. Used to bound an arm to the nodes that actually lie
2437 /// on a path `diverge → exit`.
2438 fn backward_reachable(&self, from: NodeId) -> HashSet<NodeId> {
2439 let mut seen: HashSet<NodeId> = HashSet::new();
2440 let mut stack = vec![from];
2441 while let Some(n) = stack.pop() {
2442 if !seen.insert(n) {
2443 continue;
2444 }
2445 for &inp in &self.nodes[n.0].inputs {
2446 if !seen.contains(&inp) {
2447 stack.push(inp);
2448 }
2449 }
2450 }
2451 seen
2452 }
2453
2454 // -------------------------------------------------------------------
2455 // Compaction of the append-only arena (PR-B4)
2456 // -------------------------------------------------------------------
2457
2458 /// The set of nodes that constitute the **live structure** of the
2459 /// graph relative to `roots`: everything reachable, following node
2460 /// `inputs`, from the union of
2461 ///
2462 /// - the caller's `roots`,
2463 /// - the `side_effect_roots` (nodes the executor must schedule even
2464 /// when no output reads them — e.g. `Op::Release` eviction), and
2465 /// - the full multi-path structure: for every reachable `Op::Branch`,
2466 /// its `reconverge_at` and **all its arms** (the arm exits, which
2467 /// are the Branch node's `inputs`, and transitively their interiors).
2468 /// Phase C's route picker needs every arm, so the alternative arms
2469 /// must survive even though nothing downstream reads them directly
2470 /// (the `reconverge_at` node reads only arm 0).
2471 ///
2472 /// A finalized `Op::Branch` is itself typically orphaned — nothing
2473 /// downstream reads it (PR-A1's runnability invariant has the merge
2474 /// read arm 0 directly, not the Branch). So a plain forward walk from
2475 /// `roots` would miss it. We therefore mirror [`run::extract_runs_multi`]'s
2476 /// `effective_roots` discipline: scan the arena and seed any Branch
2477 /// whose `reconverge_at` (or any arm exit) is already reachable, to a
2478 /// fixpoint, then take the input-closure of all seeds. The result is
2479 /// the exact set compaction must keep.
2480 fn live_set(&self, roots: &[NodeId]) -> HashSet<NodeId> {
2481 // Seeds: roots + side-effect roots. We grow this set with the
2482 // Branch nodes that participate in the reachable computation, then
2483 // take its full input-closure.
2484 let mut seeds: Vec<NodeId> = Vec::new();
2485 let mut seed_set: HashSet<NodeId> = HashSet::new();
2486 let push_seed = |id: NodeId, seeds: &mut Vec<NodeId>, seed_set: &mut HashSet<NodeId>| {
2487 if id.0 < self.nodes.len() && seed_set.insert(id) {
2488 seeds.push(id);
2489 }
2490 };
2491 for &r in roots {
2492 push_seed(r, &mut seeds, &mut seed_set);
2493 }
2494 for &r in &self.side_effect_roots {
2495 push_seed(r, &mut seeds, &mut seed_set);
2496 }
2497
2498 // Grow the seed set with participating Branch nodes to a fixpoint.
2499 // A Branch "participates" when its merge target or any arm exit is
2500 // already reachable from the current seeds (following inputs). Each
2501 // newly-seeded Branch may pull in further arms whose interiors then
2502 // make another Branch participate, hence the fixpoint.
2503 loop {
2504 let reachable = self.input_closure(&seeds);
2505 let mut added = false;
2506 for idx in 0..self.nodes.len() {
2507 let id = NodeId(idx);
2508 if seed_set.contains(&id) {
2509 continue;
2510 }
2511 let Op::Branch { reconverge_at } = self.nodes[idx].op else {
2512 continue;
2513 };
2514 let participates = reachable.contains(&reconverge_at)
2515 || self.nodes[idx].inputs.iter().any(|a| reachable.contains(a));
2516 if participates {
2517 seed_set.insert(id);
2518 seeds.push(id);
2519 added = true;
2520 }
2521 }
2522 if !added {
2523 break;
2524 }
2525 }
2526
2527 // The live set is the full input-closure of the (roots + side-effect
2528 // + participating-Branch) seeds, plus each reachable Branch's
2529 // explicit `reconverge_at` (which is downstream of the arms, so it
2530 // is not pulled in by following inputs from the Branch). The merge
2531 // node is normally reachable from `roots` already, but seeding it
2532 // explicitly makes the live set self-consistent — a Branch never
2533 // outlives its merge target.
2534 let mut live = self.input_closure(&seeds);
2535 let recon_seeds: Vec<NodeId> = live
2536 .iter()
2537 .filter_map(|&id| match self.nodes[id.0].op {
2538 Op::Branch { reconverge_at } => Some(reconverge_at),
2539 _ => None,
2540 })
2541 .collect();
2542 if !recon_seeds.is_empty() {
2543 for n in self.input_closure(&recon_seeds) {
2544 live.insert(n);
2545 }
2546 }
2547 live
2548 }
2549
2550 /// Every node reachable from any of `from`, following node `inputs`
2551 /// transitively (the backward / input cone). Mirrors
2552 /// [`topo_order_multi`] but returns just the set.
2553 fn input_closure(&self, from: &[NodeId]) -> HashSet<NodeId> {
2554 let mut seen: HashSet<NodeId> = HashSet::new();
2555 let mut stack: Vec<NodeId> = from.to_vec();
2556 while let Some(n) = stack.pop() {
2557 if n.0 >= self.nodes.len() || !seen.insert(n) {
2558 continue;
2559 }
2560 for &inp in &self.nodes[n.0].inputs {
2561 if !seen.contains(&inp) {
2562 stack.push(inp);
2563 }
2564 }
2565 }
2566 seen
2567 }
2568
2569 /// **Required compaction of the append-only arena** (PR-B4).
2570 ///
2571 /// Drops every node *not* in the live structure relative to `roots`
2572 /// (the exploration debris that pathfinders leave) and rebuilds the
2573 /// arena with contiguous, renumbered [`NodeId`]s, remapping **every**
2574 /// `NodeId` reference in the graph. Returns the [`NodeRemap`] from old
2575 /// to new ids so callers can fix up their own `NodeHandle` handles / roots.
2576 ///
2577 /// The live set follows node `inputs` from: `roots`, the
2578 /// `side_effect_roots`, and the full multi-path structure — for every
2579 /// reachable [`Op::Branch`], its `reconverge_at` **and all its arms**
2580 /// (so the route picker's alternatives survive). See [`Graph::live_set`].
2581 ///
2582 /// What is remapped (the correctness crux — a missed remap is silent
2583 /// corruption). Every NodeId-bearing structure in the graph:
2584 /// - each surviving [`Node`]'s `inputs`;
2585 /// - the `NodeId` carried *inside* an op variant — [`Op::Branch`]'s
2586 /// `reconverge_at` (the only `Op` variant carrying a `NodeId`);
2587 /// - every NodeId-keyed side-table on [`Graph`]: `placements`,
2588 /// `target_backends`, `layouts`, `storage_map`, `node_output_views`;
2589 /// - the `side_effect_roots` vector.
2590 ///
2591 /// # Not in the per-realize hot path
2592 ///
2593 /// Compaction renumbers `NodeId`s, which would invalidate a realize
2594 /// already built around the current ids (the dispatch order and the
2595 /// `StorageCache` key are `NodeId`). It is therefore a **standalone
2596 /// pass**, deliberately **not** registered as an `Optimizer` in the
2597 /// per-realize driver / `optimize_graph` loop. It runs at load-time
2598 /// **between optimization rounds** (Phase D) and is **required before
2599 /// finalize-to-disk** (Phase E) so the persisted `.fuel` holds the lean
2600 /// result, not exploration debris. Neither caller exists yet.
2601 ///
2602 /// Orphans never change results, so this is a *size* pass, not a
2603 /// *correctness* one — but the remap it performs must be exhaustive or
2604 /// it would itself introduce corruption, which is the property the
2605 /// born-red tests + [`Graph::verify_no_dangling`] guard.
2606 ///
2607 /// This is the implementation behind the free function [`compact`];
2608 /// call that.
2609 fn compact_in_place(&mut self, roots: &[NodeId]) -> NodeRemap {
2610 let live = self.live_set(roots);
2611 let n = self.nodes.len();
2612
2613 // Assign new contiguous ids in ascending old-id order, so the
2614 // relative order of surviving nodes (and hence any topological
2615 // property over them) is preserved.
2616 let mut old_to_new: Vec<Option<NodeId>> = vec![None; n];
2617 let mut next = 0usize;
2618 #[expect(
2619 clippy::needless_range_loop,
2620 reason = "`idx` is an id-space counter: it builds `NodeId(idx)` for the membership check and indexes `old_to_new` by that id; the bound `n` is the old-id count, not an array to enumerate"
2621 )]
2622 for idx in 0..n {
2623 if live.contains(&NodeId(idx)) {
2624 old_to_new[idx] = Some(NodeId(next));
2625 next += 1;
2626 }
2627 }
2628 let remap = NodeRemap { old_to_new };
2629
2630 // Rebuild the node arena, remapping each surviving node's inputs and
2631 // any op-carried NodeId. Surviving nodes' inputs are themselves
2632 // always live (the live set is input-closed), so every `map` here
2633 // resolves.
2634 let mut new_nodes: Vec<Node> = Vec::with_capacity(next);
2635 for idx in 0..n {
2636 if remap.old_to_new[idx].is_none() {
2637 continue;
2638 }
2639 let mut node = self.nodes[idx].clone();
2640 for inp in node.inputs.iter_mut() {
2641 *inp = remap.expect(*inp);
2642 }
2643 if let Op::Branch { reconverge_at } = &mut node.op {
2644 *reconverge_at = remap.expect(*reconverge_at);
2645 }
2646 new_nodes.push(node);
2647 }
2648 self.nodes = new_nodes;
2649
2650 // Remap every NodeId-keyed side-table. Drop entries for dropped
2651 // nodes; rekey survivors to their new id.
2652 self.placements = remap.rekey(std::mem::take(&mut self.placements));
2653 self.target_backends = remap.rekey(std::mem::take(&mut self.target_backends));
2654 self.layouts = remap.rekey(std::mem::take(&mut self.layouts));
2655 self.storage_map = remap.rekey(std::mem::take(&mut self.storage_map));
2656 self.node_output_views = remap.rekey(std::mem::take(&mut self.node_output_views));
2657 self.storage_class = remap.rekey(std::mem::take(&mut self.storage_class));
2658 self.node_matmul_row_count = remap.rekey(std::mem::take(&mut self.node_matmul_row_count));
2659
2660 // Remap the side-effect-roots vector (every entry is live — they
2661 // were reachability seeds — so each maps).
2662 self.side_effect_roots = self
2663 .side_effect_roots
2664 .iter()
2665 .map(|&id| remap.expect(id))
2666 .collect();
2667
2668 debug_assert!(
2669 self.verify_no_dangling().is_ok(),
2670 "compact left a dangling NodeId reference: {:?}",
2671 self.verify_no_dangling().err(),
2672 );
2673 remap
2674 }
2675
2676 /// Verify that **no** `NodeId` reference in the graph points outside
2677 /// the arena — the post-compaction safety net for a missed remap.
2678 /// Checks every node's `inputs`, the op-carried `Op::Branch`
2679 /// `reconverge_at`, every NodeId-keyed side-table, and the
2680 /// `side_effect_roots` vector. Returns the first offending reference as
2681 /// a typed error (never panics); used by [`crate::compact`]'s
2682 /// `debug_assert` and by tests.
2683 pub fn verify_no_dangling(&self) -> std::result::Result<(), fuel_ir::Error> {
2684 let n = self.nodes.len();
2685 let bad = |what: String| {
2686 Err(fuel_ir::Error::Msg(format!(
2687 "dangling NodeId reference: {what} (arena has {n} nodes)",
2688 )))
2689 };
2690 for (idx, node) in self.nodes.iter().enumerate() {
2691 for &inp in &node.inputs {
2692 if inp.0 >= n {
2693 return bad(format!("Node#{idx} input Node#{}", inp.0));
2694 }
2695 }
2696 if let Op::Branch { reconverge_at } = node.op
2697 && reconverge_at.0 >= n
2698 {
2699 return bad(format!(
2700 "Node#{idx} Branch.reconverge_at Node#{}",
2701 reconverge_at.0
2702 ));
2703 }
2704 }
2705 for id in self.placements.keys() {
2706 if id.0 >= n {
2707 return bad(format!("placements key Node#{}", id.0));
2708 }
2709 }
2710 for id in self.target_backends.keys() {
2711 if id.0 >= n {
2712 return bad(format!("target_backends key Node#{}", id.0));
2713 }
2714 }
2715 for id in self.layouts.keys() {
2716 if id.0 >= n {
2717 return bad(format!("layouts key Node#{}", id.0));
2718 }
2719 }
2720 for id in self.storage_map.keys() {
2721 if id.0 >= n {
2722 return bad(format!("storage_map key Node#{}", id.0));
2723 }
2724 }
2725 for id in self.node_output_views.keys() {
2726 if id.0 >= n {
2727 return bad(format!("node_output_views key Node#{}", id.0));
2728 }
2729 }
2730 for id in self.storage_class.keys() {
2731 if id.0 >= n {
2732 return bad(format!("storage_class key Node#{}", id.0));
2733 }
2734 }
2735 for &id in &self.side_effect_roots {
2736 if id.0 >= n {
2737 return bad(format!("side_effect_root Node#{}", id.0));
2738 }
2739 }
2740 Ok(())
2741 }
2742}
2743
2744/// **Required compaction of the append-only arena** (PR-B4).
2745///
2746/// Drops every node *not* in the live structure relative to `roots` (the
2747/// exploration debris that pathfinders leave) and rebuilds the arena with
2748/// contiguous, renumbered [`NodeId`]s, remapping **every** `NodeId`
2749/// reference in the graph. Returns the [`NodeRemap`] from old → new ids so
2750/// callers can fix up their own roots / `NodeHandle` handles.
2751///
2752/// The live set follows node `inputs` from `roots`, the
2753/// `side_effect_roots`, and the full multi-path structure — for every
2754/// reachable [`Op::Branch`], its `reconverge_at` **and all its arms** (so
2755/// Phase C's route picker keeps its alternatives). Everything else is
2756/// dropped.
2757///
2758/// **Not in the per-realize hot path.** Compaction renumbers `NodeId`s,
2759/// which would invalidate a realize built around the current ids (the
2760/// dispatch order + the `StorageCache` key are `NodeId`). It is a
2761/// standalone pass — deliberately **not** registered as an `Optimizer` in
2762/// the per-realize driver / `optimize_graph` loop — run at load-time
2763/// **between optimization rounds** (Phase D) and **required before
2764/// finalize-to-disk** (Phase E). Neither caller exists yet.
2765///
2766/// See [`Graph::verify_no_dangling`] for the post-condition the
2767/// `debug_assert` checks: no `NodeId` reference (node inputs, the
2768/// op-carried `Op::Branch.reconverge_at`, any side-table, or
2769/// `side_effect_roots`) points outside the new arena.
2770pub fn compact(graph: &mut Graph, roots: &[NodeId]) -> NodeRemap {
2771 graph.compact_in_place(roots)
2772}
2773
2774/// The old → new `NodeId` mapping produced by [`compact`].
2775///
2776/// Indexed by the *old* `NodeId`: `old_to_new[old.0]` is `Some(new)` if the
2777/// node survived compaction, or `None` if it was dropped as unreachable
2778/// debris. Callers use [`NodeRemap::get`] to translate roots / `NodeHandle`
2779/// ids they still hold; passes that know a node must have survived use
2780/// `NodeRemap::expect`.
2781#[derive(Debug, Clone)]
2782pub struct NodeRemap {
2783 old_to_new: Vec<Option<NodeId>>,
2784}
2785
2786impl NodeRemap {
2787 /// The new id for `old`, or `None` if `old` was dropped (or is out of
2788 /// range of the pre-compaction arena).
2789 pub fn get(&self, old: NodeId) -> Option<NodeId> {
2790 self.old_to_new.get(old.0).copied().flatten()
2791 }
2792
2793 /// Whether `old` survived compaction.
2794 pub fn survived(&self, old: NodeId) -> bool {
2795 self.get(old).is_some()
2796 }
2797
2798 /// The new id for `old`, asserting it survived. Used internally when
2799 /// remapping a reference that is known-live (a surviving node's input,
2800 /// a reachable Branch's `reconverge_at`, a side-effect root) — a `None`
2801 /// here would mean the live-set computation was unsound.
2802 fn expect(&self, old: NodeId) -> NodeId {
2803 self.get(old).unwrap_or_else(|| {
2804 panic!(
2805 "NodeRemap::expect: Node#{} was expected to survive compaction \
2806 but was dropped — the live set is unsound (a referenced node \
2807 was not kept)",
2808 old.0,
2809 )
2810 })
2811 }
2812
2813 /// Rekey a `NodeId`-keyed side-table: drop entries whose key was
2814 /// dropped, rewrite surviving keys to their new id. Values are moved,
2815 /// not cloned.
2816 fn rekey<V>(&self, table: HashMap<NodeId, V>) -> HashMap<NodeId, V> {
2817 let mut out = HashMap::with_capacity(table.len());
2818 for (old, v) in table {
2819 if let Some(new) = self.get(old) {
2820 out.insert(new, v);
2821 }
2822 }
2823 out
2824 }
2825}
2826
2827/// Accumulates the arms of an in-construction [`Op::Branch`] (phi/merge)
2828/// node before [`finalize_branches`](Self::finalize_branches) validates
2829/// them and emits the node. Created by [`Graph::open_branch`].
2830///
2831/// The multi-path structure is an **arena fact, not an overlay**: a
2832/// `Branch` node's divergent arms are its `inputs` (each input is one
2833/// route's *exit*), and the op carries an explicit `reconverge_at`. The
2834/// builder is a pure `NodeId` accumulator — it holds no graph reference —
2835/// so the graph remains free to keep appending nodes (further arms) while
2836/// the builder is open. Nothing mutates the arena until
2837/// `finalize_branches`, which is the single validation gate.
2838#[derive(Debug, Clone)]
2839pub struct BranchBuilder {
2840 /// The shared node every arm departs from.
2841 diverge: NodeId,
2842 /// Each arm's *exit* node, in priority order. `arms[0]` is the
2843 /// runnability fallback (arm 0): the route a finalized-but-unpicked
2844 /// graph realizes on.
2845 arms: Vec<NodeId>,
2846}
2847
2848impl BranchBuilder {
2849 /// Append one arm by its *exit* node — the node whose value the merge
2850 /// reads for this route. The first arm added is **arm 0**, the
2851 /// runnability fallback: `reconverge_at` must read arm 0's exit so a
2852 /// finalized-but-not-yet-route-picked graph still realizes (validated
2853 /// in [`finalize_branches`](Self::finalize_branches)).
2854 ///
2855 /// Returns `&mut Self` for chaining. Validation is deferred to
2856 /// finalize — `add_arm` never inspects the graph and never fails.
2857 pub fn add_arm(&mut self, exit: NodeId) -> &mut Self {
2858 self.arms.push(exit);
2859 self
2860 }
2861
2862 /// The shared diverge point this branch departs from.
2863 pub fn diverge(&self) -> NodeId {
2864 self.diverge
2865 }
2866
2867 /// The arm exits accumulated so far, in add order (arm 0 first).
2868 pub fn arms(&self) -> &[NodeId] {
2869 &self.arms
2870 }
2871
2872 /// Validate and emit the [`Op::Branch`] node, returning its fresh
2873 /// `NodeId`. This is the single build-time gate; it **never panics**,
2874 /// surfacing every rejection as [`fuel_ir::error::Error::InvalidBranch`].
2875 ///
2876 /// Returns:
2877 /// - `Ok(Some(branch_id))` — a multi-arm branch was emitted.
2878 /// - `Ok(None)` — a **single-arm branch collapsed** to that arm (no
2879 /// real decision point), leaving the arena untouched.
2880 /// - `Err(Error::InvalidBranch { .. })` — a validation rule failed.
2881 ///
2882 /// Validation rules (all checked before any mutation):
2883 /// 1. At least one arm; `diverge`, `reconverge_at`, and every arm
2884 /// exit are in-bounds.
2885 /// 2. **Descendant `reconverge_at`** — the merge must be a forward
2886 /// descendant of (and distinct from) `diverge`.
2887 /// 3. **Internally-disjoint arms** — each arm's interior nodes (the
2888 /// nodes on paths `diverge → exit`, excluding the shared `diverge`)
2889 /// must neither be shared with another arm nor read by any node
2890 /// outside the branch (`reconverge_at` reading an arm exit is the
2891 /// one allowed external consumer).
2892 /// 4. **Cast-to-uniform** — all arm exits agree on shape & dtype.
2893 /// PR-A1 *validates* uniformity and errors on mismatch (it does not
2894 /// insert `Cast` nodes); dtype-lowered alternatives must therefore
2895 /// cast back to the merge dtype *inside* their arm before the exit.
2896 /// 5. **Arm-0 runnability** — `reconverge_at` must read arm 0's exit,
2897 /// so a finalized-but-unpicked graph still realizes on arm 0.
2898 pub fn finalize_branches(
2899 self,
2900 graph: &mut Graph,
2901 reconverge_at: NodeId,
2902 ) -> std::result::Result<Option<NodeId>, fuel_ir::Error> {
2903 let n = graph.nodes.len();
2904 let invalid = |reason: String| fuel_ir::Error::InvalidBranch { reason };
2905
2906 // (1a) At least one arm.
2907 if self.arms.is_empty() {
2908 return Err(invalid(
2909 "branch has no arms; at least one route is required".to_string(),
2910 ));
2911 }
2912 // (1b) Bounds-check every referenced node up front so later
2913 // arena indexing cannot panic.
2914 let in_bounds = |id: NodeId| id.0 < n;
2915 if !in_bounds(self.diverge) {
2916 return Err(invalid(format!(
2917 "diverge Node#{} is out of bounds (graph has {n} nodes)",
2918 self.diverge.0,
2919 )));
2920 }
2921 if !in_bounds(reconverge_at) {
2922 return Err(invalid(format!(
2923 "reconverge_at Node#{} is out of bounds (graph has {n} nodes)",
2924 reconverge_at.0,
2925 )));
2926 }
2927 for &arm in &self.arms {
2928 if !in_bounds(arm) {
2929 return Err(invalid(format!(
2930 "arm exit Node#{} is out of bounds (graph has {n} nodes)",
2931 arm.0,
2932 )));
2933 }
2934 }
2935
2936 // (d) Single-arm branches collapse back to that arm — no real
2937 // decision point, so no Op::Branch is emitted and the arena is
2938 // left untouched.
2939 if self.arms.len() == 1 {
2940 return Ok(None);
2941 }
2942
2943 // Build a consumer (reverse) adjacency once for the reachability
2944 // queries below.
2945 let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
2946 for (idx, node) in graph.nodes.iter().enumerate() {
2947 let consumer = NodeId(idx);
2948 for &inp in &node.inputs {
2949 consumers.entry(inp).or_default().push(consumer);
2950 }
2951 }
2952
2953 // (2) reconverge_at must be a forward descendant of diverge and
2954 // distinct from it.
2955 if reconverge_at == self.diverge {
2956 return Err(invalid(format!(
2957 "reconverge_at Node#{} must be a strict descendant of the \
2958 diverge point, not the diverge point itself",
2959 reconverge_at.0,
2960 )));
2961 }
2962 let fwd_from_diverge = Graph::forward_reachable(&consumers, self.diverge);
2963 if !fwd_from_diverge.contains(&reconverge_at) {
2964 return Err(invalid(format!(
2965 "reconverge_at Node#{} is not a descendant of diverge Node#{}",
2966 reconverge_at.0, self.diverge.0,
2967 )));
2968 }
2969
2970 // (4) Cast-to-uniform: every arm exit must agree on shape & dtype
2971 // with arm 0 (PR-A1 validates uniformity rather than inserting
2972 // Cast nodes).
2973 let arm0 = self.arms[0];
2974 let (want_shape, want_dtype) = {
2975 let a0 = &graph.nodes[arm0.0];
2976 (a0.shape.clone(), a0.dtype)
2977 };
2978 for &arm in &self.arms[1..] {
2979 let node = &graph.nodes[arm.0];
2980 if node.shape != want_shape || node.dtype != want_dtype {
2981 return Err(invalid(format!(
2982 "arm exit Node#{} ({:?} {:?}) disagrees with arm 0 Node#{} \
2983 ({:?} {:?}); arms must cast to a uniform shape & dtype at \
2984 reconverge",
2985 arm.0, node.shape, node.dtype, arm0.0, want_shape, want_dtype,
2986 )));
2987 }
2988 }
2989
2990 // (5) Arm-0 runnability: reconverge_at must read arm 0's exit, so
2991 // an unpicked graph realizes on arm 0.
2992 if !graph.nodes[reconverge_at.0].inputs.contains(&arm0) {
2993 return Err(invalid(format!(
2994 "reconverge_at Node#{} does not read arm-0 exit Node#{}; the \
2995 arm-0 runnability invariant requires the merge to read arm 0 \
2996 so a not-yet-route-picked graph still realizes",
2997 reconverge_at.0, arm0.0,
2998 )));
2999 }
3000
3001 // (3) Internal disjointness. Each arm's node set is the nodes on
3002 // paths diverge → exit: backward-reachable from the exit AND
3003 // forward-reachable from diverge. The arm *interior* excludes the
3004 // shared diverge point.
3005 let mut arm_interiors: Vec<HashSet<NodeId>> = Vec::with_capacity(self.arms.len());
3006 for &exit in &self.arms {
3007 let back = graph.backward_reachable(exit);
3008 let mut interior: HashSet<NodeId> =
3009 back.intersection(&fwd_from_diverge).copied().collect();
3010 interior.remove(&self.diverge);
3011 // The exit itself is always part of the arm even if (for a
3012 // degenerate arm) it equals the diverge point — but a
3013 // diverge-equals-exit arm has an empty interior, which would
3014 // make the arm indistinguishable from "no route", so reject.
3015 if interior.is_empty() {
3016 return Err(invalid(format!(
3017 "arm exit Node#{} has no interior strictly after diverge \
3018 Node#{}; an arm must add at least one node between the \
3019 diverge point and its exit",
3020 exit.0, self.diverge.0,
3021 )));
3022 }
3023 arm_interiors.push(interior);
3024 }
3025
3026 // (3a) Arms must not share interior nodes.
3027 for i in 0..arm_interiors.len() {
3028 for j in (i + 1)..arm_interiors.len() {
3029 if let Some(shared) = arm_interiors[i].intersection(&arm_interiors[j]).next() {
3030 return Err(invalid(format!(
3031 "arms {i} and {j} share interior Node#{}; arms must be \
3032 internally disjoint",
3033 shared.0,
3034 )));
3035 }
3036 }
3037 }
3038
3039 // (3b) No arm-interior node may be read from outside the branch.
3040 // The branch's universe is the union of all arm interiors plus
3041 // the merge node; reconverge_at reading an arm exit is the one
3042 // legitimate "external" consumer.
3043 let mut branch_universe: HashSet<NodeId> = HashSet::new();
3044 for interior in &arm_interiors {
3045 branch_universe.extend(interior.iter().copied());
3046 }
3047 branch_universe.insert(reconverge_at);
3048 for (i, interior) in arm_interiors.iter().enumerate() {
3049 for &m in interior {
3050 if let Some(cs) = consumers.get(&m) {
3051 for &c in cs {
3052 if !branch_universe.contains(&c) {
3053 return Err(invalid(format!(
3054 "arm {i} interior Node#{} is read from outside \
3055 the branch by Node#{}; arm interiors must not be \
3056 reachable from outside the branch",
3057 m.0, c.0,
3058 )));
3059 }
3060 }
3061 }
3062 }
3063 }
3064
3065 // All validation passed — emit the Branch node. Its inputs ARE the
3066 // arm exits, in priority order (arm 0 first); reconverge_at is
3067 // carried on the op. Shape/dtype mirror arm 0 (the uniform merge
3068 // type validated above).
3069 let branch = graph.push(Node {
3070 op: Op::Branch { reconverge_at },
3071 inputs: self.arms.clone(),
3072 shape: want_shape,
3073 dtype: want_dtype,
3074 });
3075 Ok(Some(branch))
3076 }
3077}
3078
3079/// A shared, mutable graph. Builders clone this cheaply and hand it to
3080/// every derived tensor so that all tensors in one computation point to
3081/// the same arena.
3082pub type SharedGraph = Arc<RwLock<Graph>>;
3083
3084/// A handle to a node in a shared graph. Cheap to clone. Carries the
3085/// graph reference so builder methods have everything they need to append
3086/// a new node.
3087#[derive(Debug, Clone)]
3088pub struct NodeHandle {
3089 graph: SharedGraph,
3090 id: NodeId,
3091}
3092
3093impl NodeHandle {
3094 /// Wrap an existing `(graph, node_id)` pair as a NodeHandle handle.
3095 /// Used by graph-rewriting passes (e.g., `opt::insert_copies`)
3096 /// that produce new root `NodeId`s and need to hand them back to
3097 /// call sites as Tensors.
3098 pub fn from_existing(graph: SharedGraph, id: NodeId) -> Self {
3099 Self { graph, id }
3100 }
3101
3102 /// The node ID this handle points to.
3103 pub fn id(&self) -> NodeId {
3104 self.id
3105 }
3106
3107 /// The shared graph this handle belongs to. Exposed so executors and
3108 /// tests can walk the underlying arena.
3109 pub fn graph(&self) -> &SharedGraph {
3110 &self.graph
3111 }
3112
3113 /// This tensor's graph identity — see [`GraphId`].
3114 ///
3115 /// Two tensors can be combined **iff** their `graph_id`s match. Affinity is
3116 /// still *checked* by pointer identity (`Arc::ptr_eq`, which cannot alias);
3117 /// this is the human-readable form, so a failure can say *which* graphs are
3118 /// involved rather than only that they differ.
3119 pub fn graph_id(&self) -> GraphId {
3120 self.graph.read().unwrap().id()
3121 }
3122
3123 /// The shape of this tensor, read from the underlying node.
3124 pub fn shape(&self) -> Shape {
3125 self.graph.read().unwrap().node(self.id).shape.clone()
3126 }
3127
3128 /// The dtype of this tensor, read from the underlying node.
3129 pub fn dtype(&self) -> DType {
3130 self.graph.read().unwrap().node(self.id).dtype
3131 }
3132
3133 /// Phase 7.5 work item G: look up the realized-storage slot for
3134 /// this tensor's node, if any. Returns an Arc clone so the slot
3135 /// stays in the map after this call and the caller's Arc keeps
3136 /// the bytes alive even if a later eviction removes the map
3137 /// entry. `None` means "not realized yet" — the caller should
3138 /// realize the graph first.
3139 pub fn storage_for(&self) -> Option<Arc<RwLock<Storage>>> {
3140 self.graph.read().unwrap().storage_for(self.id)
3141 }
3142
3143 /// The placement hint for this tensor's node, if one was set. `None`
3144 /// means "inherit from the executor's default device."
3145 pub fn placement(&self) -> Option<DeviceLocation> {
3146 self.graph.read().unwrap().placement(self.id)
3147 }
3148
3149 /// Tag this tensor's node with a target device. The executor will
3150 /// validate (post-Phase-1) that the node's op can be evaluated on
3151 /// that device. Returns the same `NodeHandle` handle so this composes
3152 /// with builder-style graph construction:
3153 ///
3154 /// ```ignore
3155 /// let y = a.matmul(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
3156 /// ```
3157 pub fn on_device(self, loc: DeviceLocation) -> Self {
3158 self.graph.write().unwrap().set_placement(self.id, loc);
3159 self
3160 }
3161
3162 /// Release this tensor's device-resident storage. Appends an
3163 /// `Op::Release` node whose output is a zero-element marker (shape
3164 /// `[0]`, same dtype as self). Destructive on `self` — after this
3165 /// op runs, `self`'s storage is gone.
3166 ///
3167 /// The ordering-analysis pass (`opt::derive_ordering`, arriving in
3168 /// a follow-up PR) automatically pins the Release to run after
3169 /// every non-destructive reader of `self`. Callers should NOT
3170 /// invoke this directly in a graph that has other readers of
3171 /// `self` until that pass is in place — today's executor has no
3172 /// mechanism to stop them running in the wrong order.
3173 pub fn release(&self) -> Self {
3174 let dtype = self.dtype();
3175 let id = self.graph.write().unwrap().push(Node {
3176 op: Op::Release,
3177 inputs: vec![self.id],
3178 shape: Shape::from_dims(&[0]),
3179 dtype,
3180 });
3181 NodeHandle {
3182 graph: Arc::clone(&self.graph),
3183 id,
3184 }
3185 }
3186
3187 /// Move this tensor's data to `target` device — destroying the
3188 /// source in the process. Appends an `Op::Move` node. The output
3189 /// has the same shape and dtype as the input and lives on
3190 /// `target`; the source's device storage is freed once the op
3191 /// runs.
3192 ///
3193 /// Semantically equivalent to `copy_to_device(target)` followed
3194 /// by dropping the source. Use this when you KNOW the source
3195 /// won't be needed after the transfer — it lets backends skip
3196 /// the intermediate alloc in fast-path cases and lets the
3197 /// scheduler free the source's device memory immediately.
3198 ///
3199 /// If the source may still be read by other ops, use
3200 /// [`Self::copy_to_device`] instead — Copy leaves the source
3201 /// resident.
3202 ///
3203 /// The ordering-analysis pass (`opt::derive_ordering`)
3204 /// automatically pins this op to run after every non-destructive
3205 /// reader of the source. The caller does NOT need to worry about
3206 /// topo ordering — just emit the Move wherever the data-flow
3207 /// says it should go.
3208 pub fn move_to_device(&self, target: DeviceLocation) -> Self {
3209 let shape = self.shape();
3210 let dtype = self.dtype();
3211 let id = self.graph.write().unwrap().push(Node {
3212 op: Op::Move { target },
3213 inputs: vec![self.id],
3214 shape,
3215 dtype,
3216 });
3217 NodeHandle {
3218 graph: Arc::clone(&self.graph),
3219 id,
3220 }
3221 }
3222
3223 /// Copy this tensor's data to `target` device. Source stays
3224 /// resident. Appends an `Op::Copy` node. The output has the same
3225 /// shape and dtype as the input; only residency changes.
3226 ///
3227 /// Same-device copies are still a legal thing to ask for — the
3228 /// backend can optimize them into a cheap clone (or the scheduler
3229 /// can elide the Copy node entirely). Cross-device copies resolve
3230 /// through the pipelined executor's Copy arm (kernel lookup at
3231 /// `(OpKind::Copy, [dt, dt], source backend)`) — today a host
3232 /// round-trip; P2P comes later.
3233 pub fn copy_to_device(&self, target: DeviceLocation) -> Self {
3234 let shape = self.shape();
3235 let dtype = self.dtype();
3236 let id = self.graph.write().unwrap().push(Node {
3237 op: Op::Copy { target },
3238 inputs: vec![self.id],
3239 shape,
3240 dtype,
3241 });
3242 NodeHandle {
3243 graph: Arc::clone(&self.graph),
3244 id,
3245 }
3246 }
3247
3248 /// Project one logical output out of a multi-output producer node.
3249 ///
3250 /// `self` must have been declared as a multi-output producer via
3251 /// [`Graph::set_output_views`] (Session 2's authoring contract will
3252 /// drive this for real fused ops; Session 1 tests drive it
3253 /// directly). The View's output shape, dtype, and layout come from
3254 /// `output_views(self.id)[slot]`. Zero bytes are moved at
3255 /// realization time — the View shares the producer's bundled
3256 /// `Arc<RwLock<Storage>>` and exposes the slot's typed window.
3257 ///
3258 /// **Returns `Result`**: the producer must have declared its slot
3259 /// specs; `slot` must be in range. Errors at graph-build time
3260 /// (per the `validate-at-graph-build-time` rule); the executor
3261 /// never sees a malformed View node.
3262 pub fn view(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3263 let mut graph_w = self.graph.write().unwrap();
3264 let (slot_shape, slot_dtype, slot_byte_offset, slot_layout) = {
3265 let views = graph_w.output_views(self.id).ok_or_else(|| {
3266 fuel_ir::Error::Msg(format!(
3267 "NodeHandle::view: Node#{} is not a multi-output \
3268 producer (no output_views registered)",
3269 self.id.0,
3270 ))
3271 .bt()
3272 })?;
3273 let idx = slot as usize;
3274 let v = views.get(idx).ok_or_else(|| {
3275 fuel_ir::Error::Msg(format!(
3276 "NodeHandle::view: slot {idx} out of range \
3277 (producer has {} slots)",
3278 views.len(),
3279 ))
3280 .bt()
3281 })?;
3282 (v.shape.clone(), v.dtype, v.byte_offset, v.layout.clone())
3283 };
3284 let id = graph_w.push(Node {
3285 op: Op::View { slot },
3286 inputs: vec![self.id],
3287 shape: slot_shape.clone(),
3288 dtype: slot_dtype,
3289 });
3290 // Compose the slot's intrinsic layout (which carries
3291 // slot-relative strides + start_offset) with the slot's
3292 // byte_offset inside the bundle. The result is the layout a
3293 // downstream kernel sees when treating the producer's bundle
3294 // bytes as `slot_dtype` elements: start_offset is in slot-
3295 // dtype-element units; bundle byte_offset is divided by the
3296 // dtype's size_in_bytes to land at the slot's first byte. The
3297 // bundled allocator (`compose_bundle`) aligns each slot's
3298 // byte_offset to its dtype size — so the division is exact.
3299 let dtype_bytes = slot_dtype.size_in_bytes().max(1);
3300 let extra_offset = slot_byte_offset / dtype_bytes;
3301 let effective_layout = if extra_offset == 0 {
3302 slot_layout
3303 } else {
3304 Layout::new(
3305 slot_layout.shape().clone(),
3306 slot_layout.stride().to_vec().into_iter().collect(),
3307 slot_layout.start_offset() + extra_offset,
3308 )
3309 };
3310 // The side-table is set whenever the effective layout differs
3311 // from `Layout::contiguous(slot_shape)` — i.e. whenever the
3312 // slot has a strided layout OR a non-zero composed offset
3313 // (slot 1+ in any bundle).
3314 if effective_layout != Layout::contiguous(slot_shape) {
3315 graph_w.set_layout(id, effective_layout);
3316 }
3317 drop(graph_w);
3318 Ok(NodeHandle {
3319 graph: Arc::clone(&self.graph),
3320 id,
3321 })
3322 }
3323
3324 /// Owned variant of [`Self::view`] — the slot's bytes are copied
3325 /// into a fresh contiguous Storage at realization time, so the
3326 /// producer's bundle Arc can drop independently. Output layout
3327 /// is always contiguous.
3328 ///
3329 /// Same validation as `view`; same error surface.
3330 pub fn view_owned(&self, slot: u32) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3331 let mut graph_w = self.graph.write().unwrap();
3332 let (slot_shape, slot_dtype) = {
3333 let views = graph_w.output_views(self.id).ok_or_else(|| {
3334 fuel_ir::Error::Msg(format!(
3335 "NodeHandle::view_owned: Node#{} is not a multi-output \
3336 producer (no output_views registered)",
3337 self.id.0,
3338 ))
3339 .bt()
3340 })?;
3341 let idx = slot as usize;
3342 let v = views.get(idx).ok_or_else(|| {
3343 fuel_ir::Error::Msg(format!(
3344 "NodeHandle::view_owned: slot {idx} out of range \
3345 (producer has {} slots)",
3346 views.len(),
3347 ))
3348 .bt()
3349 })?;
3350 (v.shape.clone(), v.dtype)
3351 };
3352 let id = graph_w.push(Node {
3353 op: Op::ViewOwned { slot },
3354 inputs: vec![self.id],
3355 shape: slot_shape,
3356 dtype: slot_dtype,
3357 });
3358 drop(graph_w);
3359 Ok(NodeHandle {
3360 graph: Arc::clone(&self.graph),
3361 id,
3362 })
3363 }
3364
3365 /// Append an `Op::WriteSlice` node — copies `source`'s bytes into
3366 /// `self` at the rectangular slab defined by `ranges`. Per-axis,
3367 /// `ranges[i] = (start, end)` is the half-open destination range;
3368 /// `source.dims()[i]` must equal `end - start`, and `end` must
3369 /// not exceed `self.dims()[i]`. Dtypes must match.
3370 ///
3371 /// Destructive on `self`: after the write, `self`'s NodeId is no
3372 /// longer readable (the scheduler pins this op to run after every
3373 /// other reader of `self` via [`opt::derive_ordering`]). The
3374 /// returned tensor adopts `self`'s Storage and Layout; downstream
3375 /// consumers read post-write bytes through this NodeId.
3376 ///
3377 /// Phase E.3.2: introduced to back persistent KV-cache writes
3378 /// (`InferenceContext` + `KvCache`). Non-differentiable.
3379 ///
3380 /// **Returns `Result`**: rank/shape/range mismatches surface as a
3381 /// typed error.
3382 pub fn write_slice(
3383 &self,
3384 source: &NodeHandle,
3385 ranges: Vec<(usize, usize)>,
3386 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3387 self.require_same_graph(source, "write_slice", "source")?;
3388 let dest_shape = self.shape();
3389 let dest_dims = dest_shape.dims();
3390 let src_shape = source.shape();
3391 let src_dims = src_shape.dims();
3392 let rank = dest_dims.len();
3393 if ranges.len() != rank {
3394 return Err(fuel_ir::Error::Msg(format!(
3395 "write_slice: ranges.len() ({}) must equal destination rank ({rank})",
3396 ranges.len(),
3397 ))
3398 .bt());
3399 }
3400 if src_dims.len() != rank {
3401 return Err(fuel_ir::Error::Msg(format!(
3402 "write_slice: source rank ({}) must equal destination rank ({rank})",
3403 src_dims.len(),
3404 ))
3405 .bt());
3406 }
3407 for (i, &(start, end)) in ranges.iter().enumerate() {
3408 if end < start {
3409 return Err(fuel_ir::Error::Msg(format!(
3410 "write_slice: ranges[{i}] = ({start}, {end}) has end < start"
3411 ))
3412 .bt());
3413 }
3414 if end > dest_dims[i] {
3415 return Err(fuel_ir::Error::Msg(format!(
3416 "write_slice: ranges[{i}].end ({end}) > destination dim {i} ({})",
3417 dest_dims[i],
3418 ))
3419 .bt());
3420 }
3421 let slab = end - start;
3422 if src_dims[i] != slab {
3423 return Err(fuel_ir::Error::Msg(format!(
3424 "write_slice: source dim {i} ({}) must equal slab width ({slab}) \
3425 = ranges[{i}].end - ranges[{i}].start",
3426 src_dims[i],
3427 ))
3428 .bt());
3429 }
3430 }
3431 if self.dtype() != source.dtype() {
3432 return Err(fuel_ir::Error::Msg(format!(
3433 "write_slice: dtype mismatch — destination {:?} vs source {:?}",
3434 self.dtype(),
3435 source.dtype(),
3436 ))
3437 .bt());
3438 }
3439 let dtype = self.dtype();
3440 let id = self.graph.write().unwrap().push(Node {
3441 op: Op::WriteSlice {
3442 ranges,
3443 dyn_offset: None,
3444 },
3445 inputs: vec![self.id, source.id],
3446 shape: dest_shape,
3447 dtype,
3448 });
3449 Ok(NodeHandle {
3450 graph: Arc::clone(&self.graph),
3451 id,
3452 })
3453 }
3454
3455 /// Append an `Op::WriteSlice` whose start on `dyn_axis` is a runtime
3456 /// value resolved through the per-pass [`fuel_ir::SymEnv`] at
3457 /// realize, rather than the build-time `ranges[dyn_axis].0`.
3458 ///
3459 /// This is the **input-determined** dynamic-offset path (a
3460 /// [`DynScalar`] over the one `SymEnv`), distinct from
3461 /// [`Self::write_slice_rotating`]'s **data-determined** position (a
3462 /// tensor input read mid-pass). It backs the persistent decode
3463 /// KV-cache write: the append offset is `cached_len`, a per-token
3464 /// runtime value over a fixed-capacity buffer, so the graph
3465 /// structure (and every shape) stays identical across tokens and the
3466 /// plan is reused (Phase D symbolic extents).
3467 ///
3468 /// On `dyn_axis`, `ranges[dyn_axis].0` is ignored (the start is
3469 /// dynamic) and `ranges[dyn_axis].1 - ranges[dyn_axis].0` is the slab
3470 /// width, which must equal `source.dims()[dyn_axis]` and not exceed
3471 /// the destination capacity on that axis. On every other axis the
3472 /// same shape contract as [`Self::write_slice`] applies. The runtime
3473 /// `offset + width` is bounds-checked against the destination
3474 /// capacity at realize (a typed error, never a panic).
3475 ///
3476 /// **Returns `Result`**: rank/dtype/axis-bound/width mismatches
3477 /// surface as a typed error at build time.
3478 pub fn write_slice_dyn(
3479 &self,
3480 source: &NodeHandle,
3481 ranges: Vec<(usize, usize)>,
3482 dyn_axis: usize,
3483 offset: DynScalar,
3484 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3485 self.require_same_graph(source, "write_slice_dyn", "source")?;
3486 let dest_shape = self.shape();
3487 let dest_dims = dest_shape.dims();
3488 let src_shape = source.shape();
3489 let src_dims = src_shape.dims();
3490 let rank = dest_dims.len();
3491 if ranges.len() != rank {
3492 return Err(fuel_ir::Error::Msg(format!(
3493 "write_slice_dyn: ranges.len() ({}) must equal destination rank ({rank})",
3494 ranges.len(),
3495 ))
3496 .bt());
3497 }
3498 if src_dims.len() != rank {
3499 return Err(fuel_ir::Error::Msg(format!(
3500 "write_slice_dyn: source rank ({}) must equal destination rank ({rank})",
3501 src_dims.len(),
3502 ))
3503 .bt());
3504 }
3505 if dyn_axis >= rank {
3506 return Err(fuel_ir::Error::Msg(format!(
3507 "write_slice_dyn: dyn_axis ({dyn_axis}) out of bounds for rank {rank}",
3508 ))
3509 .bt());
3510 }
3511 for (i, &(start, end)) in ranges.iter().enumerate() {
3512 if end < start {
3513 return Err(fuel_ir::Error::Msg(format!(
3514 "write_slice_dyn: ranges[{i}] = ({start}, {end}) has end < start"
3515 ))
3516 .bt());
3517 }
3518 let slab = end - start;
3519 if src_dims[i] != slab {
3520 return Err(fuel_ir::Error::Msg(format!(
3521 "write_slice_dyn: source dim {i} ({}) must equal slab width ({slab}) \
3522 = ranges[{i}].end - ranges[{i}].start",
3523 src_dims[i],
3524 ))
3525 .bt());
3526 }
3527 if i == dyn_axis {
3528 // The start on `dyn_axis` is dynamic, so `ranges[i].0`/`.1`
3529 // are not bounded by `dest_dims[i]` here — only the slab
3530 // WIDTH must fit the capacity. The runtime `offset + width`
3531 // is bounds-checked against `dest_dims[i]` at realize.
3532 if slab > dest_dims[i] {
3533 return Err(fuel_ir::Error::Msg(format!(
3534 "write_slice_dyn: dynamic-axis slab width ({slab}) > destination capacity \
3535 dim {i} ({})",
3536 dest_dims[i],
3537 ))
3538 .bt());
3539 }
3540 } else if end > dest_dims[i] {
3541 return Err(fuel_ir::Error::Msg(format!(
3542 "write_slice_dyn: ranges[{i}].end ({end}) > destination dim {i} ({})",
3543 dest_dims[i],
3544 ))
3545 .bt());
3546 }
3547 }
3548 if self.dtype() != source.dtype() {
3549 return Err(fuel_ir::Error::Msg(format!(
3550 "write_slice_dyn: dtype mismatch — destination {:?} vs source {:?}",
3551 self.dtype(),
3552 source.dtype(),
3553 ))
3554 .bt());
3555 }
3556 let dtype = self.dtype();
3557 let id = self.graph.write().unwrap().push(Node {
3558 op: Op::WriteSlice {
3559 ranges,
3560 dyn_offset: Some((dyn_axis, offset)),
3561 },
3562 inputs: vec![self.id, source.id],
3563 shape: dest_shape,
3564 dtype,
3565 });
3566 Ok(NodeHandle {
3567 graph: Arc::clone(&self.graph),
3568 id,
3569 })
3570 }
3571
3572 /// Append an [`Op::WriteSliceRotating`] node — copies `source`'s
3573 /// bytes into `self` at the rectangular slab defined by `ranges`,
3574 /// with the `axis` axis wrapping modulo `modulus`. The dynamic
3575 /// write position comes through `position` (a rank-0 `U32`
3576 /// tensor); the kernel computes `start = position % modulus` and
3577 /// splits the write across the ring boundary if needed.
3578 ///
3579 /// `ranges[axis].0` is ignored (the rotating-axis start is
3580 /// dynamic). `ranges[axis].1 - ranges[axis].0` is the write
3581 /// length on the rotating axis and must equal `source.dims()[axis]`.
3582 /// On every other axis the same shape contract as `write_slice`
3583 /// applies.
3584 ///
3585 /// Destructive on `self`; scheduled like `write_slice`. Backward
3586 /// panics — sliding-window KV-cache writes are forward-only.
3587 ///
3588 /// **Returns `Result`**: rank/dtype/axis-bound/modulus/range
3589 /// mismatches surface as a typed error at build time.
3590 pub fn write_slice_rotating(
3591 &self,
3592 source: &NodeHandle,
3593 position: &NodeHandle,
3594 axis: usize,
3595 modulus: usize,
3596 ranges: Vec<(usize, usize)>,
3597 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3598 self.require_same_graph(source, "write_slice_rotating", "source")?;
3599 self.require_same_graph(position, "write_slice_rotating", "position")?;
3600 let dest_shape = self.shape();
3601 let dest_dims = dest_shape.dims();
3602 let src_shape = source.shape();
3603 let src_dims = src_shape.dims();
3604 let rank = dest_dims.len();
3605 if ranges.len() != rank {
3606 return Err(fuel_ir::Error::Msg(format!(
3607 "write_slice_rotating: ranges.len() ({}) must equal destination rank ({rank})",
3608 ranges.len(),
3609 ))
3610 .bt());
3611 }
3612 if src_dims.len() != rank {
3613 return Err(fuel_ir::Error::Msg(format!(
3614 "write_slice_rotating: source rank ({}) must equal destination rank ({rank})",
3615 src_dims.len(),
3616 ))
3617 .bt());
3618 }
3619 if axis >= rank {
3620 return Err(fuel_ir::Error::Msg(format!(
3621 "write_slice_rotating: axis {axis} out of bounds for rank {rank}",
3622 ))
3623 .bt());
3624 }
3625 if modulus == 0 {
3626 return Err(
3627 fuel_ir::Error::Msg("write_slice_rotating: modulus must be >= 1".into()).bt(),
3628 );
3629 }
3630 if modulus > dest_dims[axis] {
3631 return Err(fuel_ir::Error::Msg(format!(
3632 "write_slice_rotating: modulus ({modulus}) must not exceed destination dim {axis} ({})",
3633 dest_dims[axis],
3634 )).bt());
3635 }
3636 for (i, &(start, end)) in ranges.iter().enumerate() {
3637 if end < start {
3638 return Err(fuel_ir::Error::Msg(format!(
3639 "write_slice_rotating: ranges[{i}] = ({start}, {end}) has end < start"
3640 ))
3641 .bt());
3642 }
3643 let slab = end - start;
3644 if i == axis {
3645 if slab == 0 {
3646 return Err(fuel_ir::Error::Msg(format!(
3647 "write_slice_rotating: ranges[axis={axis}] slab is 0",
3648 ))
3649 .bt());
3650 }
3651 if slab > modulus {
3652 return Err(fuel_ir::Error::Msg(format!(
3653 "write_slice_rotating: rotating-axis write length ({slab}) > modulus ({modulus})",
3654 )).bt());
3655 }
3656 if src_dims[i] != slab {
3657 return Err(fuel_ir::Error::Msg(format!(
3658 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3659 src_dims[i],
3660 ))
3661 .bt());
3662 }
3663 // ranges[axis].1 itself isn't bounded by dest_dims[axis] —
3664 // the kernel wraps the start, so the logical end is meaningless.
3665 // We still require .1 <= modulus to make the slab description
3666 // self-consistent inside the window.
3667 if end > modulus {
3668 return Err(fuel_ir::Error::Msg(format!(
3669 "write_slice_rotating: ranges[axis={axis}].end ({end}) > modulus ({modulus})",
3670 )).bt());
3671 }
3672 } else {
3673 if end > dest_dims[i] {
3674 return Err(fuel_ir::Error::Msg(format!(
3675 "write_slice_rotating: ranges[{i}].end ({end}) > destination dim {i} ({})",
3676 dest_dims[i],
3677 ))
3678 .bt());
3679 }
3680 if src_dims[i] != slab {
3681 return Err(fuel_ir::Error::Msg(format!(
3682 "write_slice_rotating: source dim {i} ({}) must equal slab width ({slab})",
3683 src_dims[i],
3684 ))
3685 .bt());
3686 }
3687 }
3688 }
3689 if self.dtype() != source.dtype() {
3690 return Err(fuel_ir::Error::Msg(format!(
3691 "write_slice_rotating: dtype mismatch — destination {:?} vs source {:?}",
3692 self.dtype(),
3693 source.dtype(),
3694 ))
3695 .bt());
3696 }
3697 if position.dtype() != DType::U32 {
3698 return Err(fuel_ir::Error::Msg(format!(
3699 "write_slice_rotating: position must be U32, got {:?}",
3700 position.dtype(),
3701 ))
3702 .bt());
3703 }
3704 if !position.shape().dims().is_empty() {
3705 return Err(fuel_ir::Error::Msg(format!(
3706 "write_slice_rotating: position must be rank-0 scalar, got {:?}",
3707 position.shape().dims(),
3708 ))
3709 .bt());
3710 }
3711 let dtype = self.dtype();
3712 let id = self.graph.write().unwrap().push(Node {
3713 op: Op::WriteSliceRotating {
3714 axis,
3715 modulus,
3716 ranges,
3717 },
3718 inputs: vec![self.id, source.id, position.id],
3719 shape: dest_shape,
3720 dtype,
3721 });
3722 Ok(NodeHandle {
3723 graph: Arc::clone(&self.graph),
3724 id,
3725 })
3726 }
3727
3728 /// Append an [`Op::WriteSliceDoff`] node — copies `source`'s bytes
3729 /// into `self` at the rectangular slab defined by `ranges`, with
3730 /// the start on `axis` read from `offset` (a rank-0 `I64` tensor)
3731 /// **device-side** at kernel launch. No modulo wrap: `offset` is
3732 /// the raw start on `axis`.
3733 ///
3734 /// `ranges[axis].0` is ignored (the dynamic-axis start is device-
3735 /// resident). `ranges[axis].1 - ranges[axis].0` is the write width
3736 /// on `axis` and must equal `source.dims()[axis]`. On every other
3737 /// axis the same shape contract as [`write_slice`](Self::write_slice)
3738 /// applies.
3739 ///
3740 /// **Bounds are the caller's contract**: `offset` is device-only at
3741 /// build time, so `offset + width <= dest_dims[axis]` cannot be
3742 /// checked here and the kernel does NOT clamp. The caller must size
3743 /// `self`'s capacity on `axis` to cover the largest offset (this is
3744 /// the CUDA-graph-capturable KV-cache append; `DecodeSession` sizes
3745 /// `max_seq`). The static slab width IS checked against capacity.
3746 ///
3747 /// Destructive on `self`; scheduled like `write_slice`. Backward
3748 /// panics — decode-time KV-cache appends are forward-only.
3749 ///
3750 /// **Returns `Result`**: rank / dtype / axis-bound / static-width /
3751 /// offset-dtype mismatches surface as a typed error at build time.
3752 pub fn write_slice_doff(
3753 &self,
3754 source: &NodeHandle,
3755 offset: &NodeHandle,
3756 axis: usize,
3757 ranges: Vec<(usize, usize)>,
3758 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
3759 self.require_same_graph(source, "write_slice_doff", "source")?;
3760 self.require_same_graph(offset, "write_slice_doff", "offset")?;
3761 let dest_shape = self.shape();
3762 let dest_dims = dest_shape.dims();
3763 let src_dims = source.shape().dims().to_vec();
3764 let rank = dest_dims.len();
3765 if ranges.len() != rank {
3766 return Err(fuel_ir::Error::Msg(format!(
3767 "write_slice_doff: ranges.len() ({}) must equal destination rank ({rank})",
3768 ranges.len(),
3769 ))
3770 .bt());
3771 }
3772 if src_dims.len() != rank {
3773 return Err(fuel_ir::Error::Msg(format!(
3774 "write_slice_doff: source rank ({}) must equal destination rank ({rank})",
3775 src_dims.len(),
3776 ))
3777 .bt());
3778 }
3779 if axis >= rank {
3780 return Err(fuel_ir::Error::Msg(format!(
3781 "write_slice_doff: axis {axis} out of bounds for rank {rank}",
3782 ))
3783 .bt());
3784 }
3785 for (i, &(start, end)) in ranges.iter().enumerate() {
3786 if end < start {
3787 return Err(fuel_ir::Error::Msg(format!(
3788 "write_slice_doff: ranges[{i}] = ({start}, {end}) has end < start"
3789 ))
3790 .bt());
3791 }
3792 let slab = end - start;
3793 if i == axis {
3794 if slab == 0 {
3795 return Err(fuel_ir::Error::Msg(format!(
3796 "write_slice_doff: ranges[axis={axis}] slab is 0",
3797 ))
3798 .bt());
3799 }
3800 // The write width can't exceed the buffer capacity on
3801 // `axis` even at offset 0 (the offset itself is dynamic
3802 // and bounds-checked device-side by the caller's sizing).
3803 if slab > dest_dims[axis] {
3804 return Err(fuel_ir::Error::Msg(format!(
3805 "write_slice_doff: dynamic-axis write width ({slab}) > destination dim {axis} ({})",
3806 dest_dims[axis],
3807 )).bt());
3808 }
3809 if src_dims[i] != slab {
3810 return Err(fuel_ir::Error::Msg(format!(
3811 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3812 src_dims[i],
3813 ))
3814 .bt());
3815 }
3816 } else {
3817 if end > dest_dims[i] {
3818 return Err(fuel_ir::Error::Msg(format!(
3819 "write_slice_doff: ranges[{i}].end ({end}) > destination dim {i} ({})",
3820 dest_dims[i],
3821 ))
3822 .bt());
3823 }
3824 if src_dims[i] != slab {
3825 return Err(fuel_ir::Error::Msg(format!(
3826 "write_slice_doff: source dim {i} ({}) must equal slab width ({slab})",
3827 src_dims[i],
3828 ))
3829 .bt());
3830 }
3831 }
3832 }
3833 if self.dtype() != source.dtype() {
3834 return Err(fuel_ir::Error::Msg(format!(
3835 "write_slice_doff: dtype mismatch — destination {:?} vs source {:?}",
3836 self.dtype(),
3837 source.dtype(),
3838 ))
3839 .bt());
3840 }
3841 if offset.dtype() != DType::I64 {
3842 return Err(fuel_ir::Error::Msg(format!(
3843 "write_slice_doff: offset must be I64 (device-resident start), got {:?}",
3844 offset.dtype(),
3845 ))
3846 .bt());
3847 }
3848 if !offset.shape().dims().is_empty() {
3849 return Err(fuel_ir::Error::Msg(format!(
3850 "write_slice_doff: offset must be rank-0 scalar, got {:?}",
3851 offset.shape().dims(),
3852 ))
3853 .bt());
3854 }
3855 let dtype = self.dtype();
3856 let id = self.graph.write().unwrap().push(Node {
3857 op: Op::WriteSliceDoff { axis, ranges },
3858 inputs: vec![self.id, source.id, offset.id],
3859 shape: dest_shape,
3860 dtype,
3861 });
3862 Ok(NodeHandle {
3863 graph: Arc::clone(&self.graph),
3864 id,
3865 })
3866 }
3867
3868 /// Build a `Const` tensor from an `f32` slice and shape on a fresh
3869 /// graph. The new graph is returned via the tensor's `graph` handle.
3870 ///
3871 /// `data` takes `impl Into<Arc<[f32]>>` so both `Vec<f32>` (one-time
3872 /// conversion at the call site) and `Arc<[f32]>` (free clone that
3873 /// shares buffers across forward passes) work.
3874 ///
3875 /// Phase 7.5 work item G2: `device` is the device on which the
3876 /// realized Storage is allocated. The graph's storage_map slot is
3877 /// populated with that Storage and `Op::Const` is emitted —
3878 /// no host-side `ConstData` payload rides on the node.
3879 pub fn from_f32(
3880 data: impl Into<Arc<[f32]>>,
3881 shape: impl Into<Shape>,
3882 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3883 ) -> Result<Self, fuel_ir::Error> {
3884 let v: Arc<[f32]> = data.into();
3885 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
3886 Self::from_host_buffer(buf, DType::F32, shape, device)
3887 }
3888
3889 /// Build a `Const` tensor from an `f64` slice and shape on a fresh graph.
3890 /// `device` selects where the realized Storage is allocated.
3891 pub fn from_f64(
3892 data: impl Into<Arc<[f64]>>,
3893 shape: impl Into<Shape>,
3894 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3895 ) -> Result<Self, fuel_ir::Error> {
3896 let v: Arc<[f64]> = data.into();
3897 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
3898 Self::from_host_buffer(buf, DType::F64, shape, device)
3899 }
3900
3901 /// Build a `Const` tensor from a `bf16` slice and shape on a fresh graph.
3902 /// `device` selects where the realized Storage is allocated.
3903 pub fn from_bf16(
3904 data: impl Into<Arc<[bf16]>>,
3905 shape: impl Into<Shape>,
3906 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3907 ) -> Result<Self, fuel_ir::Error> {
3908 let v: Arc<[bf16]> = data.into();
3909 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
3910 Self::from_host_buffer(buf, DType::BF16, shape, device)
3911 }
3912
3913 /// Build a `Const` tensor from an `f16` slice and shape on a fresh graph.
3914 /// `device` selects where the realized Storage is allocated.
3915 pub fn from_f16(
3916 data: impl Into<Arc<[f16]>>,
3917 shape: impl Into<Shape>,
3918 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3919 ) -> Result<Self, fuel_ir::Error> {
3920 let v: Arc<[f16]> = data.into();
3921 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
3922 Self::from_host_buffer(buf, DType::F16, shape, device)
3923 }
3924
3925 /// Build a `Const` tensor from a `u32` slice and shape on a fresh
3926 /// graph. Primarily used to construct index tensors for gather /
3927 /// scatter / index_select. `u32` is the index type all real fuel
3928 /// backends use (Candle CPU, CUDA, Metal), so keeping the reference
3929 /// on the same type means oracle-equivalence tests do not need any
3930 /// index-type translation. `device` selects where the realized
3931 /// Storage is allocated.
3932 pub fn from_u32(
3933 data: impl Into<Arc<[u32]>>,
3934 shape: impl Into<Shape>,
3935 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3936 ) -> Result<Self, fuel_ir::Error> {
3937 let v: Arc<[u32]> = data.into();
3938 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
3939 Self::from_host_buffer(buf, DType::U32, shape, device)
3940 }
3941
3942 /// G2 internal funnel: allocate Storage on `device` from `buf`,
3943 /// register the slot, emit `Op::Const`. Per-dtype `from_*` methods
3944 /// delegate here.
3945 fn from_host_buffer(
3946 buf: fuel_ir::HostBuffer,
3947 dtype: DType,
3948 shape: impl Into<Shape>,
3949 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3950 ) -> Result<Self, fuel_ir::Error> {
3951 let graph = Arc::new(RwLock::new(Graph::new()));
3952 Self::from_host_buffer_on(&graph, buf, dtype, shape, device)
3953 }
3954
3955 /// `from_host_buffer` against an **existing** graph — the shared body of the
3956 /// `from_*_on` family. Identical to `from_host_buffer` except that the caller
3957 /// supplies the graph instead of one being minted.
3958 fn from_host_buffer_on(
3959 graph: &SharedGraph,
3960 buf: fuel_ir::HostBuffer,
3961 dtype: DType,
3962 shape: impl Into<Shape>,
3963 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
3964 ) -> Result<Self, fuel_ir::Error> {
3965 let shape = shape.into();
3966 let n = host_buffer_elem_count(&buf);
3967 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM because
3968 // `docs/gaps.md` and `CLAUDE.md` both anchor on it -- a prose anchor is
3969 // rename-proof, so changing the words here would orphan two citations
3970 // that no identifier rename could have touched.
3971 if n != shape.elem_count() {
3972 return Err(fuel_ir::Error::Msg(format!(
3973 "NodeHandle::from_*: data length {n} does not match shape element count {}",
3974 shape.elem_count(),
3975 )));
3976 }
3977 // GAP-003: was `.expect(...)`. This is the sibling panic the row's
3978 // anchor could not see -- it carries a DIFFERENT message, and a
3979 // message-specific anchor is blind to exactly that.
3980 let backend_storage = device
3981 .storage_from_host_buffer_owned_dyn(buf)
3982 .map_err(|e| {
3983 fuel_ir::Error::Msg(format!(
3984 "NodeHandle::from_*: device.storage_from_host_buffer_owned_dyn failed: {e}"
3985 ))
3986 })?;
3987 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
3988 let id = {
3989 let mut g = graph.write().unwrap();
3990 let id = g.push(Node {
3991 op: Op::Const,
3992 inputs: vec![],
3993 shape,
3994 dtype,
3995 });
3996 g.set_storage(id, storage_arc);
3997 id
3998 };
3999 Ok(Self {
4000 graph: Arc::clone(graph),
4001 id,
4002 })
4003 }
4004
4005 /// Build an `f32` `Const` leaf **on the graph you pass in**, rather than on a
4006 /// fresh one.
4007 ///
4008 /// This is the non-anchor route for adding a tensor to an existing graph.
4009 /// `NodeHandle::from_f32` mints a NEW graph, so two `from_*` tensors can never be
4010 /// combined; `from_f32_on` puts the new leaf on `graph`, and
4011 /// [`const_f32_like`](Self::const_f32_like) does the same thing when what you
4012 /// have to hand is a sibling *tensor* rather than the graph itself.
4013 ///
4014 /// ```ignore
4015 /// let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
4016 /// let a = NodeHandle::from_f32_on(&g, a_data, [2, 3], &device);
4017 /// let w = NodeHandle::from_f32_on(&g, w_data, [3, 2], &device);
4018 /// let y = a.matmul(&w); // same graph ✓
4019 /// ```
4020 pub fn from_f32_on(
4021 graph: &SharedGraph,
4022 data: impl Into<Arc<[f32]>>,
4023 shape: impl Into<Shape>,
4024 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4025 ) -> Result<Self, fuel_ir::Error> {
4026 let v: Arc<[f32]> = data.into();
4027 let buf = fuel_ir::HostBuffer::F32(v.to_vec());
4028 Self::from_host_buffer_on(graph, buf, DType::F32, shape, device)
4029 }
4030
4031 /// `f64` sibling of [`from_f32_on`](Self::from_f32_on) — builds on the given
4032 /// graph rather than a fresh one.
4033 pub fn from_f64_on(
4034 graph: &SharedGraph,
4035 data: impl Into<Arc<[f64]>>,
4036 shape: impl Into<Shape>,
4037 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4038 ) -> Result<Self, fuel_ir::Error> {
4039 let v: Arc<[f64]> = data.into();
4040 let buf = fuel_ir::HostBuffer::F64(v.to_vec());
4041 Self::from_host_buffer_on(graph, buf, DType::F64, shape, device)
4042 }
4043
4044 /// `bf16` sibling of [`from_f32_on`](Self::from_f32_on). The common
4045 /// mixed-precision shape — f32 activations, bf16 weights — is exactly this
4046 /// plus [`from_f32_on`](Self::from_f32_on) against one shared graph.
4047 pub fn from_bf16_on(
4048 graph: &SharedGraph,
4049 data: impl Into<Arc<[half::bf16]>>,
4050 shape: impl Into<Shape>,
4051 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4052 ) -> Result<Self, fuel_ir::Error> {
4053 let v: Arc<[half::bf16]> = data.into();
4054 let buf = fuel_ir::HostBuffer::BF16(v.to_vec());
4055 Self::from_host_buffer_on(graph, buf, DType::BF16, shape, device)
4056 }
4057
4058 /// `f16` sibling of [`from_f32_on`](Self::from_f32_on).
4059 pub fn from_f16_on(
4060 graph: &SharedGraph,
4061 data: impl Into<Arc<[half::f16]>>,
4062 shape: impl Into<Shape>,
4063 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4064 ) -> Result<Self, fuel_ir::Error> {
4065 let v: Arc<[half::f16]> = data.into();
4066 let buf = fuel_ir::HostBuffer::F16(v.to_vec());
4067 Self::from_host_buffer_on(graph, buf, DType::F16, shape, device)
4068 }
4069
4070 /// `u32` sibling of [`from_f32_on`](Self::from_f32_on) — index tensors for
4071 /// gather/index_select built straight onto the graph they will be used on.
4072 pub fn from_u32_on(
4073 graph: &SharedGraph,
4074 data: impl Into<Arc<[u32]>>,
4075 shape: impl Into<Shape>,
4076 device: &Arc<dyn fuel_backend_contract::DynBackendDevice>,
4077 ) -> Result<Self, fuel_ir::Error> {
4078 let v: Arc<[u32]> = data.into();
4079 let buf = fuel_ir::HostBuffer::U32(v.to_vec());
4080 Self::from_host_buffer_on(graph, buf, DType::U32, shape, device)
4081 }
4082
4083 /// Phase 7.5 work item G2: build a `Const` leaf on a fresh graph
4084 /// whose realized bytes already live in `storage`. The graph's
4085 /// storage_map slot for the new node is populated with `storage`
4086 /// directly. The executor's slot-first dispatch returns the slot's
4087 /// Arc on realize.
4088 pub fn from_storage(
4089 storage: Arc<RwLock<Storage>>,
4090 shape: impl Into<Shape>,
4091 dtype: DType,
4092 ) -> Self {
4093 let shape = shape.into();
4094 // Sanity-check the slot's dtype matches the declared dtype.
4095 // The slot's bytes don't carry a logical shape — that's the
4096 // node's job — so we don't validate elem_count here.
4097 debug_assert_eq!(
4098 storage.read().unwrap().dtype(),
4099 dtype,
4100 "NodeHandle::from_storage: declared dtype {:?} does not match storage dtype {:?}",
4101 dtype,
4102 storage.read().unwrap().dtype(),
4103 );
4104 let graph = Arc::new(RwLock::new(Graph::new()));
4105 let id = {
4106 let mut g = graph.write().unwrap();
4107 let id = g.push(Node {
4108 op: Op::Const,
4109 inputs: vec![],
4110 shape,
4111 dtype,
4112 });
4113 g.set_storage(id, storage);
4114 id
4115 };
4116 Self { graph, id }
4117 }
4118
4119 /// Build a second `Const` tensor that lives on the same graph as
4120 /// `self`. Use this to add more inputs to an existing computation.
4121 ///
4122 /// Phase 7.5 G2: the realized Storage is allocated on the device
4123 /// derived from `self`'s graph (any existing slot's device — the
4124 /// graph always has at least one slot-bearing leaf by the time
4125 /// const_*_like is called). For cross-device const construction,
4126 /// build a fresh graph with [`NodeHandle::from_f32`] and link via
4127 /// [`Op::Move`] / [`Op::Copy`].
4128 pub fn const_f32_like(
4129 &self,
4130 data: impl Into<Arc<[f32]>>,
4131 shape: impl Into<Shape>,
4132 ) -> Result<Self, fuel_ir::Error> {
4133 let v: Arc<[f32]> = data.into();
4134 self.const_like_host_buffer(fuel_ir::HostBuffer::F32(v.to_vec()), DType::F32, shape)
4135 }
4136
4137 /// Build a second `Const f64` tensor on the same graph as `self`.
4138 pub fn const_f64_like(
4139 &self,
4140 data: impl Into<Arc<[f64]>>,
4141 shape: impl Into<Shape>,
4142 ) -> Result<Self, fuel_ir::Error> {
4143 let v: Arc<[f64]> = data.into();
4144 self.const_like_host_buffer(fuel_ir::HostBuffer::F64(v.to_vec()), DType::F64, shape)
4145 }
4146
4147 /// Build a second `Const bf16` tensor on the same graph as `self`.
4148 pub fn const_bf16_like(
4149 &self,
4150 data: impl Into<Arc<[bf16]>>,
4151 shape: impl Into<Shape>,
4152 ) -> Result<Self, fuel_ir::Error> {
4153 let v: Arc<[bf16]> = data.into();
4154 self.const_like_host_buffer(fuel_ir::HostBuffer::BF16(v.to_vec()), DType::BF16, shape)
4155 }
4156
4157 /// Build a second `Const f16` tensor on the same graph as `self`.
4158 pub fn const_f16_like(
4159 &self,
4160 data: impl Into<Arc<[f16]>>,
4161 shape: impl Into<Shape>,
4162 ) -> Result<Self, fuel_ir::Error> {
4163 let v: Arc<[f16]> = data.into();
4164 self.const_like_host_buffer(fuel_ir::HostBuffer::F16(v.to_vec()), DType::F16, shape)
4165 }
4166
4167 /// Build a second `Const u32` (index) tensor on the same graph as `self`.
4168 pub fn const_u32_like(
4169 &self,
4170 data: impl Into<Arc<[u32]>>,
4171 shape: impl Into<Shape>,
4172 ) -> Result<Self, fuel_ir::Error> {
4173 let v: Arc<[u32]> = data.into();
4174 self.const_like_host_buffer(fuel_ir::HostBuffer::U32(v.to_vec()), DType::U32, shape)
4175 }
4176
4177 /// Build a sibling U8 `Const` on the same graph. Used by
4178 /// byte-stream inputs (e.g. NF4 quantized weights packed two
4179 /// codes per byte).
4180 pub fn const_u8_like(
4181 &self,
4182 data: impl Into<Arc<[u8]>>,
4183 shape: impl Into<Shape>,
4184 ) -> Result<Self, fuel_ir::Error> {
4185 let v: Arc<[u8]> = data.into();
4186 self.const_like_host_buffer(fuel_ir::HostBuffer::U8(v.to_vec()), DType::U8, shape)
4187 }
4188
4189 /// Build a sibling I64 `Const` on the same graph. Used by
4190 /// integer-target ops (e.g. cross-entropy with class indices in
4191 /// PyTorch convention).
4192 pub fn const_i64_like(
4193 &self,
4194 data: impl Into<Arc<[i64]>>,
4195 shape: impl Into<Shape>,
4196 ) -> Result<Self, fuel_ir::Error> {
4197 let v: Arc<[i64]> = data.into();
4198 self.const_like_host_buffer(fuel_ir::HostBuffer::I64(v.to_vec()), DType::I64, shape)
4199 }
4200
4201 /// G2 internal funnel for the per-graph const_*_like family. The
4202 /// device is derived from `self`'s graph slot (any existing one)
4203 /// so callers don't have to thread a device through hot paths
4204 /// like RoPE table construction or LoRA application — the const
4205 /// goes on the same device as the graph it joins.
4206 fn const_like_host_buffer(
4207 &self,
4208 buf: fuel_ir::HostBuffer,
4209 dtype: DType,
4210 shape: impl Into<Shape>,
4211 ) -> Result<Self, fuel_ir::Error> {
4212 let shape = shape.into();
4213 let n = host_buffer_elem_count(&buf);
4214 // GAP-003: was `assert_eq!`. The message is preserved VERBATIM -- gaps.md
4215 // and CLAUDE.md both anchor on this prose, and a prose anchor is the one
4216 // an identifier rename cannot reach.
4217 if n != shape.elem_count() {
4218 return Err(fuel_ir::Error::Msg(format!(
4219 "const_*_like: data length {n} does not match shape element count {}",
4220 shape.elem_count(),
4221 )));
4222 }
4223 let device = pick_device_from_graph(&self.graph);
4224 // GAP-003: the sibling panic, converted with it -- the same pair
4225 // `from_host_buffer_on` had, and the second anchor the row named.
4226 let backend_storage = device
4227 .storage_from_host_buffer_owned_dyn(buf)
4228 .map_err(|e| {
4229 fuel_ir::Error::Msg(format!(
4230 "NodeHandle::const_like: device.storage_from_host_buffer_owned_dyn failed: {e}"
4231 ))
4232 })?;
4233 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
4234 let id = {
4235 let mut g = self.graph.write().unwrap();
4236 let id = g.push(Node {
4237 op: Op::Const,
4238 inputs: vec![],
4239 shape,
4240 dtype,
4241 });
4242 g.set_storage(id, storage_arc);
4243 id
4244 };
4245 Ok(Self {
4246 graph: self.graph.clone(),
4247 id,
4248 })
4249 }
4250
4251 /// Push a `Const` node on the same graph as `self` **without**
4252 /// populating the graph's storage_map. The caller is responsible
4253 /// for binding the storage Arc into the realize call's initial
4254 /// StorageCache, typically via
4255 /// [`InferenceContext::insert`](../fuel_core/inference_context/struct.InferenceContext.html#method.insert).
4256 ///
4257 /// Used by the Phase 7.6 step 9c E.3.3 forward path to bind
4258 /// pre-allocated KV-cache storage Arcs (held as the new
4259 /// `Arc<RwLock<fuel_memory::Storage>>` type, not the legacy
4260 /// `fuel_backend_contract::Storage` that `const_like_from_storage` takes)
4261 /// into a per-step graph without re-uploading or type-converting.
4262 ///
4263 /// **Caller contract**: the same NodeId must appear in the
4264 /// `initial` StorageCache passed to the realize call. If not, the
4265 /// executor surfaces a clean error pointing at the missing slot
4266 /// — there's no implicit fallback to `graph.storage_map`.
4267 pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: DType) -> Self {
4268 let shape = shape.into();
4269 let id = {
4270 let mut g = self.graph.write().unwrap();
4271 g.push(Node {
4272 op: Op::Const,
4273 inputs: vec![],
4274 shape,
4275 dtype,
4276 })
4277 };
4278 Self {
4279 graph: self.graph.clone(),
4280 id,
4281 }
4282 }
4283
4284 /// Phase 7.5 work item G2: build a second `Const` leaf on the same
4285 /// graph as `self` whose realized bytes already live in `storage`.
4286 /// Companion to [`NodeHandle::from_storage`] for the multi-input case.
4287 pub fn const_like_from_storage(
4288 &self,
4289 storage: Arc<RwLock<Storage>>,
4290 shape: impl Into<Shape>,
4291 dtype: DType,
4292 ) -> Self {
4293 let shape = shape.into();
4294 debug_assert_eq!(
4295 storage.read().unwrap().dtype(),
4296 dtype,
4297 "NodeHandle::const_like_from_storage: declared dtype {:?} does not match storage dtype {:?}",
4298 dtype,
4299 storage.read().unwrap().dtype(),
4300 );
4301 let id = {
4302 let mut g = self.graph.write().unwrap();
4303 let id = g.push(Node {
4304 op: Op::Const,
4305 inputs: vec![],
4306 shape,
4307 dtype,
4308 });
4309 g.set_storage(id, storage);
4310 id
4311 };
4312 Self {
4313 graph: self.graph.clone(),
4314 id,
4315 }
4316 }
4317
4318 /// Append an `Add` node `self + other` to the shared graph and return
4319 /// a handle to the result. Requires matching shapes and matching
4320 /// graphs.
4321 ///
4322 /// # Panics
4323 ///
4324 /// Panics if any operand belongs to a different [`Graph`] than the one this
4325 /// builder is building into. Operand identity is graph-scoped and checked by
4326 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4327 /// deliberate and replaces the hang a cross-graph handle used to produce.
4328 /// Build every operand from one graph, or use a `Result`-returning entry
4329 /// point where one exists.
4330 pub fn add(&self, other: &NodeHandle) -> NodeHandle {
4331 self.binary_op("add", Op::Add, other, self.shape())
4332 }
4333
4334 /// Append a `Mul` node `self * other`.
4335 ///
4336 /// # Panics
4337 ///
4338 /// Panics if any operand belongs to a different [`Graph`] than the one this
4339 /// builder is building into. Operand identity is graph-scoped and checked by
4340 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4341 /// deliberate and replaces the hang a cross-graph handle used to produce.
4342 /// Build every operand from one graph, or use a `Result`-returning entry
4343 /// point where one exists.
4344 pub fn mul(&self, other: &NodeHandle) -> NodeHandle {
4345 self.binary_op("mul", Op::Mul, other, self.shape())
4346 }
4347
4348 /// Append a `MatMul` node. Both operands must have rank ≥ 2. The
4349 /// last two dims are the matrix dims; leading dims are batch dims.
4350 ///
4351 /// - If both operands have the same rank, their batch dims must
4352 /// match exactly.
4353 /// - If one operand is rank-2 and the other is higher rank, the
4354 /// rank-2 operand is auto-broadcast to match the higher-rank
4355 /// operand's batch prefix. This is the common "linear layer
4356 /// across a batch" pattern (`[batch, seq, d_model] @ [d_model, d_out]`).
4357 /// - Any other rank combination panics; users must reshape first.
4358 ///
4359 /// Shape examples:
4360 /// - `[m, k] @ [k, n]` → `[m, n]`
4361 /// - `[batch, m, k] @ [batch, k, n]` → `[batch, m, n]`
4362 /// - `[batch, seq, k] @ [k, n]` → `[batch, seq, n]` (rhs auto-broadcast)
4363 /// - `[k, n]` @ `[batch, n, m]` → `[batch, k, m]` (lhs auto-broadcast)
4364 ///
4365 /// # Panics
4366 ///
4367 /// Panics if any operand belongs to a different [`Graph`] than the one this
4368 /// builder is building into. Operand identity is graph-scoped and checked by
4369 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4370 /// deliberate and replaces the hang a cross-graph handle used to produce.
4371 /// Build every operand from one graph, or use a `Result`-returning entry
4372 /// point where one exists.
4373 pub fn matmul(&self, other: &NodeHandle) -> NodeHandle {
4374 assert!(
4375 Arc::ptr_eq(&self.graph, &other.graph),
4376 "matmul: tensors must live on the same graph — lhs is on graph #{}, rhs on graph \
4377 #{}; each `from_*` constructor mints a NEW graph, so build `other` on this \
4378 tensor's graph with `from_f32_on(self.graph(), ..)` or `const_*_like`",
4379 self.graph_id(),
4380 other.graph_id(),
4381 );
4382 // Mixed-precision matmul: activations stay in their native
4383 // dtype while weights can live as a lower-precision type on
4384 // device. Currently supported: (F32 × BF16) → F32 for bf16-
4385 // quantized LLM serving. Other heterogeneous combinations
4386 // are rejected.
4387 let dtypes_ok = self.dtype() == other.dtype()
4388 || (self.dtype() == DType::F32 && other.dtype() == DType::BF16);
4389 assert!(
4390 dtypes_ok,
4391 "matmul: unsupported dtype combination: lhs={:?}, rhs={:?}",
4392 self.dtype(),
4393 other.dtype(),
4394 );
4395 let l = self.shape();
4396 let r = other.shape();
4397 let ld = l.dims();
4398 let rd = r.dims();
4399 assert!(
4400 ld.len() >= 2 && rd.len() >= 2,
4401 "matmul: both operands must be rank ≥ 2, got {ld:?} and {rd:?}",
4402 );
4403
4404 // Auto-broadcast the rank-2 operand against the other's batch
4405 // prefix. If ranks already match, this is a no-op.
4406 let (lhs, rhs) = if ld.len() == rd.len() {
4407 (self.clone(), other.clone())
4408 } else if ld.len() == 2 && rd.len() > 2 {
4409 let mut bc_shape: Vec<usize> = rd[..rd.len() - 2].to_vec();
4410 bc_shape.push(ld[0]);
4411 bc_shape.push(ld[1]);
4412 (
4413 self.broadcast_to(Shape::from_dims(&bc_shape)),
4414 other.clone(),
4415 )
4416 } else if rd.len() == 2 && ld.len() > 2 {
4417 let mut bc_shape: Vec<usize> = ld[..ld.len() - 2].to_vec();
4418 bc_shape.push(rd[0]);
4419 bc_shape.push(rd[1]);
4420 (
4421 self.clone(),
4422 other.broadcast_to(Shape::from_dims(&bc_shape)),
4423 )
4424 } else {
4425 panic!(
4426 "matmul: unsupported rank combination {} vs {} — only same-rank or (rank-2 × higher-rank) is supported; reshape first",
4427 ld.len(),
4428 rd.len(),
4429 );
4430 };
4431
4432 // Now both operands have the same rank. Validate batch prefix
4433 // and build the output node.
4434 let lhs_shape = lhs.shape();
4435 let rhs_shape = rhs.shape();
4436 let l = lhs_shape.dims();
4437 let r = rhs_shape.dims();
4438 let rank = l.len();
4439 let batch_rank = rank - 2;
4440 for i in 0..batch_rank {
4441 // GQA-style matmul: A may have more batch heads than B
4442 // (e.g. Q[1,32,1,64] @ K^T[1,4,64,S]). The n_rep factor
4443 // is inferred by the backend at dispatch time; at the
4444 // graph level we just validate divisibility.
4445 let (la, ra) = (l[i], r[i]);
4446 let ok = la == ra || (la > ra && ra > 0 && la % ra == 0);
4447 assert!(
4448 ok,
4449 "matmul: batch dim mismatch at axis {i}: {la} vs {ra} (not equal and not a GQA-divisible pair)",
4450 );
4451 }
4452 let k = l[rank - 1];
4453 let k2 = r[rank - 2];
4454 assert_eq!(k, k2, "matmul: inner dim mismatch (lhs k={k}, rhs k={k2})",);
4455 // Output shape + dtype now flow from primitive_shape (the single source
4456 // of truth); the same-rank operands + validated batch prefix / inner
4457 // dim above guarantee it infers cleanly. (The GQA batch-prefix carry
4458 // uses lhs's batch dims, matching primitive_shape's `l[..rank-2]`.)
4459 let (shape, dtype) = crate::shape::primitive_shape(
4460 &Op::MatMul,
4461 &[lhs_shape.clone(), rhs_shape.clone()],
4462 &[lhs.dtype(), rhs.dtype()],
4463 )
4464 .expect("matmul: operands validated (same-rank, inner dim) before primitive_shape");
4465 let id = self.graph.write().unwrap().push(Node {
4466 op: Op::MatMul,
4467 inputs: vec![lhs.id, rhs.id],
4468 shape,
4469 dtype,
4470 });
4471 Self {
4472 graph: self.graph.clone(),
4473 id,
4474 }
4475 }
4476
4477 /// Data-determined-M matmul: like [`Self::matmul`], but the LHS row
4478 /// count `M` is a **runtime** value `row_count` rather than the static
4479 /// `lhs.shape[-2]`. The LHS and output are **capacity buffers** of
4480 /// `lhs.shape[-2]` rows; only `row_count` rows are computed, the rest
4481 /// left zeroed. This is the sparse-MoE expert-FFN primitive — gather an
4482 /// expert's `count_e` routed tokens into a capacity buffer, then
4483 /// compute exactly `count_e` FFN rows (the FLOP saving). `row_count`
4484 /// resolves at compile if input-determined, else at execute from the
4485 /// producer-bound `SymEnv` (e.g. `Op::NonZeroIndices`'s count). The
4486 /// output shape is the capacity shape `[..., lhs.shape[-2], n]`.
4487 ///
4488 /// # Panics
4489 ///
4490 /// Panics if any operand belongs to a different [`Graph`] than the one this
4491 /// builder is building into. Operand identity is graph-scoped and checked by
4492 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4493 /// deliberate and replaces the hang a cross-graph handle used to produce.
4494 /// Build every operand from one graph, or use a `Result`-returning entry
4495 /// point where one exists.
4496 pub fn matmul_dyn_m(&self, other: &NodeHandle, row_count: DynScalar) -> NodeHandle {
4497 self.assert_same_graph(other, "matmul_dyn_m", "other");
4498 // Only the F32 CPU capacity kernel honors a data-determined row
4499 // count today; other dtypes/backends compute all capacity rows.
4500 // Guard here so a dynamic-M matmul can never be built where it
4501 // would silently over-compute.
4502 assert_eq!(
4503 self.dtype(),
4504 DType::F32,
4505 "matmul_dyn_m: data-determined-M is F32-only today (got lhs {:?})",
4506 self.dtype(),
4507 );
4508 let out = self.matmul(other);
4509 self.graph
4510 .write()
4511 .unwrap()
4512 .set_matmul_row_count(out.id, row_count);
4513 out
4514 }
4515
4516 /// Append an [`Op::Fused`] node carrying
4517 /// [`crate::registry::FusedOpParams::QMatMul`] that multiplies `self` (F32
4518 /// activations, shape `[..., M, K]`) with a Q-type quantized
4519 /// weight matrix of logical shape `[N, K]` stored as a raw byte
4520 /// stream (passed in as a U32 tensor; length = n_bytes / 4).
4521 ///
4522 /// Output shape: `[..., M, N]` F32. The backend dequantizes the
4523 /// weight blocks on the fly inside the matmul kernel, so the
4524 /// quantized blocks stay resident at their compressed size.
4525 ///
4526 /// # Panics
4527 ///
4528 /// Panics if any operand belongs to a different [`Graph`] than the one this
4529 /// builder is building into. Operand identity is graph-scoped and checked by
4530 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4531 /// deliberate and replaces the hang a cross-graph handle used to produce.
4532 /// Build every operand from one graph, or use a `Result`-returning entry
4533 /// point where one exists.
4534 pub fn qmatmul(
4535 &self,
4536 weight_bytes: &NodeHandle,
4537 quant_type: QuantType,
4538 k: usize,
4539 n: usize,
4540 ) -> NodeHandle {
4541 assert!(
4542 Arc::ptr_eq(&self.graph, &weight_bytes.graph),
4543 "qmatmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
4544 );
4545 assert_eq!(
4546 self.dtype(),
4547 DType::F32,
4548 "qmatmul: activations must be F32, got {:?}",
4549 self.dtype(),
4550 );
4551 assert_eq!(
4552 weight_bytes.dtype(),
4553 DType::U32,
4554 "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
4555 weight_bytes.dtype(),
4556 );
4557 let a_dims = self.shape();
4558 let a_dims = a_dims.dims();
4559 assert!(
4560 a_dims.len() >= 2,
4561 "qmatmul: activations must be rank ≥ 2, got {a_dims:?}",
4562 );
4563 assert_eq!(
4564 a_dims[a_dims.len() - 1],
4565 k,
4566 "qmatmul: last dim of activations ({}) must equal k ({k})",
4567 a_dims[a_dims.len() - 1],
4568 );
4569 assert_eq!(
4570 k % quant_type.elements_per_block(),
4571 0,
4572 "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({})",
4573 quant_type.elements_per_block(),
4574 );
4575 // Validate the weight byte count matches [N, K/block_size] blocks.
4576 let expected_bytes =
4577 n * (k / quant_type.elements_per_block()) * quant_type.bytes_per_block();
4578 let expected_u32_elems = expected_bytes / 4;
4579 assert_eq!(
4580 weight_bytes.shape().elem_count(),
4581 expected_u32_elems,
4582 "qmatmul: weight_bytes has {} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
4583 weight_bytes.shape().elem_count(),
4584 );
4585 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
4586 out_dims.push(n);
4587 // Phase 7.6 step 4 (final): emits Op::Fused(QMATMUL, _) per
4588 // the registry split.
4589 let id = self.graph.write().unwrap().push(Node {
4590 op: Op::Fused(
4591 crate::registry::FusedOps::QMATMUL,
4592 crate::registry::FusedOpParams::QMatMul { quant_type, k, n },
4593 ),
4594 inputs: vec![self.id, weight_bytes.id],
4595 shape: Shape::from_dims(&out_dims),
4596 dtype: DType::F32,
4597 });
4598 Self {
4599 graph: self.graph.clone(),
4600 id,
4601 }
4602 }
4603
4604 /// Append an [`Op::Fused`] node carrying
4605 /// [`crate::registry::FusedOpParams::Conv2D`]. `self` must be `[N, Cin, H, W]`
4606 /// (rank 4); `weight` must be `[Cout, Cin/groups, Kh, Kw]` (rank
4607 /// 4) and live on the same graph. `bias` is optional — when
4608 /// present it must be rank 1 with length `Cout`. Returns a rank-4
4609 /// tensor of shape `[N, Cout, Hout, Wout]`.
4610 ///
4611 /// Panics if the input ranks don't match, the channel counts are
4612 /// inconsistent with `groups`, or the output spatial dims would
4613 /// be non-positive.
4614 ///
4615 /// # Panics
4616 ///
4617 /// Panics if any operand belongs to a different [`Graph`] than the one this
4618 /// builder is building into. Operand identity is graph-scoped and checked by
4619 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4620 /// deliberate and replaces the hang a cross-graph handle used to produce.
4621 /// Build every operand from one graph, or use a `Result`-returning entry
4622 /// point where one exists.
4623 pub fn conv2d(
4624 &self,
4625 weight: &NodeHandle,
4626 bias: Option<&NodeHandle>,
4627 stride: (usize, usize),
4628 padding: (usize, usize),
4629 groups: usize,
4630 ) -> NodeHandle {
4631 assert!(
4632 Arc::ptr_eq(&self.graph, &weight.graph),
4633 "conv2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4634 );
4635 if let Some(b) = bias {
4636 assert!(
4637 Arc::ptr_eq(&self.graph, &b.graph),
4638 "conv2d: bias must live on the same graph; use `const_*_like` to build on an existing graph",
4639 );
4640 }
4641 assert!(groups >= 1, "conv2d: groups must be ≥ 1, got {groups}");
4642 let x_dims = self.shape();
4643 let x_dims = x_dims.dims();
4644 let w_dims = weight.shape();
4645 let w_dims = w_dims.dims();
4646 assert_eq!(
4647 x_dims.len(),
4648 4,
4649 "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4650 );
4651 assert_eq!(
4652 w_dims.len(),
4653 4,
4654 "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
4655 );
4656 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4657 let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4658 assert_eq!(
4659 cin,
4660 cin_per_g * groups,
4661 "conv2d: x has {cin} in-channels but weight expects {} ({}·{groups})",
4662 cin_per_g * groups,
4663 cin_per_g,
4664 );
4665 assert_eq!(
4666 cout % groups,
4667 0,
4668 "conv2d: Cout={cout} must be divisible by groups={groups}",
4669 );
4670 if let Some(b) = bias {
4671 let b_dims = b.shape();
4672 let b_dims = b_dims.dims();
4673 assert_eq!(
4674 b_dims,
4675 &[cout],
4676 "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
4677 );
4678 }
4679 // Hout = (H + 2·pad.0 − Kh) / stride.0 + 1
4680 let (stride_h, stride_w) = stride;
4681 let (pad_h, pad_w) = padding;
4682 assert!(stride_h >= 1 && stride_w >= 1, "conv2d: stride must be ≥ 1");
4683 let h_padded = h_in + 2 * pad_h;
4684 let w_padded = w_in + 2 * pad_w;
4685 assert!(
4686 h_padded >= kh && w_padded >= kw,
4687 "conv2d: padded input ({h_padded}×{w_padded}) smaller than kernel ({kh}×{kw})",
4688 );
4689 let h_out = (h_padded - kh) / stride_h + 1;
4690 let w_out = (w_padded - kw) / stride_w + 1;
4691 let dtype = self.dtype();
4692 let mut inputs = vec![self.id, weight.id];
4693 if let Some(b) = bias {
4694 inputs.push(b.id);
4695 }
4696 // Phase 7.6 step 4 (continued): emit
4697 // `Op::Fused(FusedOps::CONV2D, FusedOpParams::Conv2D { … })`
4698 // through the registry-extended arm. The legacy
4699 // `Op::Conv2D { … }` variant remains in the enum during
4700 // migration (Conv2D's backward still constructs inner
4701 // `Op::Fused(CONV2D, _)` nodes; the legacy variant is reached
4702 // only by direct tests until step 5 drops it).
4703 let id = self.graph.write().unwrap().push(Node {
4704 op: Op::Fused(
4705 crate::registry::FusedOps::CONV2D,
4706 crate::registry::FusedOpParams::Conv2D {
4707 stride,
4708 padding,
4709 groups,
4710 },
4711 ),
4712 inputs,
4713 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4714 dtype,
4715 });
4716 Self {
4717 graph: self.graph.clone(),
4718 id,
4719 }
4720 }
4721
4722 /// Append an [`Op::Fused`] node carrying
4723 /// [`crate::registry::FusedOpParams::PagedAttn`]. `self` is the Q tensor of shape
4724 /// `[B, Hq, Sq, D]`; `k_cache` and `v_cache` are the paged caches
4725 /// shaped `[num_blocks, block_size, Hkv, D]`; `block_table` is
4726 /// `[B, max_num_blocks_per_seq]` (u32) mapping logical → physical
4727 /// blocks; `context_lens` is `[B]` (u32) of per-sequence lengths;
4728 /// `alibi_slopes` is the optional `[Hq]` per-head bias.
4729 ///
4730 /// Returns a tensor with `q`'s shape `[B, Hq, Sq, D]`.
4731 ///
4732 /// # Panics
4733 ///
4734 /// Panics if any operand belongs to a different [`Graph`] than the one this
4735 /// builder is building into. Operand identity is graph-scoped and checked by
4736 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4737 /// deliberate and replaces the hang a cross-graph handle used to produce.
4738 /// Build every operand from one graph, or use a `Result`-returning entry
4739 /// point where one exists.
4740 pub fn paged_attn(
4741 &self,
4742 k_cache: &NodeHandle,
4743 v_cache: &NodeHandle,
4744 block_table: &NodeHandle,
4745 context_lens: &NodeHandle,
4746 alibi_slopes: Option<&NodeHandle>,
4747 softmax_scale: f32,
4748 block_size: usize,
4749 softcap: Option<f32>,
4750 ) -> NodeHandle {
4751 let g = &self.graph;
4752 assert!(
4753 Arc::ptr_eq(g, &k_cache.graph),
4754 "paged_attn: q + k_cache must share graph"
4755 );
4756 assert!(
4757 Arc::ptr_eq(g, &v_cache.graph),
4758 "paged_attn: q + v_cache must share graph"
4759 );
4760 assert!(
4761 Arc::ptr_eq(g, &block_table.graph),
4762 "paged_attn: q + block_table must share graph"
4763 );
4764 assert!(
4765 Arc::ptr_eq(g, &context_lens.graph),
4766 "paged_attn: q + context_lens must share graph"
4767 );
4768 if let Some(a) = alibi_slopes {
4769 assert!(
4770 Arc::ptr_eq(g, &a.graph),
4771 "paged_attn: alibi_slopes must share graph"
4772 );
4773 }
4774 assert!(block_size >= 1, "paged_attn: block_size must be ≥ 1");
4775
4776 let q_dims = self.shape();
4777 let q_dims = q_dims.dims();
4778 let kc_dims = k_cache.shape();
4779 let kc_dims = kc_dims.dims();
4780 let vc_dims = v_cache.shape();
4781 let vc_dims = vc_dims.dims();
4782 let bt_dims = block_table.shape();
4783 let bt_dims = bt_dims.dims();
4784 let cl_dims = context_lens.shape();
4785 let cl_dims = cl_dims.dims();
4786 assert_eq!(
4787 q_dims.len(),
4788 4,
4789 "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
4790 );
4791 assert_eq!(
4792 kc_dims.len(),
4793 4,
4794 "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}"
4795 );
4796 assert_eq!(
4797 vc_dims.len(),
4798 4,
4799 "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}"
4800 );
4801 assert_eq!(
4802 bt_dims.len(),
4803 2,
4804 "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}"
4805 );
4806 assert_eq!(
4807 cl_dims.len(),
4808 1,
4809 "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}"
4810 );
4811 let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
4812 assert_eq!(
4813 kc_dims[1], block_size,
4814 "paged_attn: k_cache block dim {} != block_size {block_size}",
4815 kc_dims[1]
4816 );
4817 assert_eq!(
4818 vc_dims[1], block_size,
4819 "paged_attn: v_cache block dim {} != block_size {block_size}",
4820 vc_dims[1]
4821 );
4822 let hkv = kc_dims[2];
4823 assert_eq!(
4824 vc_dims[2], hkv,
4825 "paged_attn: Hkv mismatch k_cache vs v_cache"
4826 );
4827 assert_eq!(kc_dims[3], d, "paged_attn: D mismatch q vs k_cache");
4828 assert_eq!(vc_dims[3], d, "paged_attn: D mismatch q vs v_cache");
4829 assert_eq!(
4830 hq % hkv,
4831 0,
4832 "paged_attn: Hq={hq} must be a multiple of Hkv={hkv}"
4833 );
4834 assert_eq!(
4835 bt_dims[0], b,
4836 "paged_attn: block_table batch dim {} != B={b}",
4837 bt_dims[0]
4838 );
4839 assert_eq!(
4840 cl_dims[0], b,
4841 "paged_attn: context_lens len {} != B={b}",
4842 cl_dims[0]
4843 );
4844 assert_eq!(
4845 block_table.dtype(),
4846 crate::DType::U32,
4847 "paged_attn: block_table must be U32"
4848 );
4849 assert_eq!(
4850 context_lens.dtype(),
4851 crate::DType::U32,
4852 "paged_attn: context_lens must be U32"
4853 );
4854 if let Some(a) = alibi_slopes {
4855 let ad = a.shape();
4856 let ad = ad.dims();
4857 assert_eq!(
4858 ad,
4859 &[hq],
4860 "paged_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
4861 );
4862 }
4863
4864 let dtype = self.dtype();
4865 let mut inputs = vec![
4866 self.id,
4867 k_cache.id,
4868 v_cache.id,
4869 block_table.id,
4870 context_lens.id,
4871 ];
4872 if let Some(a) = alibi_slopes {
4873 inputs.push(a.id);
4874 }
4875 // Phase 7.6 step 4 (final): emits Op::Fused(PAGED_ATTN, _).
4876 let id = self.graph.write().unwrap().push(Node {
4877 op: Op::Fused(
4878 crate::registry::FusedOps::PAGED_ATTN,
4879 crate::registry::FusedOpParams::PagedAttn {
4880 softmax_scale,
4881 block_size,
4882 softcap,
4883 },
4884 ),
4885 inputs,
4886 shape: Shape::from_dims(q_dims),
4887 dtype,
4888 });
4889 Self {
4890 graph: self.graph.clone(),
4891 id,
4892 }
4893 }
4894
4895 /// Append an [`Op::Fused`] node carrying
4896 /// [`crate::registry::FusedOpParams::ConvTranspose2D`]. `self` must be
4897 /// `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
4898 /// (note transposed channel order vs `conv2d`). Returns a rank-4
4899 /// tensor `[N, Cout, Hout, Wout]`.
4900 ///
4901 /// Panics if ranks don't match, channel counts are inconsistent
4902 /// with `groups`, or output spatial dims would be non-positive.
4903 ///
4904 /// # Panics
4905 ///
4906 /// Panics if any operand belongs to a different [`Graph`] than the one this
4907 /// builder is building into. Operand identity is graph-scoped and checked by
4908 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
4909 /// deliberate and replaces the hang a cross-graph handle used to produce.
4910 /// Build every operand from one graph, or use a `Result`-returning entry
4911 /// point where one exists.
4912 pub fn conv_transpose2d(
4913 &self,
4914 weight: &NodeHandle,
4915 stride: (usize, usize),
4916 padding: (usize, usize),
4917 output_padding: (usize, usize),
4918 dilation: (usize, usize),
4919 groups: usize,
4920 ) -> NodeHandle {
4921 assert!(
4922 Arc::ptr_eq(&self.graph, &weight.graph),
4923 "conv_transpose2d: x and weight must live on the same graph; use `const_*_like` to build on an existing graph",
4924 );
4925 assert!(
4926 groups >= 1,
4927 "conv_transpose2d: groups must be ≥ 1, got {groups}"
4928 );
4929 let x_dims = self.shape();
4930 let x_dims = x_dims.dims();
4931 let w_dims = weight.shape();
4932 let w_dims = w_dims.dims();
4933 assert_eq!(
4934 x_dims.len(),
4935 4,
4936 "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
4937 );
4938 assert_eq!(
4939 w_dims.len(),
4940 4,
4941 "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
4942 );
4943 let (n, cin, h_in, w_in) = (x_dims[0], x_dims[1], x_dims[2], x_dims[3]);
4944 let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
4945 assert_eq!(
4946 cin, cin_w,
4947 "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
4948 );
4949 assert_eq!(
4950 cin % groups,
4951 0,
4952 "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
4953 );
4954 let cout = cout_per_g * groups;
4955 let (stride_h, stride_w) = stride;
4956 let (pad_h, pad_w) = padding;
4957 let (out_pad_h, out_pad_w) = output_padding;
4958 let (dil_h, dil_w) = dilation;
4959 assert!(
4960 stride_h >= 1 && stride_w >= 1,
4961 "conv_transpose2d: stride must be ≥ 1"
4962 );
4963 assert!(
4964 dil_h >= 1 && dil_w >= 1,
4965 "conv_transpose2d: dilation must be ≥ 1"
4966 );
4967 // Hout = (Hin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1
4968 let h_out = (h_in.saturating_sub(1)) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
4969 let w_out = (w_in.saturating_sub(1)) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
4970 assert!(
4971 h_out > 2 * pad_h && w_out > 2 * pad_w,
4972 "conv_transpose2d: padding ({pad_h}×{pad_w}) is larger than the produced output dims",
4973 );
4974 let h_out = h_out - 2 * pad_h;
4975 let w_out = w_out - 2 * pad_w;
4976 let dtype = self.dtype();
4977 // Phase 7.6 step 4 (final): emits Op::Fused(CONV_TRANSPOSE2D, _).
4978 let id = self.graph.write().unwrap().push(Node {
4979 op: Op::Fused(
4980 crate::registry::FusedOps::CONV_TRANSPOSE2D,
4981 crate::registry::FusedOpParams::ConvTranspose2D {
4982 stride,
4983 padding,
4984 output_padding,
4985 dilation,
4986 groups,
4987 },
4988 ),
4989 inputs: vec![self.id, weight.id],
4990 shape: Shape::from_dims(&[n, cout, h_out, w_out]),
4991 dtype,
4992 });
4993 Self {
4994 graph: self.graph.clone(),
4995 id,
4996 }
4997 }
4998
4999 /// Append a transposed 1D convolution by lifting `self` and
5000 /// `weight` into the rank-4 path and dispatching through
5001 /// [`Self::conv_transpose2d`]. `self` is `[N, Cin, Lin]`;
5002 /// `weight` is `[Cin, Cout/groups, K]` (transposed channel
5003 /// order, matches PyTorch). Returns `[N, Cout, Lout]` where
5004 /// `Lout = (Lin − 1)·stride − 2·pad + dil·(K − 1) + out_pad + 1`.
5005 ///
5006 /// Used by audio codec models (DAC / EnCodec / SNAC / Mimi /
5007 /// Parler-TTS / MetaVoice / CSM) where the decoder upsamples
5008 /// quantized latents back to waveform with strided transposed
5009 /// convs.
5010 ///
5011 /// # Panics
5012 ///
5013 /// Panics if any operand belongs to a different [`Graph`] than the one this
5014 /// builder is building into. Operand identity is graph-scoped and checked by
5015 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5016 /// deliberate and replaces the hang a cross-graph handle used to produce.
5017 /// Build every operand from one graph, or use a `Result`-returning entry
5018 /// point where one exists.
5019 pub fn conv_transpose1d(
5020 &self,
5021 weight: &NodeHandle,
5022 stride: usize,
5023 padding: usize,
5024 output_padding: usize,
5025 dilation: usize,
5026 groups: usize,
5027 ) -> NodeHandle {
5028 self.assert_same_graph(weight, "conv_transpose1d", "weight");
5029 let x_dims = self.shape();
5030 let x_dims = x_dims.dims();
5031 let w_dims = weight.shape();
5032 let w_dims = w_dims.dims();
5033 assert_eq!(
5034 x_dims.len(),
5035 3,
5036 "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
5037 );
5038 assert_eq!(
5039 w_dims.len(),
5040 3,
5041 "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
5042 );
5043 let (n, cin, l_in) = (x_dims[0], x_dims[1], x_dims[2]);
5044 let (cin_w, cout_per_g, k) = (w_dims[0], w_dims[1], w_dims[2]);
5045 let x4 = self.reshape(Shape::from_dims(&[n, cin, 1, l_in]));
5046 let w4 = weight.reshape(Shape::from_dims(&[cin_w, cout_per_g, 1, k]));
5047 let y4 = x4.conv_transpose2d(
5048 &w4,
5049 (1, stride),
5050 (0, padding),
5051 (0, output_padding),
5052 (1, dilation),
5053 groups,
5054 );
5055 let y_dims = y4.shape();
5056 let y_dims = y_dims.dims();
5057 let (n_o, cout, _h_one, l_out) = (y_dims[0], y_dims[1], y_dims[2], y_dims[3]);
5058 y4.reshape(Shape::from_dims(&[n_o, cout, l_out]))
5059 }
5060
5061 /// Append an [`Op::Fused`] node carrying
5062 /// [`crate::registry::FusedOpParams::FlashAttn`]. `self` is `q` of shape
5063 /// `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]` with
5064 /// `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional) is
5065 /// `[Hq]`. Returns a tensor with `q`'s shape.
5066 /// Build the `flash_attn` node.
5067 ///
5068 /// # Panics
5069 ///
5070 /// Panics if any operand belongs to a different [`Graph`] than the one this
5071 /// builder is building into. Operand identity is graph-scoped and checked by
5072 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5073 /// deliberate and replaces the hang a cross-graph handle used to produce.
5074 /// Build every operand from one graph, or use a `Result`-returning entry
5075 /// point where one exists.
5076 pub fn flash_attn(
5077 &self,
5078 k: &NodeHandle,
5079 v: &NodeHandle,
5080 alibi_slopes: Option<&NodeHandle>,
5081 softmax_scale: f32,
5082 causal: bool,
5083 window_size_left: Option<usize>,
5084 window_size_right: Option<usize>,
5085 softcap: Option<f32>,
5086 ) -> NodeHandle {
5087 assert!(
5088 Arc::ptr_eq(&self.graph, &k.graph),
5089 "flash_attn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5090 );
5091 assert!(
5092 Arc::ptr_eq(&self.graph, &v.graph),
5093 "flash_attn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5094 );
5095 if let Some(a) = alibi_slopes {
5096 assert!(
5097 Arc::ptr_eq(&self.graph, &a.graph),
5098 "flash_attn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5099 );
5100 }
5101 let q_dims = self.shape();
5102 let q_dims = q_dims.dims();
5103 let k_dims = k.shape();
5104 let k_dims = k_dims.dims();
5105 let v_dims = v.shape();
5106 let v_dims = v_dims.dims();
5107 assert_eq!(
5108 q_dims.len(),
5109 4,
5110 "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5111 );
5112 assert_eq!(
5113 k_dims.len(),
5114 4,
5115 "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}"
5116 );
5117 assert_eq!(
5118 v_dims.len(),
5119 4,
5120 "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}"
5121 );
5122 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5123 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5124 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5125 assert_eq!(b, bk, "flash_attn: B mismatch q vs k ({b} vs {bk})");
5126 assert_eq!(b, bv, "flash_attn: B mismatch q vs v");
5127 assert_eq!(hkv, hkv_v, "flash_attn: Hkv mismatch k vs v");
5128 assert_eq!(sk, sk_v, "flash_attn: Sk mismatch k vs v");
5129 assert_eq!(d, dk, "flash_attn: head_dim mismatch q vs k");
5130 assert_eq!(d, dv, "flash_attn: head_dim mismatch q vs v");
5131 assert_eq!(
5132 hq % hkv,
5133 0,
5134 "flash_attn: Hq={hq} must be a multiple of Hkv={hkv}"
5135 );
5136 if let Some(a) = alibi_slopes {
5137 let ad = a.shape();
5138 let ad = ad.dims();
5139 assert_eq!(
5140 ad,
5141 &[hq],
5142 "flash_attn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5143 );
5144 }
5145 let dtype = self.dtype();
5146 let mut inputs = vec![self.id, k.id, v.id];
5147 if let Some(a) = alibi_slopes {
5148 inputs.push(a.id);
5149 }
5150 // Phase 7.6 step 4 (final): emits Op::Fused(FLASH_ATTN, _).
5151 let id = self.graph.write().unwrap().push(Node {
5152 op: Op::Fused(
5153 crate::registry::FusedOps::FLASH_ATTN,
5154 crate::registry::FusedOpParams::FlashAttn {
5155 softmax_scale,
5156 causal,
5157 window_size_left,
5158 window_size_right,
5159 softcap,
5160 k_len: None,
5161 },
5162 ),
5163 inputs,
5164 shape: Shape::from_dims(&[b, hq, sq, d]),
5165 dtype,
5166 });
5167 Self {
5168 graph: self.graph.clone(),
5169 id,
5170 }
5171 }
5172
5173 /// Append an [`Op::Fused`] node carrying
5174 /// [`crate::registry::FusedOpParams::FlashAttn`] over a fixed-**capacity** K/V whose
5175 /// attended length is a **runtime** value (`k_len`) resolved through
5176 /// the per-pass [`fuel_ir::SymEnv`] at realize, decoupled
5177 /// from K's allocated shape.
5178 ///
5179 /// `self` is `q` of shape `[B, Hq, Sq, D]`; `k`/`v` are the capacity
5180 /// buffers `[B, Hkv, max_seq, D]` (GQA: `Hq % Hkv == 0`). Only the
5181 /// first `k_len.resolve(env)` rows along the K/V length axis are
5182 /// attended; the causal mask (when `causal`) is bottom-right-aligned
5183 /// at offset `k_len - Sq` — the standard FlashAttention-2 convention,
5184 /// equal to `cached_len` in autoregressive decode. Returns a tensor
5185 /// with `q`'s shape.
5186 ///
5187 /// This is the flash counterpart of [`Self::write_slice_dyn`]: the
5188 /// decode KV-cache write appends at the runtime offset and flash
5189 /// attends the runtime prefix, so the graph structure stays
5190 /// identical across tokens (Phase D symbolic extents).
5191 ///
5192 /// # Panics
5193 ///
5194 /// Panics if any operand belongs to a different [`Graph`] than the one this
5195 /// builder is building into. Operand identity is graph-scoped and checked by
5196 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5197 /// deliberate and replaces the hang a cross-graph handle used to produce.
5198 /// Build every operand from one graph, or use a `Result`-returning entry
5199 /// point where one exists.
5200 pub fn flash_attn_dyn(
5201 &self,
5202 k: &NodeHandle,
5203 v: &NodeHandle,
5204 alibi_slopes: Option<&NodeHandle>,
5205 softmax_scale: f32,
5206 causal: bool,
5207 window_size_left: Option<usize>,
5208 window_size_right: Option<usize>,
5209 softcap: Option<f32>,
5210 k_len: fuel_ir::DynScalar,
5211 ) -> NodeHandle {
5212 assert!(
5213 Arc::ptr_eq(&self.graph, &k.graph),
5214 "flash_attn_dyn: q + k must live on the same graph; use `const_*_like` to build on an existing graph"
5215 );
5216 assert!(
5217 Arc::ptr_eq(&self.graph, &v.graph),
5218 "flash_attn_dyn: q + v must live on the same graph; use `const_*_like` to build on an existing graph"
5219 );
5220 if let Some(a) = alibi_slopes {
5221 assert!(
5222 Arc::ptr_eq(&self.graph, &a.graph),
5223 "flash_attn_dyn: alibi_slopes must live on the same graph; use `const_*_like` to build on an existing graph"
5224 );
5225 }
5226 let q_dims = self.shape();
5227 let q_dims = q_dims.dims();
5228 let k_dims = k.shape();
5229 let k_dims = k_dims.dims();
5230 let v_dims = v.shape();
5231 let v_dims = v_dims.dims();
5232 assert_eq!(
5233 q_dims.len(),
5234 4,
5235 "flash_attn_dyn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}"
5236 );
5237 assert_eq!(
5238 k_dims.len(),
5239 4,
5240 "flash_attn_dyn: k must be rank 4 [B, Hkv, max_seq, D], got {k_dims:?}"
5241 );
5242 assert_eq!(
5243 v_dims.len(),
5244 4,
5245 "flash_attn_dyn: v must be rank 4 [B, Hkv, max_seq, D], got {v_dims:?}"
5246 );
5247 let (b, hq, sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5248 let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5249 let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5250 assert_eq!(b, bk, "flash_attn_dyn: B mismatch q vs k ({b} vs {bk})");
5251 assert_eq!(b, bv, "flash_attn_dyn: B mismatch q vs v");
5252 assert_eq!(hkv, hkv_v, "flash_attn_dyn: Hkv mismatch k vs v");
5253 assert_eq!(
5254 sk, sk_v,
5255 "flash_attn_dyn: capacity (max_seq) mismatch k vs v ({sk} vs {sk_v})"
5256 );
5257 assert_eq!(d, dk, "flash_attn_dyn: head_dim mismatch q vs k");
5258 assert_eq!(d, dv, "flash_attn_dyn: head_dim mismatch q vs v");
5259 assert_eq!(
5260 hq % hkv,
5261 0,
5262 "flash_attn_dyn: Hq={hq} must be a multiple of Hkv={hkv}"
5263 );
5264 // A build-time constant k_len must fit the capacity and cover Sq.
5265 if let fuel_ir::DynScalar::Concrete(kl) = k_len {
5266 assert!(
5267 kl <= sk,
5268 "flash_attn_dyn: k_len ({kl}) exceeds K capacity ({sk})"
5269 );
5270 assert!(
5271 kl >= sq,
5272 "flash_attn_dyn: k_len ({kl}) must be >= Sq ({sq}) for a valid causal prefix"
5273 );
5274 }
5275 if let Some(a) = alibi_slopes {
5276 let ad = a.shape();
5277 let ad = ad.dims();
5278 assert_eq!(
5279 ad,
5280 &[hq],
5281 "flash_attn_dyn: alibi_slopes must be [Hq={hq}], got {ad:?}"
5282 );
5283 }
5284 let dtype = self.dtype();
5285 let mut inputs = vec![self.id, k.id, v.id];
5286 if let Some(a) = alibi_slopes {
5287 inputs.push(a.id);
5288 }
5289 let id = self.graph.write().unwrap().push(Node {
5290 op: Op::Fused(
5291 crate::registry::FusedOps::FLASH_ATTN,
5292 crate::registry::FusedOpParams::FlashAttn {
5293 softmax_scale,
5294 causal,
5295 window_size_left,
5296 window_size_right,
5297 softcap,
5298 k_len: Some(k_len),
5299 },
5300 ),
5301 inputs,
5302 shape: Shape::from_dims(&[b, hq, sq, d]),
5303 dtype,
5304 });
5305 Self {
5306 graph: self.graph.clone(),
5307 id,
5308 }
5309 }
5310
5311 /// Append a `Relu` node `max(0, self)`.
5312 pub fn relu(&self) -> NodeHandle {
5313 self.unary_op(Op::Relu)
5314 }
5315
5316 /// Append a `Sqr` node `self * self`.
5317 pub fn sqr(&self) -> NodeHandle {
5318 self.unary_op(Op::Sqr)
5319 }
5320
5321 /// Append an `Exp` node `e^self`.
5322 pub fn exp(&self) -> NodeHandle {
5323 self.unary_op(Op::Exp)
5324 }
5325
5326 /// Append a `Permute` node rearranging the axes according to `axes`.
5327 /// `out.shape[i] = self.shape[axes[i]]`. The axes vector must be a
5328 /// permutation of `0..rank`. For a rank-3 input with `axes = [2, 0, 1]`,
5329 /// the shape transform is `[a, b, c] → [c, a, b]`.
5330 pub fn permute(&self, axes: &[usize]) -> NodeHandle {
5331 let in_shape = self.shape();
5332 let in_dims = in_shape.dims();
5333 let rank = in_dims.len();
5334 assert_eq!(
5335 axes.len(),
5336 rank,
5337 "permute: axes length {} must equal tensor rank {}",
5338 axes.len(),
5339 rank,
5340 );
5341 // Validate that axes is a permutation of 0..rank.
5342 let mut seen = vec![false; rank];
5343 for &ax in axes {
5344 assert!(
5345 ax < rank,
5346 "permute: axis {ax} out of bounds for rank {rank}"
5347 );
5348 assert!(!seen[ax], "permute: duplicate axis {ax} in axes");
5349 seen[ax] = true;
5350 }
5351 let out_dims: Vec<usize> = axes.iter().map(|&ax| in_dims[ax]).collect();
5352 let dtype = self.dtype();
5353 let id = self.graph.write().unwrap().push(Node {
5354 op: Op::Permute(axes.to_vec()),
5355 inputs: vec![self.id],
5356 shape: Shape::from_dims(&out_dims),
5357 dtype,
5358 });
5359 Self {
5360 graph: self.graph.clone(),
5361 id,
5362 }
5363 }
5364
5365 /// Result-returning sibling of [`Self::permute`]. Surfaces bad
5366 /// axes (wrong length, out-of-bounds entry, or duplicate) as a
5367 /// typed error rather than panicking.
5368 pub fn try_permute(&self, axes: &[usize]) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5369 let in_shape = self.shape();
5370 let rank = in_shape.dims().len();
5371 if axes.len() != rank {
5372 return Err(fuel_ir::Error::Msg(format!(
5373 "permute: axes length {} must equal tensor rank {}",
5374 axes.len(),
5375 rank,
5376 ))
5377 .bt());
5378 }
5379 let mut seen = vec![false; rank];
5380 for &ax in axes {
5381 if ax >= rank {
5382 return Err(fuel_ir::Error::Msg(format!(
5383 "permute: axis {ax} out of bounds for rank {rank}",
5384 ))
5385 .bt());
5386 }
5387 if seen[ax] {
5388 return Err(
5389 fuel_ir::Error::Msg(format!("permute: duplicate axis {ax} in axes",)).bt(),
5390 );
5391 }
5392 seen[ax] = true;
5393 }
5394 let op = Op::Permute(axes.to_vec());
5395 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5396 let id = self.graph.write().unwrap().push(Node {
5397 op,
5398 inputs: vec![self.id],
5399 shape,
5400 dtype,
5401 });
5402 Ok(Self {
5403 graph: self.graph.clone(),
5404 id,
5405 })
5406 }
5407
5408 /// Append a `Transpose` node that swaps the last two dimensions of a
5409 /// tensor of rank ≥ 2. Leading dims are unchanged. For a rank-2
5410 /// tensor this is the ordinary matrix transpose; for higher ranks,
5411 /// every batch slice is transposed independently.
5412 pub fn transpose(&self) -> NodeHandle {
5413 let in_shape = self.shape();
5414 assert!(
5415 in_shape.dims().len() >= 2,
5416 "transpose: input must be rank ≥ 2, got shape {:?}",
5417 in_shape.dims(),
5418 );
5419 let op = Op::Transpose;
5420 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
5421 .expect("transpose: rank validated above");
5422 let id = self.graph.write().unwrap().push(Node {
5423 op,
5424 inputs: vec![self.id],
5425 shape,
5426 dtype,
5427 });
5428 Self {
5429 graph: self.graph.clone(),
5430 id,
5431 }
5432 }
5433
5434 /// Result-returning sibling of [`Self::transpose`]. Surfaces
5435 /// rank < 2 as a typed error rather than panicking.
5436 pub fn try_transpose(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5437 let in_shape = self.shape();
5438 if in_shape.dims().len() < 2 {
5439 return Err(fuel_ir::Error::Msg(format!(
5440 "transpose: input must be rank ≥ 2, got shape {:?}",
5441 in_shape.dims(),
5442 ))
5443 .bt());
5444 }
5445 let op = Op::Transpose;
5446 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5447 let id = self.graph.write().unwrap().push(Node {
5448 op,
5449 inputs: vec![self.id],
5450 shape,
5451 dtype,
5452 });
5453 Ok(Self {
5454 graph: self.graph.clone(),
5455 id,
5456 })
5457 }
5458
5459 // --- additional element-wise binary ops ---
5460
5461 /// Append a `Sub` node `self - other`. Requires matching shapes and dtypes.
5462 ///
5463 /// # Panics
5464 ///
5465 /// Panics if any operand belongs to a different [`Graph`] than the one this
5466 /// builder is building into. Operand identity is graph-scoped and checked by
5467 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5468 /// deliberate and replaces the hang a cross-graph handle used to produce.
5469 /// Build every operand from one graph, or use a `Result`-returning entry
5470 /// point where one exists.
5471 pub fn sub(&self, other: &NodeHandle) -> NodeHandle {
5472 self.binary_op("sub", Op::Sub, other, self.shape())
5473 }
5474
5475 /// Append a `Div` node `self / other`. Requires matching shapes and dtypes.
5476 ///
5477 /// # Panics
5478 ///
5479 /// Panics if any operand belongs to a different [`Graph`] than the one this
5480 /// builder is building into. Operand identity is graph-scoped and checked by
5481 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
5482 /// deliberate and replaces the hang a cross-graph handle used to produce.
5483 /// Build every operand from one graph, or use a `Result`-returning entry
5484 /// point where one exists.
5485 pub fn div(&self, other: &NodeHandle) -> NodeHandle {
5486 self.binary_op("div", Op::Div, other, self.shape())
5487 }
5488
5489 // --- additional element-wise unary ops ---
5490
5491 /// Append a `Neg` node `-self`.
5492 pub fn neg(&self) -> NodeHandle {
5493 self.unary_op(Op::Neg)
5494 }
5495
5496 /// Append a `Sqrt` node `sqrt(self)`.
5497 pub fn sqrt(&self) -> NodeHandle {
5498 self.unary_op(Op::Sqrt)
5499 }
5500
5501 /// Append a `Log` node `ln(self)`.
5502 pub fn log(&self) -> NodeHandle {
5503 self.unary_op(Op::Log)
5504 }
5505
5506 /// Append a `Sin` node.
5507 pub fn sin(&self) -> NodeHandle {
5508 self.unary_op(Op::Sin)
5509 }
5510
5511 /// Append a `Cos` node.
5512 pub fn cos(&self) -> NodeHandle {
5513 self.unary_op(Op::Cos)
5514 }
5515
5516 /// Append a `Tanh` node.
5517 pub fn tanh(&self) -> NodeHandle {
5518 self.unary_op(Op::Tanh)
5519 }
5520
5521 /// Append a `Sigmoid` node.
5522 pub fn sigmoid(&self) -> NodeHandle {
5523 self.unary_op(Op::Sigmoid)
5524 }
5525
5526 /// Append a `Silu` node (SiLU/Swish activation: `x · sigmoid(x)`).
5527 pub fn silu(&self) -> NodeHandle {
5528 self.unary_op(Op::Silu)
5529 }
5530
5531 /// Append a `GeluTanh` node (tanh-approximation GELU).
5532 pub fn gelu_tanh(&self) -> NodeHandle {
5533 self.unary_op(Op::GeluTanh)
5534 }
5535
5536 /// Append a `Step` node (Heaviside step: `1` where `x > 0`, else `0`).
5537 pub fn step(&self) -> NodeHandle {
5538 self.unary_op(Op::Step)
5539 }
5540
5541 /// Append a `Recip` node (`1 / self`).
5542 pub fn recip(&self) -> NodeHandle {
5543 self.unary_op(Op::Recip)
5544 }
5545
5546 /// Append an `Abs` node (`|self|`).
5547 pub fn abs(&self) -> NodeHandle {
5548 self.unary_op(Op::Abs)
5549 }
5550
5551 // ---- In-place unary builders (Phase 2 of the in-place ops
5552 // infrastructure) ----
5553 //
5554 // Each emits an `Op::*Inplace` node whose input is `self`. The
5555 // returned `NodeHandle` shares the underlying graph and is the new
5556 // root; subsequent ops should use the returned handle to make the
5557 // mutation-after-read ordering observable to `derive_ordering`.
5558 //
5559 // Phase 4 (the mutation-safety pass) is what makes these safe to
5560 // call on tape-tracked tensors. Until Phase 4 lands, calling these
5561 // on a tensor that's been saved for backward will panic at
5562 // `NodeHandle::backward` time (clear error, no silent gradient
5563 // corruption).
5564
5565 /// Append a `ReluInplace` node — mutates `self`'s storage with
5566 /// `max(0, self)`. See `NodeHandle::relu` for the functional variant.
5567 pub fn relu_inplace(&self) -> NodeHandle {
5568 self.unary_op(Op::ReluInplace)
5569 }
5570
5571 /// Append a `SiluInplace` node — mutates `self`'s storage with
5572 /// `self * sigmoid(self)`. See `NodeHandle::silu` for the functional
5573 /// variant.
5574 pub fn silu_inplace(&self) -> NodeHandle {
5575 self.unary_op(Op::SiluInplace)
5576 }
5577
5578 /// Append a `GeluTanhInplace` node — mutates `self`'s storage with
5579 /// the tanh-approximation GELU. See `NodeHandle::gelu_tanh` for the
5580 /// functional variant.
5581 pub fn gelu_tanh_inplace(&self) -> NodeHandle {
5582 self.unary_op(Op::GeluTanhInplace)
5583 }
5584
5585 /// Append a `TanhInplace` node — mutates `self`'s storage with
5586 /// `tanh(self)`. See `NodeHandle::tanh` for the functional variant.
5587 pub fn tanh_inplace(&self) -> NodeHandle {
5588 self.unary_op(Op::TanhInplace)
5589 }
5590
5591 /// Append a `SigmoidInplace` node — mutates `self`'s storage
5592 /// with `sigmoid(self)`. See `NodeHandle::sigmoid` for the functional
5593 /// variant.
5594 pub fn sigmoid_inplace(&self) -> NodeHandle {
5595 self.unary_op(Op::SigmoidInplace)
5596 }
5597
5598 /// Append a `NegInplace` node — mutates `self`'s storage with
5599 /// `-self`. See `NodeHandle::neg` for the functional variant.
5600 pub fn neg_inplace(&self) -> NodeHandle {
5601 self.unary_op(Op::NegInplace)
5602 }
5603
5604 /// Append an `AbsInplace` node — mutates `self`'s storage with
5605 /// `|self|`. See `NodeHandle::abs` for the functional variant.
5606 pub fn abs_inplace(&self) -> NodeHandle {
5607 self.unary_op(Op::AbsInplace)
5608 }
5609
5610 /// Append a `SqrInplace` node — mutates `self`'s storage with
5611 /// `self²`. See `NodeHandle::sqr` for the functional variant.
5612 pub fn sqr_inplace(&self) -> NodeHandle {
5613 self.unary_op(Op::SqrInplace)
5614 }
5615
5616 /// Append a `SqrtInplace` node — mutates `self`'s storage with
5617 /// `√self`. See `NodeHandle::sqrt` for the functional variant.
5618 pub fn sqrt_inplace(&self) -> NodeHandle {
5619 self.unary_op(Op::SqrtInplace)
5620 }
5621
5622 /// Append a `RsqrtInplace` node — mutates `self`'s storage with
5623 /// `1/√self`. See `NodeHandle::rsqrt` for the functional variant.
5624 pub fn rsqrt_inplace(&self) -> NodeHandle {
5625 self.unary_op(Op::RsqrtInplace)
5626 }
5627
5628 /// Append a `RecipInplace` node — mutates `self`'s storage with
5629 /// `1/self`. See `NodeHandle::recip` for the functional variant.
5630 pub fn recip_inplace(&self) -> NodeHandle {
5631 self.unary_op(Op::RecipInplace)
5632 }
5633
5634 /// Append an `ExpInplace` node — mutates `self`'s storage with
5635 /// `exp(self)`. See `NodeHandle::exp` for the functional variant.
5636 pub fn exp_inplace(&self) -> NodeHandle {
5637 self.unary_op(Op::ExpInplace)
5638 }
5639
5640 /// Append a `LogInplace` node — mutates `self`'s storage with
5641 /// `ln(self)`. See `NodeHandle::log` for the functional variant.
5642 pub fn log_inplace(&self) -> NodeHandle {
5643 self.unary_op(Op::LogInplace)
5644 }
5645
5646 /// Append a `SinInplace` node — mutates `self`'s storage with
5647 /// `sin(self)`. See `NodeHandle::sin` for the functional variant.
5648 pub fn sin_inplace(&self) -> NodeHandle {
5649 self.unary_op(Op::SinInplace)
5650 }
5651
5652 /// Append a `CosInplace` node — mutates `self`'s storage with
5653 /// `cos(self)`. See `NodeHandle::cos` for the functional variant.
5654 pub fn cos_inplace(&self) -> NodeHandle {
5655 self.unary_op(Op::CosInplace)
5656 }
5657
5658 /// Append a `SignInplace` node — mutates `self`'s storage with
5659 /// `sign(self)`. See `NodeHandle::sign` for the functional variant.
5660 pub fn sign_inplace(&self) -> NodeHandle {
5661 self.unary_op(Op::SignInplace)
5662 }
5663
5664 /// Append a `FloorInplace` node — mutates `self`'s storage with
5665 /// `⌊self⌋`. See `NodeHandle::floor` for the functional variant.
5666 pub fn floor_inplace(&self) -> NodeHandle {
5667 self.unary_op(Op::FloorInplace)
5668 }
5669
5670 /// Append a `CeilInplace` node — mutates `self`'s storage with
5671 /// `⌈self⌉`. See `NodeHandle::ceil` for the functional variant.
5672 pub fn ceil_inplace(&self) -> NodeHandle {
5673 self.unary_op(Op::CeilInplace)
5674 }
5675
5676 /// Append a `RoundInplace` node — mutates `self`'s storage with
5677 /// `round(self)`. See `NodeHandle::round` for the functional variant.
5678 pub fn round_inplace(&self) -> NodeHandle {
5679 self.unary_op(Op::RoundInplace)
5680 }
5681
5682 /// Append an `ErfInplace` node — mutates `self`'s storage with
5683 /// `erf(self)`. See `NodeHandle::erf` for the functional variant.
5684 pub fn erf_inplace(&self) -> NodeHandle {
5685 self.unary_op(Op::ErfInplace)
5686 }
5687
5688 /// Append a `GeluInplace` node — mutates `self`'s storage
5689 /// with the exact-GeLU formula. See `NodeHandle::gelu` for the
5690 /// functional variant.
5691 pub fn gelu_inplace(&self) -> NodeHandle {
5692 self.unary_op(Op::GeluInplace)
5693 }
5694
5695 /// Append a `ClampInplace { min, max }` node — mutates `self`'s
5696 /// storage with `clamp(self, min, max)`. See `NodeHandle::clamp` for
5697 /// the functional variant.
5698 pub fn clamp_inplace(&self, min: f64, max: f64) -> NodeHandle {
5699 self.unary_op(Op::ClampInplace { min, max })
5700 }
5701
5702 /// Append a `PowIInplace(exp)` node — mutates `self`'s storage
5703 /// with `self.powi(exp)`. See `NodeHandle::powi` for the functional
5704 /// variant.
5705 pub fn powi_inplace(&self, exp: i32) -> NodeHandle {
5706 self.unary_op(Op::PowIInplace(exp))
5707 }
5708
5709 /// Append an `Op::Fused(INPLACE_AFFINE, ...)` node — mutates
5710 /// `self`'s storage with `self = mul · self + add`. Single-input
5711 /// fused op (no functional `Op::Affine` exists on
5712 /// `fuel-graph::Op`; the non-inplace equivalent is `self
5713 /// .mul_scalar(mul).add_scalar(add)`). Wired to baracuda's
5714 /// `affine_inplace_*` symbol on CUDA when Phase 3 lands.
5715 pub fn affine_inplace(&self, mul: f64, add: f64) -> NodeHandle {
5716 let shape = self.shape();
5717 let dtype = self.dtype();
5718 let id = self.graph.write().unwrap().push(Node {
5719 op: Op::Fused(
5720 crate::registry::FusedOps::INPLACE_AFFINE,
5721 crate::registry::FusedOpParams::InplaceAffine { mul, add },
5722 ),
5723 inputs: vec![self.id],
5724 shape,
5725 dtype,
5726 });
5727 Self {
5728 graph: self.graph.clone(),
5729 id,
5730 }
5731 }
5732
5733 /// Append a `Floor` node (`⌊self⌋`). Output dtype = input dtype.
5734 /// Backward is the zero distribution almost everywhere; gradient
5735 /// is dropped silently.
5736 pub fn floor(&self) -> NodeHandle {
5737 self.unary_op(Op::Floor)
5738 }
5739
5740 /// Append a `Ceil` node (`⌈self⌉`). Output dtype = input dtype.
5741 /// Backward drops gradient (non-differentiable almost everywhere).
5742 pub fn ceil(&self) -> NodeHandle {
5743 self.unary_op(Op::Ceil)
5744 }
5745
5746 /// Append a `Round` node — banker's rounding (round-half-to-even,
5747 /// IEEE 754 roundeven). 0.5 → 0, 1.5 → 2, 2.5 → 2, 3.5 → 4.
5748 /// Output dtype = input dtype. Backward drops gradient.
5749 pub fn round(&self) -> NodeHandle {
5750 self.unary_op(Op::Round)
5751 }
5752
5753 /// Append a `Sign` node (`-1` / `0` / `1`). `sign(0) = 0` by
5754 /// subgradient convention. Output dtype = input dtype. Backward
5755 /// drops gradient.
5756 pub fn sign(&self) -> NodeHandle {
5757 self.unary_op(Op::Sign)
5758 }
5759
5760 /// Append an `Erf` node (Gauss error function). Output dtype =
5761 /// input dtype. Differentiable.
5762 pub fn erf(&self) -> NodeHandle {
5763 self.unary_op(Op::Erf)
5764 }
5765
5766 /// Append a `Gelu` node — exact-erf formulation of GELU
5767 /// (`0.5 * x * (1 + erf(x/√2))`). Distinct from [`Self::gelu_tanh`]
5768 /// (tanh approximation). Output dtype = input dtype.
5769 /// Differentiable.
5770 pub fn gelu(&self) -> NodeHandle {
5771 self.unary_op(Op::Gelu)
5772 }
5773
5774 /// Append a `Pow` node `pow(self, other)` element-wise (real
5775 /// exponent). Both operands must share dtype and shape. Distinct
5776 /// from [`Self::powi`] (scalar `i32` exponent). NaN follows
5777 /// IEEE-754 (`pow(-2, 0.5) = NaN`).
5778 ///
5779 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5780 /// typed error, not a panic.
5781 pub fn pow(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5782 let out_shape = self.shape();
5783 self.try_binary_op("pow", Op::Pow, other, out_shape)
5784 }
5785
5786 /// Append an `Rsqrt` node (`1 / sqrt(self)`). Same dtype as
5787 /// input. Single op rather than `sqrt(x).recip()` — one kernel
5788 /// launch and matches RMSNorm's `x * rsqrt(...)` shape.
5789 /// Differentiable.
5790 pub fn rsqrt(&self) -> NodeHandle {
5791 self.unary_op(Op::Rsqrt)
5792 }
5793
5794 /// Append a `Rem` node `self % other` element-wise (PyTorch
5795 /// convention: `a - floor(a/b) * b`, sign of result matches
5796 /// divisor). Both operands must share dtype and shape.
5797 /// Differentiable.
5798 ///
5799 /// **Returns `Result`**: dtype/shape mismatch surfaces as a
5800 /// typed error, not a panic.
5801 pub fn rem(&self, other: &NodeHandle) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5802 let out_shape = self.shape();
5803 self.try_binary_op("rem", Op::Rem, other, out_shape)
5804 }
5805
5806 /// Append a `Flip` node — reverses element order along `dim`.
5807 /// Output shape == input shape. Materializing op (real byte
5808 /// shuffle; not a metadata-only view). Differentiable
5809 /// (involutive: backward is another Flip on the same dim).
5810 ///
5811 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5812 pub fn flip(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5813 let in_shape = self.shape();
5814 let rank = in_shape.dims().len();
5815 if dim >= rank {
5816 return Err(fuel_ir::Error::Msg(format!(
5817 "flip: dim {dim} out of bounds for rank {rank}",
5818 ))
5819 .bt());
5820 }
5821 let op = Op::Flip { dim };
5822 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5823 let id = self.graph.write().unwrap().push(Node {
5824 op,
5825 inputs: vec![self.id],
5826 shape,
5827 dtype,
5828 });
5829 Ok(Self {
5830 graph: self.graph.clone(),
5831 id,
5832 })
5833 }
5834
5835 /// Append a `Roll` node — cyclic shift along `dim` by `shift`
5836 /// positions. Positive `shift` moves elements to higher indices
5837 /// (wrapping); negative the opposite. Output shape == input
5838 /// shape. Differentiable (backward is `Roll { dim, -shift }`).
5839 ///
5840 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5841 pub fn roll(&self, dim: usize, shift: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5842 let in_shape = self.shape();
5843 let rank = in_shape.dims().len();
5844 if dim >= rank {
5845 return Err(fuel_ir::Error::Msg(format!(
5846 "roll: dim {dim} out of bounds for rank {rank}",
5847 ))
5848 .bt());
5849 }
5850 let op = Op::Roll { dim, shift };
5851 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
5852 let id = self.graph.write().unwrap().push(Node {
5853 op,
5854 inputs: vec![self.id],
5855 shape,
5856 dtype,
5857 });
5858 Ok(Self {
5859 graph: self.graph.clone(),
5860 id,
5861 })
5862 }
5863
5864 /// Append a `CumSum` node — running cumulative sum along `dim`.
5865 /// Output shape == input shape. Differentiable; backward is
5866 /// reverse-cumsum (`Flip → CumSum → Flip`).
5867 ///
5868 /// **Returns `Result`**: bad `dim` surfaces as a typed error.
5869 pub fn cumsum(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5870 let in_shape = self.shape();
5871 let rank = in_shape.dims().len();
5872 if dim >= rank {
5873 return Err(fuel_ir::Error::Msg(format!(
5874 "cumsum: dim {dim} out of bounds for rank {rank}",
5875 ))
5876 .bt());
5877 }
5878 let dtype = self.dtype();
5879 let id = self.graph.write().unwrap().push(Node {
5880 op: Op::CumSum { dim },
5881 inputs: vec![self.id],
5882 shape: in_shape,
5883 dtype,
5884 });
5885 Ok(Self {
5886 graph: self.graph.clone(),
5887 id,
5888 })
5889 }
5890
5891 /// Append a `Triu` node — upper-triangular mask along the last two
5892 /// dims. `diagonal = 0` keeps the main diagonal and above; positive
5893 /// values shift the cutoff up (keeping less); negative shift down
5894 /// (keeping more, including subdiagonals).
5895 ///
5896 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
5897 pub fn triu(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5898 let in_shape = self.shape();
5899 let rank = in_shape.dims().len();
5900 if rank < 2 {
5901 return Err(fuel_ir::Error::Msg(format!(
5902 "triu: input must have rank >= 2, got {rank}",
5903 ))
5904 .bt());
5905 }
5906 let dtype = self.dtype();
5907 let id = self.graph.write().unwrap().push(Node {
5908 op: Op::Triu { diagonal },
5909 inputs: vec![self.id],
5910 shape: in_shape,
5911 dtype,
5912 });
5913 Ok(Self {
5914 graph: self.graph.clone(),
5915 id,
5916 })
5917 }
5918
5919 /// Append an [`Op::Scan`] node — a bounded `lax.scan` recurrence.
5920 /// `self` is the `init_carry`. The body must already be built in the same
5921 /// graph, referencing `Op::ScanPlaceholder{Carry,0}` for the per-step
5922 /// carry and `Op::ScanPlaceholder{Elem,i}` for the per-step slice of
5923 /// `xs[i]`; `consts` are referenced by real NodeId. `body_new_carry` /
5924 /// `body_y` are the body's two exit nodes. Always a 2-slot bundle
5925 /// (slot 0 = stacked `ys` `[bound] ++ body_y`, slot 1 = final carry);
5926 /// `emit` selects which slot this call projects. `early_exit` is Phase 2
5927 /// (always `None` here).
5928 ///
5929 /// **Returns `Result`**: a malformed body/carry/bound surfaces as a typed
5930 /// error — never a panic.
5931 pub fn scan(
5932 &self,
5933 xs: &[NodeHandle],
5934 consts: &[NodeHandle],
5935 body_new_carry: &NodeHandle,
5936 body_y: &NodeHandle,
5937 bound: usize,
5938 emit: ScanEmit,
5939 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
5940 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
5941 if !same_graph(body_new_carry)
5942 || !same_graph(body_y)
5943 || !xs.iter().all(same_graph)
5944 || !consts.iter().all(same_graph)
5945 {
5946 return Err(fuel_ir::Error::Msg(
5947 "scan: init_carry, xs, consts, and body exits must live on one graph".into(),
5948 )
5949 .bt());
5950 }
5951 if bound == 0 {
5952 return Err(fuel_ir::Error::Msg("scan: bound must be >= 1".into()).bt());
5953 }
5954 let carry_shape = self.shape();
5955 if body_new_carry.shape().dims() != carry_shape.dims() {
5956 return Err(fuel_ir::Error::Msg(format!(
5957 "scan: body_new_carry shape {:?} must equal init_carry shape {:?}",
5958 body_new_carry.shape().dims(),
5959 carry_shape.dims(),
5960 ))
5961 .bt());
5962 }
5963 // Validate body placeholders at graph-build time (single-carry; every
5964 // Elem index < n_xs) so a malformed body is a typed Err here, not a
5965 // later `elem[index]` panic on the unroll / forward-driver path.
5966 {
5967 let g = self.graph.read().unwrap();
5968 crate::scan::validate_scan_body_placeholders(
5969 &g,
5970 &[body_new_carry.id, body_y.id],
5971 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
5972 // construction below); the IR and the unroll are not.
5973 1,
5974 xs.len(),
5975 )?;
5976 }
5977 let carry_dtype = self.dtype();
5978 let y_dtype = body_y.dtype();
5979
5980 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
5981 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
5982 ys_dims.push(bound);
5983 ys_dims.extend_from_slice(body_y.shape().dims());
5984 let ys_shape = Shape::from_dims(&ys_dims);
5985 let specs = vec![
5986 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
5987 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
5988 ];
5989 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs)
5990 .map_err(|e| fuel_ir::Error::Msg(format!("scan: compose_bundle failed: {e}")).bt())?;
5991
5992 let mut inputs: Vec<NodeId> = Vec::with_capacity(2 + xs.len() + consts.len() + 2);
5993 inputs.push(self.id);
5994 inputs.extend(xs.iter().map(|t| t.id));
5995 inputs.extend(consts.iter().map(|t| t.id));
5996 inputs.push(body_new_carry.id);
5997 inputs.push(body_y.id);
5998
5999 let id = {
6000 let mut g = self.graph.write().unwrap();
6001 // Node.shape/dtype are the PRIMARY (slot-0) shape/dtype per the
6002 // multi-output authoring contract.
6003 let id = g.push(Node {
6004 op: Op::Scan {
6005 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6006 // `parse_scan_layout` and `build_scan_step` all handle N
6007 // carries. This BUILDER deliberately still constructs ONE.
6008 //
6009 // Widening it means N+1 output-view specs through
6010 // `compose_bundle` below -- i.e. the bundle arity -- which is
6011 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6012 // is NOT this change. A reader must not read "the builder makes
6013 // one" as "multi-carry does not work".
6014 n_carries: 1,
6015 n_xs: xs.len(),
6016 bound,
6017 emit,
6018 early_exit: None,
6019 },
6020 inputs,
6021 shape: ys_shape,
6022 dtype: y_dtype,
6023 });
6024 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6025 .map_err(|e| {
6026 fuel_ir::Error::Msg(format!("scan: set_output_views failed: {e}")).bt()
6027 })?;
6028 id
6029 };
6030 let producer = Self {
6031 graph: self.graph.clone(),
6032 id,
6033 };
6034 match emit {
6035 ScanEmit::All => producer.view(0),
6036 ScanEmit::Final => producer.view(1),
6037 }
6038 }
6039
6040 /// Append an early-exit [`Op::Scan`] node — the `Result`-returning sibling
6041 /// of [`NodeHandle::scan`] that carries a convergence predicate as the extra
6042 /// trailing input (`early_exit = Some(ScanPredicate)`). `self` is the
6043 /// `init_carry`; `pred_exit` is a scalar-`U8` sub-DAG over the carry
6044 /// (`Op::ScanPlaceholder{Carry,0}` for the pre-step carry, and the shared
6045 /// `body_new_carry` node for the post-step carry) that stops iteration when
6046 /// it fires. The runtime stop count is data-dependent under the static
6047 /// capacity `bound`.
6048 ///
6049 /// **`consts` must include every const referenced by the body OR the
6050 /// predicate** — the clone/unroll machinery shares only `consts`; a
6051 /// predicate const outside `consts` would be re-cloned dataless and fail at
6052 /// realize.
6053 ///
6054 /// **Returns `Result`**: a malformed body/carry/bound, or a non-scalar /
6055 /// non-`U8` / `Elem`-referencing predicate, surfaces as a typed error —
6056 /// never a panic (validated at graph-build time).
6057 pub fn scan_until(
6058 &self,
6059 xs: &[NodeHandle],
6060 consts: &[NodeHandle],
6061 body_new_carry: &NodeHandle,
6062 body_y: &NodeHandle,
6063 pred_exit: &NodeHandle,
6064 bound: usize,
6065 emit: ScanEmit,
6066 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6067 let same_graph = |t: &NodeHandle| Arc::ptr_eq(&self.graph, &t.graph);
6068 if !same_graph(body_new_carry)
6069 || !same_graph(body_y)
6070 || !same_graph(pred_exit)
6071 || !xs.iter().all(same_graph)
6072 || !consts.iter().all(same_graph)
6073 {
6074 return Err(fuel_ir::Error::Msg(
6075 "scan_until: init_carry, xs, consts, body exits, and pred_exit must live on one graph".into(),
6076 ).bt());
6077 }
6078 if bound == 0 {
6079 return Err(fuel_ir::Error::Msg("scan_until: bound must be >= 1".into()).bt());
6080 }
6081 let carry_shape = self.shape();
6082 if body_new_carry.shape().dims() != carry_shape.dims() {
6083 return Err(fuel_ir::Error::Msg(format!(
6084 "scan_until: body_new_carry shape {:?} must equal init_carry shape {:?}",
6085 body_new_carry.shape().dims(),
6086 carry_shape.dims(),
6087 ))
6088 .bt());
6089 }
6090 // Validate body placeholders at graph-build time (single-carry; every
6091 // Elem index < n_xs) so a malformed body is a typed Err here, not a
6092 // later `elem[index]` panic in the forward driver's build_scan_step.
6093 {
6094 let g = self.graph.read().unwrap();
6095 crate::scan::validate_scan_body_placeholders(
6096 &g,
6097 &[body_new_carry.id, body_y.id],
6098 // GAP-303: the BUILDER is still single-carry (see the Op::Scan
6099 // construction below); the IR and the unroll are not.
6100 1,
6101 xs.len(),
6102 )?;
6103 }
6104 // Predicate must be a scalar Bool (shape [] or product == 1) — a
6105 // convergence flag, not a per-element mask. Validate at build time.
6106 // GAP-168(c): Bool, not U8. A predicate's natural producer is a
6107 // comparison, and those now yield Bool, so requiring U8 here would make
6108 // the ordinary `carry.ge(&thr)` path unusable as a predicate.
6109 if pred_exit.dtype() != fuel_ir::DType::Bool {
6110 return Err(fuel_ir::Error::Msg(format!(
6111 "scan_until: pred_exit must be Bool (a boolean flag), got {:?}",
6112 pred_exit.dtype(),
6113 ))
6114 .bt());
6115 }
6116 let pred_dims = pred_exit.shape();
6117 let pred_numel: usize = pred_dims.dims().iter().product();
6118 if pred_numel != 1 {
6119 return Err(fuel_ir::Error::Msg(format!(
6120 "scan_until: pred_exit must be a scalar (shape [] or [1]/all-ones), got {:?}",
6121 pred_dims.dims(),
6122 ))
6123 .bt());
6124 }
6125 // Every ScanPlaceholder reachable from pred_exit must be Carry{0} — the
6126 // predicate is over the carry, never a per-step Elem slice.
6127 {
6128 let g = self.graph.read().unwrap();
6129 for &id in &crate::topo_order_multi(&g, &[pred_exit.id]) {
6130 if let Op::ScanPlaceholder { role, index } = &g.node(id).op {
6131 let bad = matches!(role, ScanRole::Elem) || *index != 0;
6132 if bad {
6133 return Err(fuel_ir::Error::Msg(format!(
6134 "scan_until: pred_exit references ScanPlaceholder{{{role:?}, {index}}} — \
6135 the predicate may only read the carry (Carry, index 0)",
6136 )).bt());
6137 }
6138 }
6139 }
6140 }
6141 let carry_dtype = self.dtype();
6142 let y_dtype = body_y.dtype();
6143
6144 // 2-slot bundle: slot 0 = stacked ys, slot 1 = final carry.
6145 let mut ys_dims: Vec<usize> = Vec::with_capacity(1 + body_y.shape().dims().len());
6146 ys_dims.push(bound);
6147 ys_dims.extend_from_slice(body_y.shape().dims());
6148 let ys_shape = Shape::from_dims(&ys_dims);
6149 let specs = vec![
6150 fuel_ir::storage::OutputViewSpec::contiguous(y_dtype, ys_shape.clone()),
6151 fuel_ir::storage::OutputViewSpec::contiguous(carry_dtype, carry_shape.clone()),
6152 ];
6153 let (_bytes, views) = fuel_ir::storage::compose_bundle(&specs).map_err(|e| {
6154 fuel_ir::Error::Msg(format!("scan_until: compose_bundle failed: {e}")).bt()
6155 })?;
6156
6157 let mut inputs: Vec<NodeId> = Vec::with_capacity(3 + xs.len() + consts.len());
6158 inputs.push(self.id);
6159 inputs.extend(xs.iter().map(|t| t.id));
6160 inputs.extend(consts.iter().map(|t| t.id));
6161 inputs.push(body_new_carry.id);
6162 inputs.push(body_y.id);
6163 inputs.push(pred_exit.id); // <-- the C1 trailing predicate
6164
6165 let id = {
6166 let mut g = self.graph.write().unwrap();
6167 let id = g.push(Node {
6168 op: Op::Scan {
6169 // ⚠️ GAP-303 SCOPE LINE: the IR, the validator, `unroll_scan`,
6170 // `parse_scan_layout` and `build_scan_step` all handle N
6171 // carries. This BUILDER deliberately still constructs ONE.
6172 //
6173 // Widening it means N+1 output-view specs through
6174 // `compose_bundle` below -- i.e. the bundle arity -- which is
6175 // GAP-303 row 2 (`Op::ScatterIntoSlot`, kernel-less today) and
6176 // is NOT this change. A reader must not read "the builder makes
6177 // one" as "multi-carry does not work".
6178 n_carries: 1,
6179 n_xs: xs.len(),
6180 bound,
6181 emit,
6182 early_exit: Some(ScanPredicate),
6183 },
6184 inputs,
6185 shape: ys_shape,
6186 dtype: y_dtype,
6187 });
6188 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
6189 .map_err(|e| {
6190 fuel_ir::Error::Msg(format!("scan_until: set_output_views failed: {e}")).bt()
6191 })?;
6192 id
6193 };
6194 let producer = Self {
6195 graph: self.graph.clone(),
6196 id,
6197 };
6198 match emit {
6199 ScanEmit::All => producer.view(0),
6200 ScanEmit::Final => producer.view(1),
6201 }
6202 }
6203
6204 /// Append a `Tril` node — lower-triangular mask along the last two
6205 /// dims. `diagonal = 0` keeps the main diagonal and below.
6206 /// `tril(diagonal = 0)` is the canonical causal-attention mask.
6207 ///
6208 /// **Returns `Result`**: rank < 2 surfaces as a typed error.
6209 pub fn tril(&self, diagonal: i64) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6210 let in_shape = self.shape();
6211 let rank = in_shape.dims().len();
6212 if rank < 2 {
6213 return Err(fuel_ir::Error::Msg(format!(
6214 "tril: input must have rank >= 2, got {rank}",
6215 ))
6216 .bt());
6217 }
6218 let dtype = self.dtype();
6219 let id = self.graph.write().unwrap().push(Node {
6220 op: Op::Tril { diagonal },
6221 inputs: vec![self.id],
6222 shape: in_shape,
6223 dtype,
6224 });
6225 Ok(Self {
6226 graph: self.graph.clone(),
6227 id,
6228 })
6229 }
6230
6231 /// Append a `LogSoftmaxLastDim` node. Output shape == input shape.
6232 /// Numerically stable (max-subtracting formula) — preferred over
6233 /// `log(softmax(x))` for NLL / cross-entropy loss.
6234 ///
6235 /// **Returns `Result`**: rank < 1 surfaces as a typed error.
6236 pub fn log_softmax_last_dim(&self) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6237 let in_shape = self.shape();
6238 if in_shape.dims().is_empty() {
6239 return Err(fuel_ir::Error::Msg(
6240 "log_softmax_last_dim: input must have rank >= 1".to_string(),
6241 )
6242 .bt());
6243 }
6244 let dtype = self.dtype();
6245 let id = self.graph.write().unwrap().push(Node {
6246 op: Op::LogSoftmaxLastDim,
6247 inputs: vec![self.id],
6248 shape: in_shape,
6249 dtype,
6250 });
6251 Ok(Self {
6252 graph: self.graph.clone(),
6253 id,
6254 })
6255 }
6256
6257 /// Append a `MaskedFill` node. `mask` must be `Bool` (GAP-168(c)) and have
6258 /// the same shape as `self`. Every position where `mask` is true gets `value`;
6259 /// every position where `mask == 0` passes `self` through. `value`
6260 /// is a scalar of `self`'s dtype.
6261 ///
6262 /// **Returns `Result`**: shape or dtype mismatches surface as typed
6263 /// errors.
6264 pub fn masked_fill(
6265 &self,
6266 mask: &NodeHandle,
6267 value: Scalar,
6268 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6269 self.require_same_graph(mask, "masked_fill", "mask")?;
6270 if self.shape().dims() != mask.shape().dims() {
6271 return Err(fuel_ir::Error::Msg(format!(
6272 "masked_fill: x.shape={:?} != mask.shape={:?}",
6273 self.shape().dims(),
6274 mask.shape().dims(),
6275 ))
6276 .bt());
6277 }
6278 if mask.dtype() != DType::Bool {
6279 return Err(fuel_ir::Error::Msg(format!(
6280 "masked_fill: mask dtype must be Bool, got {:?} — cast a numeric \
6281 mask to Bool explicitly (GAP-168(c))",
6282 mask.dtype(),
6283 ))
6284 .bt());
6285 }
6286 // GAP-002 (D5) / GAP-075 (fix B): classify EVERY dtype explicitly — no
6287 // wildcard default. The guard is SEMANTIC: masked_fill needs a
6288 // representable fill value AND a zero (the backward fills with zero), so
6289 // it rejects the packed formats (F4/F6*, no scalar fill) and the
6290 // block-scales (F8E8M0/F8E6M2, no zero), and permits the ordinary
6291 // numeric dtypes. Rejecting on the guard's own terms also keeps the
6292 // `Scalar::zero` Err branch in the MaskedFill `backward` arm provably
6293 // unreachable in a well-formed graph.
6294 //
6295 // Under the OLD denylist (`matches!(reject-set)`, else allow) a FUTURE
6296 // dtype fell through to "permitted" SILENTLY. With new dtypes scheduled
6297 // (GAP-097: e5m2, complex, sub-byte int, …) that would silently accept
6298 // masked_fill on formats whose fill semantics are unsettled. An
6299 // exhaustive match makes a new dtype a COMPILE ERROR here, forcing the
6300 // person who adds it to decide its permission consciously — the compiler
6301 // is the real guard; the tests below protect the existing classification.
6302 //
6303 // NOTE: "permitted" is a graph-build PERMISSION (is masked_fill
6304 // semantically well-defined?), NOT a promise a backend can allocate/run
6305 // the dtype. An unimplemented storage still declines loudly downstream
6306 // (typed `UnsupportedDTypeForOp` at allocation), which is the sound
6307 // composition — a semantically-true guard upstream, a loud capability
6308 // decline downstream.
6309 match self.dtype() {
6310 DType::F4 | DType::F6E2M3 | DType::F6E3M2 | DType::F8E8M0 | DType::F8E6M2 => {
6311 return Err(
6312 fuel_ir::Error::UnsupportedDTypeForOp(self.dtype(), "masked_fill").bt(),
6313 );
6314 }
6315 DType::U8
6316 | DType::I8
6317 | DType::U32
6318 | DType::I16
6319 | DType::I32
6320 | DType::I64
6321 | DType::BF16
6322 | DType::F16
6323 | DType::F32
6324 | DType::F64
6325 | DType::F8E4M3
6326 // GAP-097: F8E5M2 is PERMITTED, on the guard's own semantic terms.
6327 //
6328 // The reject set above is not "exotic dtypes" — it is two distinct
6329 // NON-VALUE categories: the block-scales (F8E8M0/F8E6M2) ride as
6330 // sibling operands and are not element value dtypes at all, and the
6331 // block-scoped elements (F4/F6*) have no standalone byte layout, so
6332 // a single element is not addressable without its block. Neither has
6333 // a well-defined fill-one-element operation, which is what this op
6334 // needs. F8E5M2 is a value dtype in exactly the way F8E4M3 (already
6335 // permitted, directly above) is: sign + exponent + mantissa, a
6336 // standalone byte layout, a representable zero for the backward, and
6337 // a representable fill value. So permitting it CONTINUES the
6338 // existing classification; rejecting would be the exception.
6339 //
6340 // Weighed and rejected as grounds for the opposite call: F8E5M2
6341 // currently has NO host or CUDA storage (fuel-cpu-backend and
6342 // fuel-cuda-backend both decline it), so this permits a graph the
6343 // backends cannot yet allocate — GAP(GAP-161) tracks that storage
6344 // decline and its expiry. That is the NOTE above working as
6345 // designed — permission is semantic, allocation is a capability, and
6346 // they are different questions. Writing REJECT here would encode the
6347 // claim "F8E5M2 has no representable fill value", which is FALSE and
6348 // would outlive the storage gap that motivated it.
6349 | DType::F8E5M2
6350 // GAP-168(c): Bool is a value dtype with a representable fill value
6351 // (true/false) and a zero for the backward (false) — permitted on
6352 // this guard's own semantic terms, exactly as the FP8 value dtypes
6353 // are. (This is the FILLED tensor's dtype; the MASK dtype is checked
6354 // separately above.)
6355 | DType::Bool => {}
6356 }
6357 if value.dtype() != self.dtype() {
6358 return Err(fuel_ir::Error::Msg(format!(
6359 "masked_fill: value dtype {:?} != x dtype {:?}",
6360 value.dtype(),
6361 self.dtype(),
6362 ))
6363 .bt());
6364 }
6365 let op = Op::MaskedFill { value };
6366 let (shape, dtype) = crate::shape::primitive_shape(
6367 &op,
6368 &[self.shape(), mask.shape()],
6369 &[self.dtype(), mask.dtype()],
6370 )
6371 .expect("masked_fill: shapes/dtypes validated above");
6372 let id = self.graph.write().unwrap().push(Node {
6373 op,
6374 inputs: vec![self.id, mask.id],
6375 shape,
6376 dtype,
6377 });
6378 Ok(Self {
6379 graph: self.graph.clone(),
6380 id,
6381 })
6382 }
6383
6384 /// Append a `Pad` node — multi-dim padding. `padding[i] = (before, after)`
6385 /// for axis `i`; `padding.len()` must equal `self.rank()`.
6386 /// Output shape: `out[i] = in[i] + padding[i].0 + padding[i].1`.
6387 /// `value` is the fill constant for [`PadMode::Constant`]
6388 /// (ignored for other modes).
6389 ///
6390 /// Only Constant mode is wired through the executor in the v1
6391 /// cut; the other modes produce a clean error at realize time.
6392 /// Differentiable for Constant (backward slices the gradient
6393 /// along each padded axis to restore the input shape).
6394 ///
6395 /// **Returns `Result`**: rank mismatch surfaces as a typed error.
6396 pub fn pad(
6397 &self,
6398 padding: Vec<(usize, usize)>,
6399 mode: PadMode,
6400 value: f64,
6401 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6402 let in_shape = self.shape();
6403 let rank = in_shape.dims().len();
6404 if padding.len() != rank {
6405 return Err(fuel_ir::Error::Msg(format!(
6406 "pad: padding.len() ({}) must equal tensor rank ({rank})",
6407 padding.len(),
6408 ))
6409 .bt());
6410 }
6411 let op = Op::Pad {
6412 padding,
6413 mode,
6414 value,
6415 };
6416 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6417 let id = self.graph.write().unwrap().push(Node {
6418 op,
6419 inputs: vec![self.id],
6420 shape,
6421 dtype,
6422 });
6423 Ok(Self {
6424 graph: self.graph.clone(),
6425 id,
6426 })
6427 }
6428
6429 /// Append an `Equal` node (`self == other`) producing a `Bool` mask.
6430 /// Both operands must share dtype and shape; output dtype is `Bool`
6431 /// (`1` where equal, `0` otherwise). NaN follows IEEE-754
6432 /// (`NaN == NaN` is false). Non-differentiable.
6433 ///
6434 /// # Panics
6435 ///
6436 /// Panics if any operand belongs to a different [`Graph`] than the one this
6437 /// builder is building into. Operand identity is graph-scoped and checked by
6438 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6439 /// deliberate and replaces the hang a cross-graph handle used to produce.
6440 /// Build every operand from one graph, or use a `Result`-returning entry
6441 /// point where one exists.
6442 pub fn eq(&self, other: &NodeHandle) -> NodeHandle {
6443 self.binary_compare_op("eq", Op::Equal, other)
6444 }
6445
6446 /// Append a `Ne` node (`self != other`) producing a `Bool` mask.
6447 /// Same shape/dtype contract as [`Self::eq`]. NaN follows
6448 /// IEEE-754 (`NaN != NaN` is true → `1`). Non-differentiable.
6449 ///
6450 /// # Panics
6451 ///
6452 /// Panics if any operand belongs to a different [`Graph`] than the one this
6453 /// builder is building into. Operand identity is graph-scoped and checked by
6454 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6455 /// deliberate and replaces the hang a cross-graph handle used to produce.
6456 /// Build every operand from one graph, or use a `Result`-returning entry
6457 /// point where one exists.
6458 pub fn ne(&self, other: &NodeHandle) -> NodeHandle {
6459 self.binary_compare_op("ne", Op::Ne, other)
6460 }
6461
6462 /// Append an `Lt` node (`self < other`) producing a `Bool` mask.
6463 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6464 /// is always `0` (IEEE-754 unordered). Non-differentiable.
6465 ///
6466 /// # Panics
6467 ///
6468 /// Panics if any operand belongs to a different [`Graph`] than the one this
6469 /// builder is building into. Operand identity is graph-scoped and checked by
6470 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6471 /// deliberate and replaces the hang a cross-graph handle used to produce.
6472 /// Build every operand from one graph, or use a `Result`-returning entry
6473 /// point where one exists.
6474 pub fn lt(&self, other: &NodeHandle) -> NodeHandle {
6475 self.binary_compare_op("lt", Op::Lt, other)
6476 }
6477
6478 /// Append an `Le` node (`self <= other`) producing a `Bool` mask.
6479 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6480 /// is always `0`. Non-differentiable.
6481 ///
6482 /// # Panics
6483 ///
6484 /// Panics if any operand belongs to a different [`Graph`] than the one this
6485 /// builder is building into. Operand identity is graph-scoped and checked by
6486 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6487 /// deliberate and replaces the hang a cross-graph handle used to produce.
6488 /// Build every operand from one graph, or use a `Result`-returning entry
6489 /// point where one exists.
6490 pub fn le(&self, other: &NodeHandle) -> NodeHandle {
6491 self.binary_compare_op("le", Op::Le, other)
6492 }
6493
6494 /// Append a `Gt` node (`self > other`) producing a `Bool` mask.
6495 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6496 /// is always `0`. Non-differentiable.
6497 ///
6498 /// # Panics
6499 ///
6500 /// Panics if any operand belongs to a different [`Graph`] than the one this
6501 /// builder is building into. Operand identity is graph-scoped and checked by
6502 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6503 /// deliberate and replaces the hang a cross-graph handle used to produce.
6504 /// Build every operand from one graph, or use a `Result`-returning entry
6505 /// point where one exists.
6506 pub fn gt(&self, other: &NodeHandle) -> NodeHandle {
6507 self.binary_compare_op("gt", Op::Gt, other)
6508 }
6509
6510 /// Append a `Ge` node (`self >= other`) producing a `Bool` mask.
6511 /// Same shape/dtype contract as [`Self::eq`]. NaN-on-either-side
6512 /// is always `0`. Non-differentiable.
6513 ///
6514 /// # Panics
6515 ///
6516 /// Panics if any operand belongs to a different [`Graph`] than the one this
6517 /// builder is building into. Operand identity is graph-scoped and checked by
6518 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6519 /// deliberate and replaces the hang a cross-graph handle used to produce.
6520 /// Build every operand from one graph, or use a `Result`-returning entry
6521 /// point where one exists.
6522 pub fn ge(&self, other: &NodeHandle) -> NodeHandle {
6523 self.binary_compare_op("ge", Op::Ge, other)
6524 }
6525
6526 /// Ternary select: `result[i] = if self[i] { a[i] } else { b[i] }`.
6527 /// Receiver is the `cond` mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
6528 /// must share dtype with each other and shape with `self`. Output
6529 /// dtype matches `a`/`b`. Returning a new tensor where each slot is
6530 /// picked from `a` (cond=1) or `b` (cond=0).
6531 ///
6532 /// Named `where_cond` because `where` is a Rust reserved keyword.
6533 /// Common spelling in Candle/PyTorch families.
6534 ///
6535 /// Differentiable through `a` and `b` only; gradient through the
6536 /// cond mask is `None` (registered in
6537 /// [`crate::grad::WhereRule`]).
6538 ///
6539 /// # Panics
6540 ///
6541 /// Panics if any operand belongs to a different [`Graph`] than the one this
6542 /// builder is building into. Operand identity is graph-scoped and checked by
6543 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
6544 /// deliberate and replaces the hang a cross-graph handle used to produce.
6545 /// Build every operand from one graph, or use a `Result`-returning entry
6546 /// point where one exists.
6547 pub fn where_cond(&self, a: &NodeHandle, b: &NodeHandle) -> NodeHandle {
6548 assert!(
6549 Arc::ptr_eq(&self.graph, &a.graph) && Arc::ptr_eq(&self.graph, &b.graph),
6550 "where_cond: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
6551 );
6552 assert_eq!(
6553 self.dtype(),
6554 DType::Bool,
6555 "where_cond: cond must be Bool (GAP-168(c)), got {:?} — cast a numeric \
6556 mask to Bool explicitly",
6557 self.dtype(),
6558 );
6559 assert_eq!(
6560 a.dtype(),
6561 b.dtype(),
6562 "where_cond: a/b dtype mismatch: a={:?}, b={:?}",
6563 a.dtype(),
6564 b.dtype(),
6565 );
6566 assert_eq!(
6567 self.shape().dims(),
6568 a.shape().dims(),
6569 "where_cond: cond/a shape mismatch: cond={:?}, a={:?}",
6570 self.shape().dims(),
6571 a.shape().dims(),
6572 );
6573 assert_eq!(
6574 self.shape().dims(),
6575 b.shape().dims(),
6576 "where_cond: cond/b shape mismatch: cond={:?}, b={:?}",
6577 self.shape().dims(),
6578 b.shape().dims(),
6579 );
6580 let (shape, dtype) = crate::shape::primitive_shape(
6581 &Op::Where,
6582 &[self.shape(), a.shape(), b.shape()],
6583 &[self.dtype(), a.dtype(), b.dtype()],
6584 )
6585 .expect("where_cond: shapes/dtypes validated above");
6586 let id = self.graph.write().unwrap().push(Node {
6587 op: Op::Where,
6588 inputs: vec![self.id, a.id, b.id],
6589 shape,
6590 dtype,
6591 });
6592 Self {
6593 graph: self.graph.clone(),
6594 id,
6595 }
6596 }
6597
6598 // --- dtype and broadcasting ---
6599
6600 /// Append a `Cast` node converting this tensor's element type to
6601 /// `target`. Shape is preserved. An identity cast (`target` equals the
6602 /// current dtype) is a no-op that the optimizer elides (see
6603 /// `opt::optimize`'s identity-`Cast` rule) — kept here rather than
6604 /// special-cased at construction so every identity cast, however it
6605 /// arises (decompose, autograd, user), is removed in one place.
6606 pub fn cast(&self, target: DType) -> NodeHandle {
6607 let op = Op::Cast(target);
6608 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6609 .expect("cast: single input, dtype change always infers");
6610 let id = self.graph.write().unwrap().push(Node {
6611 op,
6612 inputs: vec![self.id],
6613 shape,
6614 dtype,
6615 });
6616 Self {
6617 graph: self.graph.clone(),
6618 id,
6619 }
6620 }
6621
6622 /// Append a `BroadcastTo` node that expands `self` to the given target
6623 /// shape using NumPy broadcasting rules (right-align, pad with 1s,
6624 /// expand size-1 dims). The new tensor has the target shape and the
6625 /// same dtype as `self`.
6626 pub fn broadcast_to(&self, target: impl Into<Shape>) -> NodeHandle {
6627 let target = target.into();
6628 let src_dims = self.shape();
6629 // Validate broadcast compatibility up front so users hear about
6630 // bad target shapes at build time, not realize time.
6631 check_broadcast_compatible(src_dims.dims(), target.dims());
6632 let op = Op::BroadcastTo(target);
6633 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6634 .expect("broadcast_to: compatibility validated above");
6635 let id = self.graph.write().unwrap().push(Node {
6636 op,
6637 inputs: vec![self.id],
6638 shape,
6639 dtype,
6640 });
6641 Self {
6642 graph: self.graph.clone(),
6643 id,
6644 }
6645 }
6646
6647 /// Result-returning sibling of [`Self::broadcast_to`]. Surfaces
6648 /// shape incompatibility as a typed error rather than panicking.
6649 pub fn try_broadcast_to(
6650 &self,
6651 target: impl Into<Shape>,
6652 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6653 let target = target.into();
6654 let src_dims = self.shape();
6655 try_check_broadcast_compatible(src_dims.dims(), target.dims())?;
6656 let op = Op::BroadcastTo(target);
6657 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6658 let id = self.graph.write().unwrap().push(Node {
6659 op,
6660 inputs: vec![self.id],
6661 shape,
6662 dtype,
6663 });
6664 Ok(Self {
6665 graph: self.graph.clone(),
6666 id,
6667 })
6668 }
6669
6670 /// Append an `Unsqueeze` node that inserts a size-1 dimension at
6671 /// position `dim`. `dim` must be in `0..=rank` (where `dim == rank`
6672 /// appends to the end). Pure metadata — the output shares bytes
6673 /// with `self`, with a new size-1 axis layered into the Layout
6674 /// side-table. Strictly more efficient than `reshape` for the
6675 /// size-1-insertion case because non-contiguous (e.g. transposed
6676 /// or broadcast) inputs flow through without auto-Contiguize.
6677 pub fn unsqueeze(&self, dim: usize) -> NodeHandle {
6678 let in_shape = self.shape();
6679 let rank = in_shape.dims().len();
6680 assert!(
6681 dim <= rank,
6682 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6683 );
6684 let op = Op::Unsqueeze { dim };
6685 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6686 .expect("unsqueeze: dim validated above");
6687 let id = self.graph.write().unwrap().push(Node {
6688 op,
6689 inputs: vec![self.id],
6690 shape,
6691 dtype,
6692 });
6693 Self {
6694 graph: self.graph.clone(),
6695 id,
6696 }
6697 }
6698
6699 /// Result-returning sibling of [`Self::unsqueeze`]. Surfaces
6700 /// `dim > rank` as a typed error rather than panicking.
6701 pub fn try_unsqueeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6702 let in_shape = self.shape();
6703 let rank = in_shape.dims().len();
6704 if dim > rank {
6705 return Err(fuel_ir::Error::Msg(format!(
6706 "unsqueeze: dim {dim} out of bounds for rank {rank} (must be <= rank)",
6707 ))
6708 .bt());
6709 }
6710 let op = Op::Unsqueeze { dim };
6711 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6712 let id = self.graph.write().unwrap().push(Node {
6713 op,
6714 inputs: vec![self.id],
6715 shape,
6716 dtype,
6717 });
6718 Ok(Self {
6719 graph: self.graph.clone(),
6720 id,
6721 })
6722 }
6723
6724 /// Append a `Squeeze` node that drops the size-1 dimension at
6725 /// position `dim` (range `0..rank`). Inverse of [`Self::unsqueeze`].
6726 /// Metadata-only view: the output shares bytes with `self`, with
6727 /// the named dim pruned from the Layout side-table.
6728 ///
6729 /// **Returns `Result`** rather than panicking — production paths
6730 /// can recover from a bad `dim` instead of crashing. Bad `dim`
6731 /// (out of bounds OR `shape[dim] != 1`) surfaces as a typed error.
6732 pub fn squeeze(&self, dim: usize) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6733 let in_shape = self.shape();
6734 let rank = in_shape.dims().len();
6735 if dim >= rank {
6736 return Err(fuel_ir::Error::Msg(format!(
6737 "squeeze: dim {dim} out of bounds for rank {rank} (must be < rank)",
6738 ))
6739 .bt());
6740 }
6741 if in_shape.dims()[dim] != 1 {
6742 return Err(fuel_ir::Error::Msg(format!(
6743 "squeeze: dim {dim} has size {}, expected 1",
6744 in_shape.dims()[dim],
6745 ))
6746 .bt());
6747 }
6748 let op = Op::Squeeze { dim };
6749 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])?;
6750 let id = self.graph.write().unwrap().push(Node {
6751 op,
6752 inputs: vec![self.id],
6753 shape,
6754 dtype,
6755 });
6756 Ok(Self {
6757 graph: self.graph.clone(),
6758 id,
6759 })
6760 }
6761
6762 /// Append an `Op::Contiguize` node that materializes a
6763 /// contiguous copy of `self`. Output shape and dtype match the
6764 /// input; only the layout changes to contiguous + zero-offset.
6765 /// Zero-copy when the input is already contiguous + zero-offset
6766 /// (the executor adopts the input Storage Arc unchanged).
6767 ///
6768 /// First-class IR node so the optimizer (Phase 2.2) can insert
6769 /// layout-fixups before kernels that don't advertise
6770 /// `crate::KernelCaps::strided_input` without overloading
6771 /// [`Self::reshape`]'s "change shape" semantics.
6772 pub fn contiguize(&self) -> NodeHandle {
6773 let shape = self.shape().clone();
6774 let dtype = self.dtype();
6775 let id = self.graph.write().unwrap().push(Node {
6776 op: Op::Contiguize,
6777 inputs: vec![self.id],
6778 shape,
6779 dtype,
6780 });
6781 Self {
6782 graph: self.graph.clone(),
6783 id,
6784 }
6785 }
6786
6787 /// Append a `Reshape` node producing `self`'s data under a new shape.
6788 /// The new shape must have the same total element count as the
6789 /// current shape.
6790 pub fn reshape(&self, target: impl Into<Shape>) -> NodeHandle {
6791 let target = target.into();
6792 assert_eq!(
6793 self.shape().elem_count(),
6794 target.elem_count(),
6795 "reshape: element count mismatch: from {} to {}",
6796 self.shape().elem_count(),
6797 target.elem_count(),
6798 );
6799 let op = Op::Reshape(target);
6800 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6801 .expect("reshape: element count validated above");
6802 let id = self.graph.write().unwrap().push(Node {
6803 op,
6804 inputs: vec![self.id],
6805 shape,
6806 dtype,
6807 });
6808 Self {
6809 graph: self.graph.clone(),
6810 id,
6811 }
6812 }
6813
6814 /// Result-returning sibling of [`Self::reshape`]. Surfaces
6815 /// element-count mismatch as a typed error rather than panicking.
6816 pub fn try_reshape(
6817 &self,
6818 target: impl Into<Shape>,
6819 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
6820 let target = target.into();
6821 let from = self.shape().elem_count();
6822 let to = target.elem_count();
6823 if from != to {
6824 return Err(fuel_ir::Error::Msg(format!(
6825 "reshape: element count mismatch: from {from} to {to}",
6826 ))
6827 .bt());
6828 }
6829 let op = Op::Reshape(target);
6830 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])?;
6831 let id = self.graph.write().unwrap().push(Node {
6832 op,
6833 inputs: vec![self.id],
6834 shape,
6835 dtype,
6836 });
6837 Ok(Self {
6838 graph: self.graph.clone(),
6839 id,
6840 })
6841 }
6842
6843 /// Append a `ReduceSumTo` node that sum-reduces `self` to a smaller
6844 /// shape. The target must be reachable from `self.shape()` via
6845 /// reduction of dims (i.e. `self.shape()` could be produced from
6846 /// `target` by broadcasting).
6847 pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> NodeHandle {
6848 let target = target.into();
6849 // Symmetric check: self must be broadcast-compatible FROM the
6850 // smaller target. That is, the target must be broadcast-ready to
6851 // self.shape().
6852 check_broadcast_compatible(target.dims(), self.shape().dims());
6853 let op = Op::ReduceSumTo(target);
6854 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6855 .expect("reduce_sum_to: compatibility validated above");
6856 let id = self.graph.write().unwrap().push(Node {
6857 op,
6858 inputs: vec![self.id],
6859 shape,
6860 dtype,
6861 });
6862 Self {
6863 graph: self.graph.clone(),
6864 id,
6865 }
6866 }
6867
6868 /// Append a `ReduceMaxTo` node that max-reduces `self` to a smaller
6869 /// shape — the max-symmetric counterpart of [`Self::reduce_sum_to`].
6870 /// The target must be reachable from `self.shape()` via reduction
6871 /// of dims (i.e. `self.shape()` could be produced from `target` by
6872 /// broadcasting).
6873 pub fn reduce_max_to(&self, target: impl Into<Shape>) -> NodeHandle {
6874 let target = target.into();
6875 check_broadcast_compatible(target.dims(), self.shape().dims());
6876 let op = Op::ReduceMaxTo(target);
6877 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
6878 .expect("reduce_max_to: compatibility validated above");
6879 let id = self.graph.write().unwrap().push(Node {
6880 op,
6881 inputs: vec![self.id],
6882 shape,
6883 dtype,
6884 });
6885 Self {
6886 graph: self.graph.clone(),
6887 id,
6888 }
6889 }
6890
6891 // --- reductions to a scalar ---
6892
6893 /// Append a `SumAll` node reducing every element to a scalar (rank-0).
6894 pub fn sum_all(&self) -> NodeHandle {
6895 self.scalar_reduction(Op::SumAll)
6896 }
6897
6898 /// Append a `MaxAll` node producing the max element as a scalar.
6899 pub fn max_all(&self) -> NodeHandle {
6900 self.scalar_reduction(Op::MaxAll)
6901 }
6902
6903 /// Append a `MinAll` node producing the min element as a scalar.
6904 pub fn min_all(&self) -> NodeHandle {
6905 self.scalar_reduction(Op::MinAll)
6906 }
6907
6908 /// Append a `MeanAll` node producing the arithmetic mean as a scalar.
6909 pub fn mean_all(&self) -> NodeHandle {
6910 self.scalar_reduction(Op::MeanAll)
6911 }
6912
6913 // --- reductions along one dimension ---
6914
6915 /// Append a `SumDim(dim)` node. Reduces along `dim`; output rank is
6916 /// `input rank - 1` (the reduced dim is removed).
6917 pub fn sum_dim(&self, dim: usize) -> NodeHandle {
6918 self.axis_reduction("sum_dim", Op::SumDim(dim), dim)
6919 }
6920
6921 /// Append a `MaxDim(dim)` node.
6922 pub fn max_dim(&self, dim: usize) -> NodeHandle {
6923 self.axis_reduction("max_dim", Op::MaxDim(dim), dim)
6924 }
6925
6926 /// Append a `MinDim(dim)` node.
6927 pub fn min_dim(&self, dim: usize) -> NodeHandle {
6928 self.axis_reduction("min_dim", Op::MinDim(dim), dim)
6929 }
6930
6931 /// Append a `MeanDim(dim)` node.
6932 pub fn mean_dim(&self, dim: usize) -> NodeHandle {
6933 self.axis_reduction("mean_dim", Op::MeanDim(dim), dim)
6934 }
6935
6936 /// Append an `ArgMaxDim(dim)` node. Produces a U32 tensor with the
6937 /// reduced dim removed, whose values are the index of the maximum
6938 /// along that dim. Non-differentiable — trying to run `backward()`
6939 /// through an ArgMax node will panic.
6940 pub fn argmax_dim(&self, dim: usize) -> NodeHandle {
6941 self.index_reduction("argmax_dim", Op::ArgMaxDim(dim), dim)
6942 }
6943
6944 /// Append an `ArgMinDim(dim)` node. Same semantics as `argmax_dim`
6945 /// but for the minimum.
6946 pub fn argmin_dim(&self, dim: usize) -> NodeHandle {
6947 self.index_reduction("argmin_dim", Op::ArgMinDim(dim), dim)
6948 }
6949
6950 /// Internal helper for index-producing reductions. Validates the
6951 /// dim, builds the reduced shape, and stamps the output with
6952 /// `DType::U32` regardless of the input dtype.
6953 fn index_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
6954 let in_shape = self.shape();
6955 assert!(
6956 dim < in_shape.dims().len(),
6957 "{name}: dim {dim} out of bounds for shape {:?}",
6958 in_shape.dims(),
6959 );
6960 // primitive_shape carries both the rank-reduced shape and the U32
6961 // index dtype for ArgMaxDim/ArgMinDim (the single source of truth).
6962 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
6963 .expect("index_reduction: dim validated above");
6964 let id = self.graph.write().unwrap().push(Node {
6965 op,
6966 inputs: vec![self.id],
6967 shape,
6968 dtype,
6969 });
6970 Self {
6971 graph: self.graph.clone(),
6972 id,
6973 }
6974 }
6975
6976 // --- compositions ---
6977
6978 /// Append a `SoftmaxLastDim` node. Shape is preserved.
6979 ///
6980 /// Phase 7.6 step 3: emits `Op::Fused(FusedOps::SOFTMAX_LAST_DIM,
6981 /// FusedOpParams::SoftmaxLastDim)` — the registry-extended arm.
6982 /// The legacy `Op::SoftmaxLastDim` variant remains in the enum
6983 /// during the migration; step 5 drops it once nothing emits it.
6984 pub fn softmax_last_dim(&self) -> NodeHandle {
6985 assert!(
6986 !self.shape().dims().is_empty(),
6987 "softmax_last_dim: input must be rank >= 1",
6988 );
6989 self.unary_op(Op::Fused(
6990 crate::registry::FusedOps::SOFTMAX_LAST_DIM,
6991 crate::registry::FusedOpParams::SoftmaxLastDim,
6992 ))
6993 }
6994
6995 /// Append a `CausalConv1d` node — depthwise 1-D causal convolution
6996 /// + bias + optional fused SiLU. Three inputs:
6997 /// - `self` (x): `[batch, channels, seq + kernel - 1]` F32
6998 /// (caller pre-pads with `kernel - 1` zeros on the left for the
6999 /// causal mask — matches Mamba-2's prefill convention).
7000 /// - `weight`: `[channels, 1, kernel]` F32 (depthwise — one filter
7001 /// per channel; `groups == channels`).
7002 /// - `bias`: `[channels]` F32 (required — matches baracuda's
7003 /// `causal_conv1d_*_run` signature; pass zeros if you don't want
7004 /// a bias).
7005 ///
7006 /// Output: `[batch, channels, seq]` F32 where `seq = x.dims[2] -
7007 /// (kernel - 1)`.
7008 ///
7009 /// Emits `Op::Fused(FusedOps::CAUSAL_CONV1D,
7010 /// FusedOpParams::CausalConv1d { use_silu })`. See
7011 /// `fuel-graph/src/registry/causal_conv1d.rs` for the registry
7012 /// entry. No primitive decomposition exists (fuel-graph has no
7013 /// `Op::Conv1D`); backends without a native kernel fall through
7014 /// to the executor's cpu_fallback path.
7015 ///
7016 /// # Panics
7017 ///
7018 /// Panics if any operand belongs to a different [`Graph`] than the one this
7019 /// builder is building into. Operand identity is graph-scoped and checked by
7020 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7021 /// deliberate and replaces the hang a cross-graph handle used to produce.
7022 /// Build every operand from one graph, or use a `Result`-returning entry
7023 /// point where one exists.
7024 pub fn causal_conv1d(
7025 &self,
7026 weight: &NodeHandle,
7027 bias: &NodeHandle,
7028 use_silu: bool,
7029 ) -> NodeHandle {
7030 assert!(
7031 Arc::ptr_eq(&self.graph, &weight.graph) && Arc::ptr_eq(&self.graph, &bias.graph),
7032 "causal_conv1d: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7033 );
7034 let dtype = self.dtype();
7035 assert!(
7036 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7037 "causal_conv1d: x must be F32/F64/BF16/F16, got {dtype:?}",
7038 );
7039 assert_eq!(
7040 weight.dtype(),
7041 dtype,
7042 "causal_conv1d: weight dtype {:?} must match x dtype {dtype:?}",
7043 weight.dtype(),
7044 );
7045 assert_eq!(
7046 bias.dtype(),
7047 dtype,
7048 "causal_conv1d: bias dtype {:?} must match x dtype {dtype:?}",
7049 bias.dtype(),
7050 );
7051 let x_dims = self.shape();
7052 let x_dims = x_dims.dims();
7053 let w_dims = weight.shape();
7054 let w_dims = w_dims.dims();
7055 let b_dims = bias.shape();
7056 let b_dims = b_dims.dims();
7057 assert_eq!(
7058 x_dims.len(),
7059 3,
7060 "causal_conv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
7061 );
7062 assert_eq!(
7063 w_dims.len(),
7064 3,
7065 "causal_conv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
7066 );
7067 assert_eq!(
7068 b_dims.len(),
7069 1,
7070 "causal_conv1d: bias must be rank 1 [channels], got {b_dims:?}",
7071 );
7072 let batch = x_dims[0];
7073 let channels = x_dims[1];
7074 let x_seq = x_dims[2];
7075 let kernel = w_dims[2];
7076 assert_eq!(
7077 w_dims[0], channels,
7078 "causal_conv1d: weight's first dim {} must equal channels {channels}",
7079 w_dims[0],
7080 );
7081 assert_eq!(
7082 w_dims[1], 1,
7083 "causal_conv1d: weight's middle dim must be 1 (depthwise), got {}",
7084 w_dims[1],
7085 );
7086 assert_eq!(
7087 b_dims[0], channels,
7088 "causal_conv1d: bias length {} must equal channels {channels}",
7089 b_dims[0],
7090 );
7091 assert!(
7092 x_seq >= kernel - 1,
7093 "causal_conv1d: x time dim {x_seq} must be ≥ kernel - 1 = {} \
7094 (caller must pre-pad with {} zeros)",
7095 kernel - 1,
7096 kernel - 1,
7097 );
7098 let out_seq = x_seq - (kernel - 1);
7099 let id = self.graph.write().unwrap().push(Node {
7100 op: Op::Fused(
7101 crate::registry::FusedOps::CAUSAL_CONV1D,
7102 crate::registry::FusedOpParams::CausalConv1d { use_silu },
7103 ),
7104 inputs: vec![self.id, weight.id, bias.id],
7105 shape: Shape::from_dims(&[batch, channels, out_seq]),
7106 dtype,
7107 });
7108 Self {
7109 graph: self.graph.clone(),
7110 id,
7111 }
7112 }
7113
7114 /// Append an `Nf4Matmul` node — bitsandbytes-style 4-bit
7115 /// NormalFloat quantized matrix multiply. Three inputs:
7116 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7117 /// - `w_packed`: `[N, K/2]` U8 (two 4-bit codes per byte)
7118 /// - `absmax`: `[N, K/block_size]` F32 (per-output-row, per-block)
7119 ///
7120 /// Output: `[..., M, N]` matching activations' dtype.
7121 ///
7122 /// `block_size` is the NF4 quantization block size (typically 64
7123 /// in bitsandbytes). `K` must be even AND a multiple of
7124 /// `block_size`.
7125 ///
7126 /// Emits `Op::Fused(FusedOps::NF4_MATMUL, FusedOpParams::Nf4Matmul
7127 /// { block_size })`. No primitive decomposition (the dequant +
7128 /// matmul roundtrip is exactly what NF4's fused dequant-in-kernel
7129 /// design avoids); backends without a native kernel fall through
7130 /// to the executor's cpu_fallback path.
7131 ///
7132 /// # Panics
7133 ///
7134 /// Panics if any operand belongs to a different [`Graph`] than the one this
7135 /// builder is building into. Operand identity is graph-scoped and checked by
7136 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7137 /// deliberate and replaces the hang a cross-graph handle used to produce.
7138 /// Build every operand from one graph, or use a `Result`-returning entry
7139 /// point where one exists.
7140 pub fn nf4_matmul(
7141 &self,
7142 w_packed: &NodeHandle,
7143 absmax: &NodeHandle,
7144 block_size: usize,
7145 ) -> NodeHandle {
7146 assert!(
7147 Arc::ptr_eq(&self.graph, &w_packed.graph) && Arc::ptr_eq(&self.graph, &absmax.graph),
7148 "nf4_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7149 );
7150 let act_dtype = self.dtype();
7151 assert!(
7152 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7153 "nf4_matmul v1: activations must be F32/F16/BF16, got {:?}",
7154 act_dtype,
7155 );
7156 assert_eq!(
7157 w_packed.dtype(),
7158 DType::U8,
7159 "nf4_matmul: w_packed must be U8 (two 4-bit codes per byte), got {:?}",
7160 w_packed.dtype(),
7161 );
7162 assert_eq!(
7163 absmax.dtype(),
7164 DType::F32,
7165 "nf4_matmul: absmax must be F32, got {:?}",
7166 absmax.dtype(),
7167 );
7168 let a_dims = self.shape();
7169 let a_dims = a_dims.dims();
7170 let w_dims = w_packed.shape();
7171 let w_dims = w_dims.dims();
7172 let abs_dims = absmax.shape();
7173 let abs_dims = abs_dims.dims();
7174 assert!(
7175 a_dims.len() >= 2,
7176 "nf4_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7177 );
7178 assert_eq!(
7179 w_dims.len(),
7180 2,
7181 "nf4_matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
7182 );
7183 assert_eq!(
7184 abs_dims.len(),
7185 2,
7186 "nf4_matmul: absmax must be rank 2 [n, k/block_size], got {abs_dims:?}",
7187 );
7188 let _m = a_dims[a_dims.len() - 2];
7189 let k = a_dims[a_dims.len() - 1];
7190 let n = w_dims[0];
7191 assert!(
7192 k.is_multiple_of(2),
7193 "nf4_matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
7194 );
7195 assert!(
7196 block_size > 0 && k.is_multiple_of(block_size),
7197 "nf4_matmul: k={k} must be a positive multiple of block_size={block_size}",
7198 );
7199 assert_eq!(
7200 w_dims[1],
7201 k / 2,
7202 "nf4_matmul: w_packed second dim {} must equal k/2 = {}",
7203 w_dims[1],
7204 k / 2,
7205 );
7206 assert_eq!(
7207 abs_dims,
7208 &[n, k / block_size][..],
7209 "nf4_matmul: absmax {abs_dims:?} must be [n={n}, k/block_size={}]",
7210 k / block_size,
7211 );
7212 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7213 out_dims.push(n);
7214 let id = self.graph.write().unwrap().push(Node {
7215 op: Op::Fused(
7216 crate::registry::FusedOps::NF4_MATMUL,
7217 crate::registry::FusedOpParams::Nf4Matmul { block_size },
7218 ),
7219 inputs: vec![self.id, w_packed.id, absmax.id],
7220 shape: Shape::from_dims(&out_dims),
7221 dtype: act_dtype,
7222 });
7223 Self {
7224 graph: self.graph.clone(),
7225 id,
7226 }
7227 }
7228
7229 /// Append an `AwqMatmul` node — AWQ (mit-han-lab) asymmetric int4
7230 /// weight-only matrix multiply. Four inputs:
7231 /// - `self` (activations): `[..., M, K]`, dtype ∈ {F32, F16, BF16}
7232 /// - `qweight`: `[N, K/8]` U32 (eight int4 codes packed per word)
7233 /// - `qzeros`: `[K/group_size, N/8]` U32 (eight int4 zero-point
7234 /// codes packed per word)
7235 /// - `scales`: `[K/group_size, N]` F32 (per-group, per-output-
7236 /// channel scale)
7237 ///
7238 /// Output: `[..., M, N]` matching activations' dtype.
7239 ///
7240 /// `group_size` must be positive and evenly divide `K`. `K` must be a
7241 /// multiple of 8 (`qweight`'s packing); `N` must be a multiple of 8
7242 /// (`qzeros`' packing). `split_k_iters` is a CUDA launch-tuning
7243 /// parameter carried through unused by the (current, decompose-only)
7244 /// execution path — see [`crate::registry::awq_matmul`]'s module doc
7245 /// for what is and isn't wired/verified yet, including the
7246 /// packing-order caveat.
7247 ///
7248 /// Emits `Op::Fused(FusedOps::AWQ_MATMUL, FusedOpParams::AwqMatmul
7249 /// { group_size, split_k_iters })`.
7250 ///
7251 /// # Panics
7252 ///
7253 /// Panics if any operand belongs to a different [`Graph`] than the one
7254 /// this builder is building into, or if any shape/dtype precondition
7255 /// above doesn't hold — same discipline as [`Self::nf4_matmul`].
7256 pub fn awq_matmul(
7257 &self,
7258 qweight: &NodeHandle,
7259 qzeros: &NodeHandle,
7260 scales: &NodeHandle,
7261 group_size: usize,
7262 split_k_iters: i32,
7263 ) -> NodeHandle {
7264 assert!(
7265 Arc::ptr_eq(&self.graph, &qweight.graph)
7266 && Arc::ptr_eq(&self.graph, &qzeros.graph)
7267 && Arc::ptr_eq(&self.graph, &scales.graph),
7268 "awq_matmul: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7269 );
7270 let act_dtype = self.dtype();
7271 assert!(
7272 matches!(act_dtype, DType::F32 | DType::F16 | DType::BF16),
7273 "awq_matmul v1: activations must be F32/F16/BF16, got {:?}",
7274 act_dtype,
7275 );
7276 assert_eq!(
7277 qweight.dtype(),
7278 DType::U32,
7279 "awq_matmul: qweight must be U32 (eight 4-bit codes per word), got {:?}",
7280 qweight.dtype(),
7281 );
7282 assert_eq!(
7283 qzeros.dtype(),
7284 DType::U32,
7285 "awq_matmul: qzeros must be U32 (eight 4-bit codes per word), got {:?}",
7286 qzeros.dtype(),
7287 );
7288 assert_eq!(
7289 scales.dtype(),
7290 DType::F32,
7291 "awq_matmul: scales must be F32, got {:?}",
7292 scales.dtype(),
7293 );
7294 let a_dims = self.shape();
7295 let a_dims = a_dims.dims();
7296 let w_dims = qweight.shape();
7297 let w_dims = w_dims.dims();
7298 let z_dims = qzeros.shape();
7299 let z_dims = z_dims.dims();
7300 let s_dims = scales.shape();
7301 let s_dims = s_dims.dims();
7302 assert!(
7303 a_dims.len() >= 2,
7304 "awq_matmul: activations must be rank ≥ 2, got {a_dims:?}",
7305 );
7306 assert_eq!(
7307 w_dims.len(),
7308 2,
7309 "awq_matmul: qweight must be rank 2 [N, K/8], got {w_dims:?}",
7310 );
7311 assert_eq!(
7312 z_dims.len(),
7313 2,
7314 "awq_matmul: qzeros must be rank 2 [K/group_size, N/8], got {z_dims:?}",
7315 );
7316 assert_eq!(
7317 s_dims.len(),
7318 2,
7319 "awq_matmul: scales must be rank 2 [K/group_size, N], got {s_dims:?}",
7320 );
7321 let _m = a_dims[a_dims.len() - 2];
7322 let k = a_dims[a_dims.len() - 1];
7323 let n = w_dims[0];
7324 assert!(
7325 k.is_multiple_of(8),
7326 "awq_matmul: k={k} must be a multiple of 8 (qweight packs 8 codes per word along k)",
7327 );
7328 assert!(
7329 n.is_multiple_of(8),
7330 "awq_matmul: n={n} must be a multiple of 8 (qzeros packs 8 codes per word along n)",
7331 );
7332 assert!(
7333 group_size > 0 && k.is_multiple_of(group_size),
7334 "awq_matmul: k={k} must be a positive multiple of group_size={group_size}",
7335 );
7336 assert_eq!(
7337 w_dims[1],
7338 k / 8,
7339 "awq_matmul: qweight second dim {} must equal k/8 = {}",
7340 w_dims[1],
7341 k / 8,
7342 );
7343 let n_groups = k / group_size;
7344 assert_eq!(
7345 z_dims,
7346 &[n_groups, n / 8][..],
7347 "awq_matmul: qzeros {z_dims:?} must be [k/group_size={n_groups}, n/8={}]",
7348 n / 8,
7349 );
7350 assert_eq!(
7351 s_dims,
7352 &[n_groups, n][..],
7353 "awq_matmul: scales {s_dims:?} must be [k/group_size={n_groups}, n={n}]",
7354 );
7355 let mut out_dims: Vec<usize> = a_dims[..a_dims.len() - 1].to_vec();
7356 out_dims.push(n);
7357 let id = self.graph.write().unwrap().push(Node {
7358 op: Op::Fused(
7359 crate::registry::FusedOps::AWQ_MATMUL,
7360 crate::registry::FusedOpParams::AwqMatmul {
7361 group_size,
7362 split_k_iters,
7363 },
7364 ),
7365 inputs: vec![self.id, qweight.id, qzeros.id, scales.id],
7366 shape: Shape::from_dims(&out_dims),
7367 dtype: act_dtype,
7368 });
7369 Self {
7370 graph: self.graph.clone(),
7371 id,
7372 }
7373 }
7374
7375 /// Append an `SsdChunkScan` node — Mamba-2's State-Space
7376 /// Duality chunked scan (forward). Five inputs:
7377 /// - `self` (x): `[batch, seqlen, heads, head_dim]` F32
7378 /// - `dt`: `[batch, seqlen, heads]` F32
7379 /// - `a`: `[heads]` F32 (per-head scalar log A)
7380 /// - `b`: `[batch, seqlen, heads, state_dim]` F32
7381 /// - `c`: `[batch, seqlen, heads, state_dim]` F32
7382 ///
7383 /// Output: `y: [batch, seqlen, heads, head_dim]` F32 (same as x).
7384 ///
7385 /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
7386 /// It controls GPU parallelism granularity but the mathematical
7387 /// result is identical to a sequential scan; the CPU kernel runs
7388 /// sequential regardless. Validation: `chunk_size > 0` and
7389 /// `seqlen % chunk_size == 0`.
7390 ///
7391 /// Emits `Op::Fused(FusedOps::SSD_CHUNK_SCAN,
7392 /// FusedOpParams::SsdChunkScan { chunk_size })`. No primitive
7393 /// decomposition; backends without a native kernel fall through
7394 /// to the executor's cpu_fallback path.
7395 /// Internal: build the bundled SsdChunkScan producer node and
7396 /// return its NodeId. Callers project per-slot via
7397 /// [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7398 fn ssd_chunk_scan_producer(
7399 &self,
7400 dt: &NodeHandle,
7401 a: &NodeHandle,
7402 b: &NodeHandle,
7403 c: &NodeHandle,
7404 chunk_size: usize,
7405 ) -> NodeHandle {
7406 assert!(
7407 Arc::ptr_eq(&self.graph, &dt.graph)
7408 && Arc::ptr_eq(&self.graph, &a.graph)
7409 && Arc::ptr_eq(&self.graph, &b.graph)
7410 && Arc::ptr_eq(&self.graph, &c.graph),
7411 "ssd_chunk_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7412 );
7413 let dtype = self.dtype();
7414 assert!(
7415 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7416 "ssd_chunk_scan: x must be F32/F64/BF16/F16, got {dtype:?}",
7417 );
7418 for (name, t) in [("dt", dt), ("a", a), ("b", b), ("c", c)] {
7419 assert_eq!(
7420 t.dtype(),
7421 dtype,
7422 "ssd_chunk_scan: {name} dtype {:?} must match x dtype {dtype:?}",
7423 t.dtype(),
7424 );
7425 }
7426 let x_dims = self.shape();
7427 let x_dims = x_dims.dims();
7428 let dt_dims = dt.shape();
7429 let dt_dims = dt_dims.dims();
7430 let a_dims = a.shape();
7431 let a_dims = a_dims.dims();
7432 let b_dims = b.shape();
7433 let b_dims = b_dims.dims();
7434 let c_dims = c.shape();
7435 let c_dims = c_dims.dims();
7436 assert_eq!(
7437 x_dims.len(),
7438 4,
7439 "ssd_chunk_scan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
7440 );
7441 let batch = x_dims[0];
7442 let seqlen = x_dims[1];
7443 let heads = x_dims[2];
7444 let head_dim = x_dims[3];
7445 assert_eq!(
7446 dt_dims,
7447 &[batch, seqlen, heads][..],
7448 "ssd_chunk_scan: dt {dt_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}]",
7449 );
7450 assert_eq!(
7451 a_dims,
7452 &[heads][..],
7453 "ssd_chunk_scan: a {a_dims:?} must be [heads={heads}]",
7454 );
7455 assert_eq!(
7456 b_dims.len(),
7457 4,
7458 "ssd_chunk_scan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
7459 );
7460 let state_dim = b_dims[3];
7461 assert_eq!(
7462 b_dims,
7463 &[batch, seqlen, heads, state_dim][..],
7464 "ssd_chunk_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, heads={heads}, state_dim={state_dim}]",
7465 );
7466 assert_eq!(
7467 c_dims,
7468 &[batch, seqlen, heads, state_dim][..],
7469 "ssd_chunk_scan: c {c_dims:?} must match b shape",
7470 );
7471 let params = crate::registry::FusedOpParams::SsdChunkScan { chunk_size };
7472 let input_shapes = [
7473 Shape::from_dims(x_dims),
7474 Shape::from_dims(dt_dims),
7475 Shape::from_dims(a_dims),
7476 Shape::from_dims(b_dims),
7477 Shape::from_dims(c_dims),
7478 ];
7479 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7480 let entry = crate::registry::default_registry()
7481 .entry(crate::registry::FusedOps::SSD_CHUNK_SCAN)
7482 .expect("SSD_CHUNK_SCAN registered");
7483 let specs =
7484 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7485 let (_total_bytes, views) =
7486 fuel_ir::storage::compose_bundle(&specs).expect("SsdChunkScan compose_bundle");
7487 let mut g = self.graph.write().unwrap();
7488 let id = g.push(Node {
7489 op: Op::Fused(crate::registry::FusedOps::SSD_CHUNK_SCAN, params),
7490 inputs: vec![self.id, dt.id, a.id, b.id, c.id],
7491 shape: Shape::from_dims(&[batch, seqlen, heads, head_dim]),
7492 dtype,
7493 });
7494 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7495 .expect("SsdChunkScan set_output_views");
7496 drop(g);
7497 Self {
7498 graph: self.graph.clone(),
7499 id,
7500 }
7501 }
7502
7503 /// Single-output SsdChunkScan: returns the `y` slot of the
7504 /// bundled producer (View(0)). See
7505 /// [`Self::ssd_chunk_scan_bundled`] for the multi-output variant.
7506 ///
7507 /// # Panics
7508 ///
7509 /// Panics if any operand belongs to a different [`Graph`] than the one this
7510 /// builder is building into. Operand identity is graph-scoped and checked by
7511 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7512 /// deliberate and replaces the hang a cross-graph handle used to produce.
7513 /// Build every operand from one graph, or use a `Result`-returning entry
7514 /// point where one exists.
7515 pub fn ssd_chunk_scan(
7516 &self,
7517 dt: &NodeHandle,
7518 a: &NodeHandle,
7519 b: &NodeHandle,
7520 c: &NodeHandle,
7521 chunk_size: usize,
7522 ) -> NodeHandle {
7523 self.assert_same_graph(dt, "ssd_chunk_scan", "dt");
7524 self.assert_same_graph(a, "ssd_chunk_scan", "a");
7525 self.assert_same_graph(b, "ssd_chunk_scan", "b");
7526 self.assert_same_graph(c, "ssd_chunk_scan", "c");
7527 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7528 producer
7529 .view(0)
7530 .expect("SsdChunkScan view(0) must succeed (just registered slots)")
7531 }
7532
7533 /// Append a `SelectiveScan` node — Mamba-1's selective
7534 /// state-space scan (forward). Five inputs:
7535 /// - `self` (u): `[batch, seqlen, dim]` F32
7536 /// - `delta`: `[batch, seqlen, dim]` F32
7537 /// - `a`: `[dim, dstate]` F32
7538 /// - `b`: `[batch, seqlen, dstate]` F32
7539 /// - `c`: `[batch, seqlen, dstate]` F32
7540 ///
7541 /// Output: `y: [batch, seqlen, dim]` F32.
7542 ///
7543 /// `delta_softplus` toggles the softplus(delta) activation before
7544 /// use (matches baracuda's `selective_scan_*_run` flag). The v1
7545 /// op surface skips the optional `d_skip`, `z`, `delta_bias`
7546 /// inputs and the `last_state` second output — see
7547 /// `fuel-graph/src/registry/selective_scan.rs` for the rationale.
7548 ///
7549 /// Emits `Op::Fused(FusedOps::SELECTIVE_SCAN,
7550 /// FusedOpParams::SelectiveScan { delta_softplus })`. No
7551 /// primitive decomposition exists (the scan is a sequential
7552 /// recurrence); backends without a native kernel fall through to
7553 /// the executor's cpu_fallback path.
7554 /// Internal: build the bundled SelectiveScan producer node and
7555 /// return its NodeId (wrapped in a `NodeHandle`). Callers project
7556 /// per-slot via [`NodeHandle::view`] / [`NodeHandle::view_owned`].
7557 fn selective_scan_producer(
7558 &self,
7559 delta: &NodeHandle,
7560 a: &NodeHandle,
7561 b: &NodeHandle,
7562 c: &NodeHandle,
7563 delta_softplus: bool,
7564 ) -> NodeHandle {
7565 assert!(
7566 Arc::ptr_eq(&self.graph, &delta.graph)
7567 && Arc::ptr_eq(&self.graph, &a.graph)
7568 && Arc::ptr_eq(&self.graph, &b.graph)
7569 && Arc::ptr_eq(&self.graph, &c.graph),
7570 "selective_scan: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7571 );
7572 let dtype = self.dtype();
7573 assert!(
7574 matches!(dtype, DType::F32 | DType::F64 | DType::BF16 | DType::F16),
7575 "selective_scan: u must be F32/F64/BF16/F16, got {dtype:?}",
7576 );
7577 for (name, t) in [("delta", delta), ("a", a), ("b", b), ("c", c)] {
7578 assert_eq!(
7579 t.dtype(),
7580 dtype,
7581 "selective_scan: {name} dtype {:?} must match u dtype {dtype:?}",
7582 t.dtype(),
7583 );
7584 }
7585 let u_dims = self.shape();
7586 let u_dims = u_dims.dims();
7587 let delta_dims = delta.shape();
7588 let delta_dims = delta_dims.dims();
7589 let a_dims = a.shape();
7590 let a_dims = a_dims.dims();
7591 let b_dims = b.shape();
7592 let b_dims = b_dims.dims();
7593 let c_dims = c.shape();
7594 let c_dims = c_dims.dims();
7595 assert_eq!(
7596 u_dims.len(),
7597 3,
7598 "selective_scan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
7599 );
7600 assert_eq!(
7601 delta_dims, u_dims,
7602 "selective_scan: delta {delta_dims:?} must match u {u_dims:?}",
7603 );
7604 assert_eq!(
7605 a_dims.len(),
7606 2,
7607 "selective_scan: a must be rank 2 [dim, dstate], got {a_dims:?}",
7608 );
7609 let batch = u_dims[0];
7610 let seqlen = u_dims[1];
7611 let dim = u_dims[2];
7612 let dstate = a_dims[1];
7613 assert_eq!(
7614 a_dims[0], dim,
7615 "selective_scan: a's first dim {} must equal dim {dim}",
7616 a_dims[0],
7617 );
7618 assert_eq!(
7619 b_dims,
7620 &[batch, seqlen, dstate][..],
7621 "selective_scan: b {b_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7622 );
7623 assert_eq!(
7624 c_dims,
7625 &[batch, seqlen, dstate][..],
7626 "selective_scan: c {c_dims:?} must be [batch={batch}, seqlen={seqlen}, dstate={dstate}]",
7627 );
7628 let params = crate::registry::FusedOpParams::SelectiveScan { delta_softplus };
7629 let input_shapes = [
7630 Shape::from_dims(u_dims),
7631 Shape::from_dims(delta_dims),
7632 Shape::from_dims(a_dims),
7633 Shape::from_dims(b_dims),
7634 Shape::from_dims(c_dims),
7635 ];
7636 let input_dtypes = [dtype, dtype, dtype, dtype, dtype];
7637 let entry = crate::registry::default_registry()
7638 .entry(crate::registry::FusedOps::SELECTIVE_SCAN)
7639 .expect("SELECTIVE_SCAN registered");
7640 let specs =
7641 (entry.output_views.expect("multi-output"))(&input_shapes, &input_dtypes, ¶ms);
7642 let (_total_bytes, views) =
7643 fuel_ir::storage::compose_bundle(&specs).expect("SelectiveScan compose_bundle");
7644 let mut g = self.graph.write().unwrap();
7645 let id = g.push(Node {
7646 op: Op::Fused(crate::registry::FusedOps::SELECTIVE_SCAN, params),
7647 inputs: vec![self.id, delta.id, a.id, b.id, c.id],
7648 shape: Shape::from_dims(&[batch, seqlen, dim]),
7649 dtype,
7650 });
7651 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7652 .expect("SelectiveScan set_output_views");
7653 drop(g);
7654 Self {
7655 graph: self.graph.clone(),
7656 id,
7657 }
7658 }
7659
7660 /// Single-output SelectiveScan: returns the `y` slot of the
7661 /// bundled producer, with the View(0) projection emitted so
7662 /// callers can downstream-realize / copy / etc. transparently.
7663 /// See [`Self::selective_scan_bundled`] for the multi-output
7664 /// variant that also exposes `last_state` for autoregressive
7665 /// resumption.
7666 ///
7667 /// # Panics
7668 ///
7669 /// Panics if any operand belongs to a different [`Graph`] than the one this
7670 /// builder is building into. Operand identity is graph-scoped and checked by
7671 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7672 /// deliberate and replaces the hang a cross-graph handle used to produce.
7673 /// Build every operand from one graph, or use a `Result`-returning entry
7674 /// point where one exists.
7675 pub fn selective_scan(
7676 &self,
7677 delta: &NodeHandle,
7678 a: &NodeHandle,
7679 b: &NodeHandle,
7680 c: &NodeHandle,
7681 delta_softplus: bool,
7682 ) -> NodeHandle {
7683 self.assert_same_graph(delta, "selective_scan", "delta");
7684 self.assert_same_graph(a, "selective_scan", "a");
7685 self.assert_same_graph(b, "selective_scan", "b");
7686 self.assert_same_graph(c, "selective_scan", "c");
7687 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7688 producer
7689 .view(0)
7690 .expect("SelectiveScan view(0) must succeed (just registered slots)")
7691 }
7692
7693 /// Multi-output variant of [`Self::selective_scan`]. Returns
7694 /// `(y, last_state)` — both Op::View tensors projected from the
7695 /// shared bundled producer. `y` matches the existing
7696 /// single-output `selective_scan` shape; `last_state` is the
7697 /// final hidden state `[batch, dim, dstate]` for autoregressive
7698 /// resumption.
7699 pub fn selective_scan_bundled(
7700 &self,
7701 delta: &NodeHandle,
7702 a: &NodeHandle,
7703 b: &NodeHandle,
7704 c: &NodeHandle,
7705 delta_softplus: bool,
7706 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7707 self.require_same_graph(delta, "selective_scan_bundled", "delta")?;
7708 self.require_same_graph(a, "selective_scan_bundled", "a")?;
7709 self.require_same_graph(b, "selective_scan_bundled", "b")?;
7710 self.require_same_graph(c, "selective_scan_bundled", "c")?;
7711 let producer = self.selective_scan_producer(delta, a, b, c, delta_softplus);
7712 let y = producer.view(0)?;
7713 let last_state = producer.view(1)?;
7714 Ok((y, last_state))
7715 }
7716
7717 /// Multi-output variant of [`Self::ssd_chunk_scan`]. Returns
7718 /// `(y, last_state)`.
7719 pub fn ssd_chunk_scan_bundled(
7720 &self,
7721 dt: &NodeHandle,
7722 a: &NodeHandle,
7723 b: &NodeHandle,
7724 c: &NodeHandle,
7725 chunk_size: usize,
7726 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7727 self.require_same_graph(dt, "ssd_chunk_scan_bundled", "dt")?;
7728 self.require_same_graph(a, "ssd_chunk_scan_bundled", "a")?;
7729 self.require_same_graph(b, "ssd_chunk_scan_bundled", "b")?;
7730 self.require_same_graph(c, "ssd_chunk_scan_bundled", "c")?;
7731 let producer = self.ssd_chunk_scan_producer(dt, a, b, c, chunk_size);
7732 let y = producer.view(0)?;
7733 let last_state = producer.view(1)?;
7734 Ok((y, last_state))
7735 }
7736
7737 /// Append an [`Op::NonZeroIndices`] producer node — the keystone
7738 /// primitive for **data-dependent dynamic shapes**. Returns the
7739 /// bundled producer `NodeHandle` (a `[capacity]` U32 tensor); callers
7740 /// usually want [`Self::nonzero_indices_bundled`] to also get the
7741 /// runtime count slot.
7742 ///
7743 /// `capacity = self.elem_count()` is the static worst-case bound
7744 /// (every element nonzero). `count_sym` is the [`SymId`] the executor
7745 /// binds to the realized nonzero count in the per-pass `SymEnv`; the
7746 /// caller allocates it from their `SymGen` and threads it into any
7747 /// downstream op that consumes the count as a dynamic extent /
7748 /// `DynScalar::Sym` (the KV-cache `cached_len` pattern, generalized to
7749 /// a data-determined count).
7750 pub fn nonzero_indices_producer(&self, count_sym: SymId) -> NodeHandle {
7751 let capacity = self.shape().elem_count();
7752 let indices_shape = Shape::from_dims(&[capacity]);
7753 let count_shape = Shape::from_dims(&[1]);
7754 let specs = vec![
7755 fuel_ir::storage::OutputViewSpec {
7756 dtype: DType::U32,
7757 shape: indices_shape.clone(),
7758 layout: Layout::contiguous(indices_shape.clone()),
7759 name: Some("indices"),
7760 },
7761 fuel_ir::storage::OutputViewSpec {
7762 dtype: DType::U32,
7763 shape: count_shape.clone(),
7764 layout: Layout::contiguous(count_shape),
7765 name: Some("count"),
7766 },
7767 ];
7768 let (_total_bytes, views) =
7769 fuel_ir::storage::compose_bundle(&specs).expect("NonZeroIndices compose_bundle");
7770 let mut g = self.graph.write().unwrap();
7771 let id = g.push(Node {
7772 op: Op::NonZeroIndices { count_sym },
7773 inputs: vec![self.id],
7774 shape: indices_shape,
7775 dtype: DType::U32,
7776 });
7777 g.set_output_views(id, Arc::from(views.into_boxed_slice()))
7778 .expect("NonZeroIndices set_output_views");
7779 drop(g);
7780 Self {
7781 graph: self.graph.clone(),
7782 id,
7783 }
7784 }
7785
7786 /// Multi-output [`Op::NonZeroIndices`]: returns `(indices, count)` —
7787 /// both `Op::View` projections of the shared bundled producer.
7788 /// `indices` is `[capacity]` U32 (first `count` entries valid, in
7789 /// ascending flat order); `count` is `[1]` U32, the runtime nonzero
7790 /// count. The executor also publishes `count`'s value into the
7791 /// per-pass `SymEnv` under the producer's `count_sym`.
7792 pub fn nonzero_indices_bundled(
7793 &self,
7794 count_sym: SymId,
7795 ) -> std::result::Result<(NodeHandle, NodeHandle), fuel_ir::Error> {
7796 let producer = self.nonzero_indices_producer(count_sym);
7797 let indices = producer.view(0)?;
7798 let count = producer.view(1)?;
7799 Ok((indices, count))
7800 }
7801
7802 /// Append a `FusedSoftmaxCrossEntropy` node. Two inputs:
7803 /// - `self` (logits): `[..., V]` F32 / F64 / BF16 / F16
7804 /// - `targets`: `[...]` I64 (class indices; matches PyTorch /
7805 /// baracuda convention)
7806 ///
7807 /// Output dtype is always F32 (the FSCE declared dtype — losses
7808 /// accumulate in F64 and narrow to F32, matching PyTorch and the
7809 /// baracuda kernel) regardless of the logits dtype. Output shape
7810 /// depends on `reduction`:
7811 /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
7812 /// - `Reduction::None` → same as `targets.shape`
7813 ///
7814 /// `ignore_index` rows are dropped from the loss accumulator and
7815 /// the Mean denominator. The conventional sentinel is `-100`.
7816 ///
7817 /// Emits `Op::Fused(FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7818 /// FusedOpParams::FusedSoftmaxCrossEntropy { reduction, ignore_index })`.
7819 /// See `fuel-graph/src/registry/fused_softmax_cross_entropy.rs` for
7820 /// the registry entry and decompose chain.
7821 ///
7822 /// # Panics
7823 ///
7824 /// Panics if any operand belongs to a different [`Graph`] than the one this
7825 /// builder is building into. Operand identity is graph-scoped and checked by
7826 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7827 /// deliberate and replaces the hang a cross-graph handle used to produce.
7828 /// Build every operand from one graph, or use a `Result`-returning entry
7829 /// point where one exists.
7830 pub fn fused_softmax_cross_entropy(
7831 &self,
7832 targets: &NodeHandle,
7833 reduction: crate::registry::Reduction,
7834 ignore_index: i64,
7835 ) -> NodeHandle {
7836 assert!(
7837 Arc::ptr_eq(&self.graph, &targets.graph),
7838 "fused_softmax_cross_entropy: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
7839 );
7840 assert!(
7841 matches!(
7842 self.dtype(),
7843 DType::F32 | DType::F64 | DType::BF16 | DType::F16,
7844 ),
7845 "fused_softmax_cross_entropy: logits must be F32/F64/BF16/F16, got {:?}",
7846 self.dtype(),
7847 );
7848 assert_eq!(
7849 targets.dtype(),
7850 DType::I64,
7851 "fused_softmax_cross_entropy: targets must be I64, got {:?}",
7852 targets.dtype(),
7853 );
7854 let logits_dims = self.shape();
7855 let logits_dims = logits_dims.dims();
7856 assert!(
7857 !logits_dims.is_empty(),
7858 "fused_softmax_cross_entropy: logits must have rank ≥ 1",
7859 );
7860 let target_dims = targets.shape();
7861 let target_dims = target_dims.dims();
7862 assert_eq!(
7863 target_dims,
7864 &logits_dims[..logits_dims.len() - 1],
7865 "fused_softmax_cross_entropy: targets shape {target_dims:?} must equal \
7866 logits shape {logits_dims:?} minus the last dim",
7867 );
7868 let out_shape = match reduction {
7869 crate::registry::Reduction::Mean | crate::registry::Reduction::Sum => {
7870 Shape::from_dims(&[])
7871 }
7872 crate::registry::Reduction::None => Shape::from_dims(target_dims),
7873 };
7874 let id = self.graph.write().unwrap().push(Node {
7875 op: Op::Fused(
7876 crate::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
7877 crate::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
7878 reduction,
7879 ignore_index,
7880 },
7881 ),
7882 inputs: vec![self.id, targets.id],
7883 shape: out_shape,
7884 dtype: DType::F32,
7885 });
7886 Self {
7887 graph: self.graph.clone(),
7888 id,
7889 }
7890 }
7891
7892 /// Append a `LayerNormLastDim` node with the given epsilon. Shape is
7893 /// preserved.
7894 ///
7895 /// Phase 7.6 step 4 (continued): emits
7896 /// `Op::Fused(FusedOps::LAYER_NORM_LAST_DIM, FusedOpParams::LayerNormLastDim { eps })`
7897 /// through the registry-extended arm. The legacy
7898 /// `Op::LayerNormLastDim { eps }` variant remains in the enum
7899 /// during migration; step 5 drops it once nothing emits it.
7900 pub fn layer_norm_last_dim(&self, eps: f64) -> NodeHandle {
7901 let dims = self.shape();
7902 let d = dims.dims();
7903 assert!(
7904 !d.is_empty() && *d.last().unwrap() > 0,
7905 "layer_norm_last_dim: input must have a non-zero last dim, got {d:?}",
7906 );
7907 self.unary_op(Op::Fused(
7908 crate::registry::FusedOps::LAYER_NORM_LAST_DIM,
7909 crate::registry::FusedOpParams::LayerNormLastDim { eps },
7910 ))
7911 }
7912
7913 /// Apply rotary position embeddings (RoPE) to `self`. The input is
7914 /// expected to have shape `[..., seq, d]` where `seq` is the
7915 /// sequence length and `d` is the per-head feature dim (which must
7916 /// be even). `base` is the frequency base — 10000.0 for LLaMA.
7917 /// `start_pos` lets callers apply RoPE at a non-zero offset, which
7918 /// is what KV-cached inference does when the query for position
7919 /// `n + k` is processed against a cache that already holds
7920 /// positions `0..n+k`.
7921 ///
7922 /// Uses the half-split layout (the one LLaMA and HuggingFace use):
7923 /// pair feature `i` with feature `i + d/2`. Under that layout the
7924 /// rotation reduces to the identity `x' = x·cos + rotate_half(x)·sin`
7925 /// where `rotate_half(x)` concatenates `[-x[d/2:], x[:d/2]]` along
7926 /// the last dim.
7927 ///
7928 /// Implemented as a composition of existing graph primitives —
7929 /// `Slice`, `Neg`, `Concat`, `Reshape`, `BroadcastTo`, `Mul`, `Add`
7930 /// — plus two precomputed `Const` tensors for the cos/sin frequency
7931 /// tables. Every primitive already has a working backward rule, so
7932 /// gradients flow through RoPE without any new backward machinery.
7933 ///
7934 /// Only `f32` is supported today. Extending to other float dtypes
7935 /// is mechanical: build the frequency tables in the target dtype.
7936 pub fn rope(&self, base: f64, start_pos: usize) -> NodeHandle {
7937 let (seq, d) = {
7938 let dims = self.shape();
7939 let v = dims.dims();
7940 let rank = v.len();
7941 assert!(rank >= 2, "rope: input must have rank ≥ 2");
7942 (v[rank - 2], v[rank - 1])
7943 };
7944 let (cos, sin) = build_rope_tables(base, start_pos, seq, d);
7945 // Phase 7.5 G2: const_*_like derives the device from self's
7946 // graph internally — RoPE tables go on the same device as self.
7947 // ⚠️ GAP-003 category 2, in production: the proof EXISTS but is NOT
7948 // LOCAL -- `build_rope_tables` owns the length guarantee and its
7949 // signature `-> (Vec<f32>, Vec<f32>)` does not carry it. So the message
7950 // claims NO proof; it names where the guarantee lives. `rope` returns
7951 // `NodeHandle` and already asserts on rank, so giving it an error
7952 // channel is a signature change -- a different obligation. See #157.
7953 let cos_t = self
7954 .const_f32_like(cos, Shape::from_dims(&[seq, d]))
7955 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7956 let sin_t = self
7957 .const_f32_like(sin, Shape::from_dims(&[seq, d]))
7958 .expect("rope: build_rope_tables must return seq*d elements for [seq, d]");
7959 self.rope_with_tables(&cos_t, &sin_t)
7960 }
7961
7962 /// Apply RoPE using caller-supplied `cos` and `sin` tables. Each
7963 /// table has shape `[seq, head_dim]` and matches the layout
7964 /// [`build_rope_tables`] produces. This is the hot-path entry
7965 /// point: in a transformer forward pass every attention layer
7966 /// applies RoPE to Q and K with the *same* `(start_pos, seq,
7967 /// head_dim)`, so the caller can build the tables once and share
7968 /// the const nodes across all layers rather than re-duplicating
7969 /// them inside each `.rope()` call. The classic [`Self::rope`] entry
7970 /// point funnels through this after building the tables itself.
7971 ///
7972 /// # Panics
7973 ///
7974 /// Panics if any operand belongs to a different [`Graph`] than the one this
7975 /// builder is building into. Operand identity is graph-scoped and checked by
7976 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
7977 /// deliberate and replaces the hang a cross-graph handle used to produce.
7978 /// Build every operand from one graph, or use a `Result`-returning entry
7979 /// point where one exists.
7980 pub fn rope_with_tables(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
7981 self.assert_same_graph(cos, "rope_with_tables", "cos");
7982 self.assert_same_graph(sin, "rope_with_tables", "sin");
7983 assert_eq!(
7984 self.dtype(),
7985 DType::F32,
7986 "rope: only f32 is supported today (cast explicitly for other dtypes)",
7987 );
7988 let in_shape = self.shape();
7989 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
7990 let rank = dims_vec.len();
7991 assert!(
7992 rank >= 2,
7993 "rope: input must have rank ≥ 2, got {dims_vec:?}"
7994 );
7995 let seq = dims_vec[rank - 2];
7996 let d = dims_vec[rank - 1];
7997 assert!(d.is_multiple_of(2), "rope: feature dim {d} must be even",);
7998 let cos_shape = cos.shape();
7999 let sin_shape = sin.shape();
8000 assert_eq!(
8001 cos_shape.dims(),
8002 &[seq, d],
8003 "rope_with_tables: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
8004 cos_shape.dims(),
8005 );
8006 assert_eq!(
8007 sin_shape.dims(),
8008 &[seq, d],
8009 "rope_with_tables: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
8010 sin_shape.dims(),
8011 );
8012 let _ = rank;
8013 // Emit a single fused Rope node. The decomposed version
8014 // (slice+neg+concat+broadcast+mul+add) produces ~72 dispatches
8015 // on GPU backends because concat-along-last-dim has a per-row
8016 // host loop. Fused path dispatches once.
8017 //
8018 // Phase 7.6 step 4 (continued): emits
8019 // `Op::Fused(FusedOps::ROPE, FusedOpParams::Rope)` through the
8020 // registry-extended arm. The legacy `Op::Rope` variant remains
8021 // in the enum during migration; step 5 drops it once nothing
8022 // emits it.
8023 let out_shape = in_shape.clone();
8024 let dtype = self.dtype();
8025 let id = self.graph.write().unwrap().push(Node {
8026 op: Op::Fused(
8027 crate::registry::FusedOps::ROPE,
8028 crate::registry::FusedOpParams::Rope,
8029 ),
8030 inputs: vec![self.id, cos.id, sin.id],
8031 shape: out_shape,
8032 dtype,
8033 });
8034 Self {
8035 graph: self.graph.clone(),
8036 id,
8037 }
8038 }
8039
8040 /// The pre-fused decomposition of `rope_with_tables`. Retained so
8041 /// backends without a native `Op::Rope` kernel can synthesize from
8042 /// primitives, and so correctness tests can cross-check the fused
8043 /// path against the primitive path.
8044 ///
8045 /// # Panics
8046 ///
8047 /// Panics if any operand belongs to a different [`Graph`] than the one this
8048 /// builder is building into. Operand identity is graph-scoped and checked by
8049 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8050 /// deliberate and replaces the hang a cross-graph handle used to produce.
8051 /// Build every operand from one graph, or use a `Result`-returning entry
8052 /// point where one exists.
8053 #[doc(hidden)]
8054 pub fn rope_with_tables_decomposed(&self, cos: &NodeHandle, sin: &NodeHandle) -> NodeHandle {
8055 self.assert_same_graph(cos, "rope_with_tables_decomposed", "cos");
8056 self.assert_same_graph(sin, "rope_with_tables_decomposed", "sin");
8057 let in_shape = self.shape();
8058 let dims_vec: Vec<usize> = in_shape.dims().to_vec();
8059 let rank = dims_vec.len();
8060 let seq = dims_vec[rank - 2];
8061 let d = dims_vec[rank - 1];
8062 let half = d / 2;
8063
8064 let mut broadcast_shape: Vec<usize> = vec![1_usize; rank];
8065 broadcast_shape[rank - 2] = seq;
8066 broadcast_shape[rank - 1] = d;
8067 let cos_reshaped = cos.reshape(Shape::from_dims(&broadcast_shape));
8068 let sin_reshaped = sin.reshape(Shape::from_dims(&broadcast_shape));
8069 let cos_bcast = cos_reshaped.broadcast_to(in_shape.clone());
8070 let sin_bcast = sin_reshaped.broadcast_to(in_shape);
8071
8072 let first_half = self.slice(rank - 1, 0, half);
8073 let second_half = self.slice(rank - 1, half, half);
8074 let neg_second = second_half.neg();
8075 let rotated_half = neg_second.concat(&first_half, rank - 1);
8076
8077 let left = self.mul(&cos_bcast);
8078 let right = rotated_half.mul(&sin_bcast);
8079 left.add(&right)
8080 }
8081
8082 /// Root-Mean-Square Normalization along the last dim, without
8083 /// affine parameters. `y = x / sqrt(mean(x², last) + eps)`.
8084 ///
8085 /// This is the normalization layer used by LLaMA-family models.
8086 /// Unlike LayerNorm, RmsNorm does not subtract the mean — it only
8087 /// divides by the root-mean-square, which is both cheaper and
8088 /// empirically just as effective in transformer blocks.
8089 ///
8090 /// Emits a fused RmsNormLastDim node. Backends that have a native
8091 /// implementation dispatch it as one kernel; ones that don't get a
8092 /// CPU fallback via the reference implementation.
8093 ///
8094 /// Phase 7.6 step 4 (continued): emits
8095 /// `Op::Fused(FusedOps::RMS_NORM_LAST_DIM, FusedOpParams::RmsNormLastDim { eps })`
8096 /// through the registry-extended arm. The legacy
8097 /// `Op::RmsNormLastDim { eps }` variant remains in the enum during
8098 /// migration; step 5 drops it once nothing emits it.
8099 ///
8100 /// Use [`rms_norm_last_dim_decomposed`](Self::rms_norm_last_dim_decomposed)
8101 /// instead if you need to differentiate through this op —
8102 /// backward through the fused op is not yet implemented.
8103 pub fn rms_norm_last_dim(&self, eps: f64) -> NodeHandle {
8104 let x_dims_vec: Vec<usize> = self.shape().dims().to_vec();
8105 assert!(
8106 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8107 "rms_norm_last_dim: input must have non-zero last dim, got {x_dims_vec:?}",
8108 );
8109 self.unary_op(Op::Fused(
8110 crate::registry::FusedOps::RMS_NORM_LAST_DIM,
8111 crate::registry::FusedOpParams::RmsNormLastDim { eps },
8112 ))
8113 }
8114
8115 /// Decomposed version — emits the (sqr → mean_dim → reshape →
8116 /// add_scalar → sqrt → broadcast_to → div) primitive chain. Has
8117 /// working backward rules through its primitive subgraph. Use
8118 /// this when you need to differentiate through RMSNorm; use
8119 /// [`rms_norm_last_dim`](Self::rms_norm_last_dim) for inference.
8120 pub fn rms_norm_last_dim_decomposed(&self, eps: f64) -> NodeHandle {
8121 let x_shape = self.shape();
8122 let x_dims_vec: Vec<usize> = x_shape.dims().to_vec();
8123 assert!(
8124 !x_dims_vec.is_empty() && *x_dims_vec.last().unwrap() > 0,
8125 "rms_norm_last_dim_decomposed: input must have non-zero last dim, got {x_dims_vec:?}",
8126 );
8127 let last = x_dims_vec.len() - 1;
8128 let mean_sq = self.sqr().mean_dim(last);
8129 let mut keepdim_dims = x_dims_vec.clone();
8130 keepdim_dims[last] = 1;
8131 let mean_sq_kd = mean_sq.reshape(Shape::from_dims(&keepdim_dims));
8132 let denom = mean_sq_kd.add_scalar(eps).sqrt();
8133 let denom_bcast = denom.broadcast_to(x_shape);
8134 self.div(&denom_bcast)
8135 }
8136
8137 // --- indexing ---
8138
8139 /// Append an `IndexSelect` node that picks slices from `self` along
8140 /// `dim` using a 1-D `u32` index tensor. The output has the same
8141 /// shape as `self` except dimension `dim` is replaced by
8142 /// `indices.shape()[0]`.
8143 ///
8144 /// # Panics
8145 ///
8146 /// Panics if any operand belongs to a different [`Graph`] than the one this
8147 /// builder is building into. Operand identity is graph-scoped and checked by
8148 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8149 /// deliberate and replaces the hang a cross-graph handle used to produce.
8150 /// Build every operand from one graph, or use a `Result`-returning entry
8151 /// point where one exists.
8152 pub fn index_select(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8153 assert!(
8154 Arc::ptr_eq(&self.graph, &indices.graph),
8155 "index_select: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8156 );
8157 assert_eq!(
8158 indices.dtype(),
8159 DType::U32,
8160 "index_select: index tensor must be U32, got {:?}",
8161 indices.dtype(),
8162 );
8163 let idx_dims = indices.shape();
8164 assert_eq!(
8165 idx_dims.dims().len(),
8166 1,
8167 "index_select: index tensor must be rank 1, got {:?}",
8168 idx_dims.dims(),
8169 );
8170 let data_dims = self.shape();
8171 assert!(
8172 dim < data_dims.dims().len(),
8173 "index_select: dim {dim} out of bounds for data shape {:?}",
8174 data_dims.dims(),
8175 );
8176 let op = Op::IndexSelect { dim };
8177 let (shape, dtype) = crate::shape::primitive_shape(
8178 &op,
8179 &[data_dims, idx_dims],
8180 &[self.dtype(), indices.dtype()],
8181 )
8182 .expect("index_select: shapes/dims validated above");
8183 let id = self.graph.write().unwrap().push(Node {
8184 op,
8185 inputs: vec![self.id, indices.id],
8186 shape,
8187 dtype,
8188 });
8189 Self {
8190 graph: self.graph.clone(),
8191 id,
8192 }
8193 }
8194
8195 /// Append a `Gather` node that performs an N-dimensional gather along
8196 /// `dim`. The `indices` tensor must be `U32` with the same rank as
8197 /// `self`. Output shape equals `indices.shape()`.
8198 ///
8199 /// # Panics
8200 ///
8201 /// Panics if any operand belongs to a different [`Graph`] than the one this
8202 /// builder is building into. Operand identity is graph-scoped and checked by
8203 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8204 /// deliberate and replaces the hang a cross-graph handle used to produce.
8205 /// Build every operand from one graph, or use a `Result`-returning entry
8206 /// point where one exists.
8207 pub fn gather(&self, dim: usize, indices: &NodeHandle) -> NodeHandle {
8208 assert!(
8209 Arc::ptr_eq(&self.graph, &indices.graph),
8210 "gather: data and index tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8211 );
8212 assert_eq!(
8213 indices.dtype(),
8214 DType::U32,
8215 "gather: index tensor must be U32, got {:?}",
8216 indices.dtype(),
8217 );
8218 let data_rank = self.shape().dims().len();
8219 let idx_rank = indices.shape().dims().len();
8220 assert_eq!(
8221 data_rank, idx_rank,
8222 "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
8223 );
8224 assert!(
8225 dim < data_rank,
8226 "gather: dim {dim} out of bounds for rank {data_rank}",
8227 );
8228 let op = Op::Gather { dim };
8229 let (shape, dtype) = crate::shape::primitive_shape(
8230 &op,
8231 &[self.shape(), indices.shape()],
8232 &[self.dtype(), indices.dtype()],
8233 )
8234 .expect("gather: shapes/dims validated above");
8235 let id = self.graph.write().unwrap().push(Node {
8236 op,
8237 inputs: vec![self.id, indices.id],
8238 shape,
8239 dtype,
8240 });
8241 Self {
8242 graph: self.graph.clone(),
8243 id,
8244 }
8245 }
8246
8247 /// Append a `Concat` node joining `self` and `other` along `dim`.
8248 ///
8249 /// # Panics
8250 ///
8251 /// Panics if any operand belongs to a different [`Graph`] than the one this
8252 /// builder is building into. Operand identity is graph-scoped and checked by
8253 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8254 /// deliberate and replaces the hang a cross-graph handle used to produce.
8255 /// Build every operand from one graph, or use a `Result`-returning entry
8256 /// point where one exists.
8257 pub fn concat(&self, other: &NodeHandle, dim: usize) -> NodeHandle {
8258 assert!(
8259 Arc::ptr_eq(&self.graph, &other.graph),
8260 "concat: tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8261 );
8262 assert_eq!(
8263 self.dtype(),
8264 other.dtype(),
8265 "concat: dtype mismatch {:?} vs {:?}",
8266 self.dtype(),
8267 other.dtype(),
8268 );
8269 let a = self.shape();
8270 let b = other.shape();
8271 let ad = a.dims();
8272 let bd = b.dims();
8273 assert_eq!(ad.len(), bd.len(), "concat: rank mismatch");
8274 assert!(dim < ad.len(), "concat: dim out of bounds");
8275 for i in 0..ad.len() {
8276 if i != dim {
8277 assert_eq!(
8278 ad[i], bd[i],
8279 "concat: non-dim shapes must match (dim {i}: {} vs {})",
8280 ad[i], bd[i],
8281 );
8282 }
8283 }
8284 let op = Op::Concat { dim };
8285 let (shape, dtype) =
8286 crate::shape::primitive_shape(&op, &[a, b], &[self.dtype(), other.dtype()])
8287 .expect("concat: shapes/dtypes validated above");
8288 let id = self.graph.write().unwrap().push(Node {
8289 op,
8290 inputs: vec![self.id, other.id],
8291 shape,
8292 dtype,
8293 });
8294 Self {
8295 graph: self.graph.clone(),
8296 id,
8297 }
8298 }
8299
8300 /// Append a `Slice` (narrow) node taking elements `[start, start+len)`
8301 /// along `dim`. The output has the same rank; only `dim` shrinks.
8302 pub fn slice(&self, dim: usize, start: usize, len: usize) -> NodeHandle {
8303 let in_shape = self.shape();
8304 let in_dims = in_shape.dims();
8305 assert!(dim < in_dims.len(), "slice: dim out of bounds");
8306 assert!(
8307 start + len <= in_dims[dim],
8308 "slice: [start={start}, len={len}) exceeds dim size {}",
8309 in_dims[dim],
8310 );
8311 let op = Op::Slice { dim, start, len };
8312 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8313 .expect("slice: dim/start/len validated above");
8314 let id = self.graph.write().unwrap().push(Node {
8315 op,
8316 inputs: vec![self.id],
8317 shape,
8318 dtype,
8319 });
8320 Self {
8321 graph: self.graph.clone(),
8322 id,
8323 }
8324 }
8325
8326 /// Append an `AddScalar` node: `y[i] = x[i] + c`. Convenient for
8327 /// avoiding a full-shape const node when you just want to bias a
8328 /// tensor by a constant.
8329 pub fn add_scalar(&self, c: f64) -> NodeHandle {
8330 self.unary_op(Op::AddScalar(c))
8331 }
8332
8333 /// Append a `MulScalar` node: `y[i] = x[i] * c`.
8334 pub fn mul_scalar(&self, c: f64) -> NodeHandle {
8335 self.unary_op(Op::MulScalar(c))
8336 }
8337
8338 /// Append a `PowI` node raising each element to an integer power.
8339 pub fn powi(&self, n: i32) -> NodeHandle {
8340 self.unary_op(Op::PowI(n))
8341 }
8342
8343 /// Append a `Clamp` node restricting each element to `[min, max]`.
8344 pub fn clamp(&self, min: f64, max: f64) -> NodeHandle {
8345 assert!(min <= max, "clamp: min ({min}) must be <= max ({max})",);
8346 self.unary_op(Op::Clamp { min, max })
8347 }
8348
8349 /// Append a `Maximum` node `max(self, other)` element-wise. Matching
8350 /// shapes required.
8351 ///
8352 /// # Panics
8353 ///
8354 /// Panics if any operand belongs to a different [`Graph`] than the one this
8355 /// builder is building into. Operand identity is graph-scoped and checked by
8356 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8357 /// deliberate and replaces the hang a cross-graph handle used to produce.
8358 /// Build every operand from one graph, or use a `Result`-returning entry
8359 /// point where one exists.
8360 pub fn maximum(&self, other: &NodeHandle) -> NodeHandle {
8361 self.binary_op("maximum", Op::Maximum, other, self.shape())
8362 }
8363
8364 /// Append a `Minimum` node `min(self, other)` element-wise.
8365 ///
8366 /// # Panics
8367 ///
8368 /// Panics if any operand belongs to a different [`Graph`] than the one this
8369 /// builder is building into. Operand identity is graph-scoped and checked by
8370 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8371 /// deliberate and replaces the hang a cross-graph handle used to produce.
8372 /// Build every operand from one graph, or use a `Result`-returning entry
8373 /// point where one exists.
8374 pub fn minimum(&self, other: &NodeHandle) -> NodeHandle {
8375 self.binary_op("minimum", Op::Minimum, other, self.shape())
8376 }
8377
8378 /// The IEEE-754 NaN-**suppressing** maximum — the KISS-OPS §6.15-0001
8379 /// `fmax_ieee` op, DISTINCT from [`maximum`](Self::maximum) (which is
8380 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8381 /// the other; if both are NaN, returns NaN; otherwise the larger.
8382 ///
8383 /// Built by RESOLUTION through the spec-pinned §6.13 decomposition
8384 /// (KISS-OPS-6.15-0001), used VERBATIM — Fuel does not substitute `maximum`
8385 /// for it (that substitution is the §6.15 violation). Because the
8386 /// decomposition is spec-authored, its edge behaviour — including ±0 ordering
8387 /// under `cmp_ge` (`cmp_ge(-0.0, +0.0)` is true, so this returns `-0.0` for
8388 /// that pair) — is the SPEC's to define and a KISS conformance vector's to
8389 /// catch. Fuel resolves; it does not re-derive. (GAP-048.)
8390 pub fn fmax_ieee(&self, other: &NodeHandle) -> NodeHandle {
8391 // select(a != a, b, select(b != b, a, select(a >= b, a, b)))
8392 let a = self;
8393 let b = other;
8394 let plain = a.ge(b).where_cond(a, b); // a >= b ? a : b
8395 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8396 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8397 }
8398
8399 /// The IEEE-754 NaN-**suppressing** minimum — the KISS-OPS §6.15-0001
8400 /// `fmin_ieee` op, DISTINCT from [`minimum`](Self::minimum) (which is
8401 /// NaN-**propagating**, torch parity). If exactly one operand is NaN, returns
8402 /// the other; if both are NaN, returns NaN; otherwise the smaller.
8403 ///
8404 /// Built by RESOLUTION through the spec-pinned KISS-OPS §6.13 decomposition
8405 /// (KISS-OPS-6.15-0001), used VERBATIM — the `cmp_le` mirror of
8406 /// [`fmax_ieee`](Self::fmax_ieee)'s `cmp_ge` form. Fuel resolves; it does not
8407 /// substitute `minimum` (that substitution is the §6.15 violation) and does
8408 /// not re-derive: the decomposition is KISS's, so its ±0 edge behaviour is the
8409 /// spec's to define and a KISS conformance vector's to catch. (GAP-048.)
8410 pub fn fmin_ieee(&self, other: &NodeHandle) -> NodeHandle {
8411 // select(a != a, b, select(b != b, a, select(a <= b, a, b)))
8412 let a = self;
8413 let b = other;
8414 let plain = a.le(b).where_cond(a, b); // a <= b ? a : b
8415 let b_not_nan = b.ne(b).where_cond(a, &plain); // b is NaN ? a : plain
8416 a.ne(a).where_cond(b, &b_not_nan) // a is NaN ? b : (above)
8417 }
8418
8419 /// Round toward zero — the KISS-OPS §6.3 `trunc` floor op (GAP-300).
8420 ///
8421 /// ⚠️ Unlike [`fmax_ieee`](Self::fmax_ieee)/[`fmin_ieee`](Self::fmin_ieee),
8422 /// which resolve through KISS's OWN §6.13 decompositions, `trunc` is a §6.3
8423 /// *floor* op: KISS-OPS-6.3-0003 forbids the standard from carrying a
8424 /// reference decomposition for a floor op, so THIS expansion is FUEL's, blessed
8425 /// by no spec clause. It IS now checked by KISS vectors: `ops-rounding.json`
8426 /// (vendored at KISS `0af5d3b6`) carries 18 `f32` `trunc` cells (signed zero, halves
8427 /// and ties, 2^23, max finite, ±inf, subnormals), all of which pass through the lazy
8428 /// `Tensor` (`fuel-tensor/tests/kiss_nan_conformance.rs`); `f64` and NaN inputs are
8429 /// not in that file. Beyond it, correctness is Fuel's liability — see GAP-300, whose born-reds assert
8430 /// on `to_bits()` (a value compare `0.0 == -0.0` passes vacuously).
8431 ///
8432 /// `trunc(q) = if q >= 0 { floor(q) } else { ceil(q) }`. Float dtypes only;
8433 /// integer dtypes are already whole, so `trunc` is identity for them (returned
8434 /// unchanged — never a panic on a non-float operand).
8435 ///
8436 /// REJECTED-FOR-NOW alternative: `copysign(floor(abs(q)), q)` is cleaner (no
8437 /// dtype-matched zero; ±0/NaN/inf fall out of the IEEE primitives). Fuel has no
8438 /// `copysign` op today (absent from `Op` and the builder API), so it is not
8439 /// buildable — adopt it IF `copysign` ever lands.
8440 pub fn trunc(&self) -> NodeHandle {
8441 let q = self;
8442 // A scalar zero of q's dtype, broadcast to q's shape — comparisons require
8443 // matching shapes (no implicit broadcast in `binary_compare_op`).
8444 let zero = match q.dtype() {
8445 DType::F32 => q
8446 .const_f32_like(vec![0.0f32], &[1])
8447 .expect("trunc: a 1-element vec with shape [1]")
8448 .broadcast_to(q.shape()),
8449 DType::F64 => q
8450 .const_f64_like(vec![0.0f64], &[1])
8451 .expect("trunc: a 1-element vec with shape [1]")
8452 .broadcast_to(q.shape()),
8453 DType::BF16 => q
8454 .const_bf16_like(vec![half::bf16::from_f32(0.0)], &[1])
8455 .expect("trunc: a 1-element vec with shape [1]")
8456 .broadcast_to(q.shape()),
8457 DType::F16 => q
8458 .const_f16_like(vec![half::f16::from_f32(0.0)], &[1])
8459 .expect("trunc: a 1-element vec with shape [1]")
8460 .broadcast_to(q.shape()),
8461 // Integer/other dtypes are already whole: trunc is identity.
8462 _ => return q.clone(),
8463 };
8464 // q >= 0 ? floor(q) : ceil(q). Note: at ±0 BOTH branches yield the same
8465 // signed zero (`floor(-0.0) == ceil(-0.0) == -0.0`), so trunc's ±0 result
8466 // is robust to a tie-bias in `ge` — but the born-red still checks the bits.
8467 q.ge(&zero).where_cond(&q.floor(), &q.ceil())
8468 }
8469
8470 /// Truncated remainder — the KISS-OPS §6.15-0003 `rem_trunc` op, DISTINCT from
8471 /// [`rem`](Self::rem) (which is FLOORED / PyTorch, sign of the *divisor*).
8472 /// `rem_trunc` takes the sign of the *dividend* (C99 `fmod` / Rust `%`).
8473 ///
8474 /// Built by RESOLUTION through KISS's spec-pinned §6.13 decomposition
8475 /// (KISS-OPS-6.15-0003) — `a - trunc(a / b) * b` — used VERBATIM. Fuel does not
8476 /// substitute `rem` (that substitution is the §6.15 violation); the two diverge
8477 /// whenever the operands have opposite signs (e.g. `-7 rem_trunc 3 = -1`, where
8478 /// `rem` (floored) = `2`). The `trunc` leaf is Fuel's own expansion (GAP-300).
8479 pub fn rem_trunc(&self, other: &NodeHandle) -> NodeHandle {
8480 // a - trunc(a / b) * b
8481 let a = self;
8482 let b = other;
8483 let t = a.div(b).trunc();
8484 a.sub(&t.mul(b))
8485 }
8486
8487 /// Element-wise addition with automatic broadcasting. Unlike `add`,
8488 /// which requires matching shapes, `broadcast_add` computes the
8489 /// broadcast shape of the two operands, inserts explicit
8490 /// `BroadcastTo` nodes as needed, and then emits a regular `Add`.
8491 /// Useful for bias addition (`[batch, hidden] + [hidden]`) without
8492 /// the caller writing the broadcast out explicitly.
8493 ///
8494 /// # Panics
8495 ///
8496 /// Panics if any operand belongs to a different [`Graph`] than the one this
8497 /// builder is building into. Operand identity is graph-scoped and checked by
8498 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8499 /// deliberate and replaces the hang a cross-graph handle used to produce.
8500 /// Build every operand from one graph, or use a `Result`-returning entry
8501 /// point where one exists.
8502 pub fn broadcast_add(&self, other: &NodeHandle) -> NodeHandle {
8503 let (a, b) = self.auto_broadcast_pair("broadcast_add", other);
8504 a.add(&b)
8505 }
8506
8507 /// Element-wise subtraction with automatic broadcasting.
8508 ///
8509 /// # Panics
8510 ///
8511 /// Panics if any operand belongs to a different [`Graph`] than the one this
8512 /// builder is building into. Operand identity is graph-scoped and checked by
8513 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8514 /// deliberate and replaces the hang a cross-graph handle used to produce.
8515 /// Build every operand from one graph, or use a `Result`-returning entry
8516 /// point where one exists.
8517 pub fn broadcast_sub(&self, other: &NodeHandle) -> NodeHandle {
8518 let (a, b) = self.auto_broadcast_pair("broadcast_sub", other);
8519 a.sub(&b)
8520 }
8521
8522 /// Element-wise multiplication with automatic broadcasting.
8523 ///
8524 /// # Panics
8525 ///
8526 /// Panics if any operand belongs to a different [`Graph`] than the one this
8527 /// builder is building into. Operand identity is graph-scoped and checked by
8528 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8529 /// deliberate and replaces the hang a cross-graph handle used to produce.
8530 /// Build every operand from one graph, or use a `Result`-returning entry
8531 /// point where one exists.
8532 pub fn broadcast_mul(&self, other: &NodeHandle) -> NodeHandle {
8533 let (a, b) = self.auto_broadcast_pair("broadcast_mul", other);
8534 a.mul(&b)
8535 }
8536
8537 /// Element-wise division with automatic broadcasting.
8538 ///
8539 /// # Panics
8540 ///
8541 /// Panics if any operand belongs to a different [`Graph`] than the one this
8542 /// builder is building into. Operand identity is graph-scoped and checked by
8543 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8544 /// deliberate and replaces the hang a cross-graph handle used to produce.
8545 /// Build every operand from one graph, or use a `Result`-returning entry
8546 /// point where one exists.
8547 pub fn broadcast_div(&self, other: &NodeHandle) -> NodeHandle {
8548 let (a, b) = self.auto_broadcast_pair("broadcast_div", other);
8549 a.div(&b)
8550 }
8551
8552 /// Build both operands broadcast to their common shape. Used by the
8553 /// `broadcast_*` wrappers above. Inserts explicit `BroadcastTo` nodes
8554 /// on whichever side needs them — either or both may pass through
8555 /// unchanged if already at the target shape.
8556 fn auto_broadcast_pair(
8557 &self,
8558 op: &'static str,
8559 other: &NodeHandle,
8560 ) -> (NodeHandle, NodeHandle) {
8561 assert!(
8562 Arc::ptr_eq(&self.graph, &other.graph),
8563 "{op}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8564 each `from_*` constructor mints a NEW graph, so build the second operand with \
8565 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8566 self.graph_id(),
8567 other.graph_id(),
8568 );
8569 assert_eq!(
8570 self.dtype(),
8571 other.dtype(),
8572 "{op}: dtype mismatch {:?} vs {:?}",
8573 self.dtype(),
8574 other.dtype(),
8575 );
8576 let a_shape = self.shape();
8577 let b_shape = other.shape();
8578 let target_dims = compute_broadcast_shape(a_shape.dims(), b_shape.dims());
8579 let target = Shape::from_dims(&target_dims);
8580 let a = if a_shape.dims() == target.dims() {
8581 self.clone()
8582 } else {
8583 self.broadcast_to(target.clone())
8584 };
8585 let b = if b_shape.dims() == target.dims() {
8586 other.clone()
8587 } else {
8588 other.broadcast_to(target)
8589 };
8590 (a, b)
8591 }
8592
8593 /// Append an `IndexAdd` node — the functional inverse of
8594 /// `IndexSelect`. Returns `base` with `src` added at positions given
8595 /// by `indices` along `dim`.
8596 ///
8597 /// # Panics
8598 ///
8599 /// Panics if any operand belongs to a different [`Graph`] than the one this
8600 /// builder is building into. Operand identity is graph-scoped and checked by
8601 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8602 /// deliberate and replaces the hang a cross-graph handle used to produce.
8603 /// Build every operand from one graph, or use a `Result`-returning entry
8604 /// point where one exists.
8605 pub fn index_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8606 assert!(
8607 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8608 "index_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8609 );
8610 assert_eq!(indices.dtype(), DType::U32, "index_add: index must be U32");
8611 assert_eq!(
8612 self.dtype(),
8613 src.dtype(),
8614 "index_add: base and src dtypes must match"
8615 );
8616 let base_dims = self.shape();
8617 let src_dims = src.shape();
8618 assert_eq!(
8619 base_dims.dims().len(),
8620 src_dims.dims().len(),
8621 "index_add: base and src must have the same rank",
8622 );
8623 assert_eq!(
8624 indices.shape().dims().len(),
8625 1,
8626 "index_add: index must be rank 1",
8627 );
8628 assert_eq!(
8629 src_dims.dims()[dim],
8630 indices.shape().dims()[0],
8631 "index_add: src dim {dim} ({}) must match index length ({})",
8632 src_dims.dims()[dim],
8633 indices.shape().dims()[0],
8634 );
8635 let dtype = self.dtype();
8636 let out_shape = base_dims;
8637 let id = self.graph.write().unwrap().push(Node {
8638 op: Op::IndexAdd { dim },
8639 inputs: vec![self.id, indices.id, src.id],
8640 shape: out_shape,
8641 dtype,
8642 });
8643 Self {
8644 graph: self.graph.clone(),
8645 id,
8646 }
8647 }
8648
8649 /// Append a `ScatterAdd` node — the functional inverse of `Gather`.
8650 /// Returns `base` with values from `src` accumulated at positions
8651 /// given by `indices` (with `indices[p]` substituted at `dim`).
8652 ///
8653 /// # Panics
8654 ///
8655 /// Panics if any operand belongs to a different [`Graph`] than the one this
8656 /// builder is building into. Operand identity is graph-scoped and checked by
8657 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
8658 /// deliberate and replaces the hang a cross-graph handle used to produce.
8659 /// Build every operand from one graph, or use a `Result`-returning entry
8660 /// point where one exists.
8661 pub fn scatter_add(&self, dim: usize, indices: &NodeHandle, src: &NodeHandle) -> NodeHandle {
8662 assert!(
8663 Arc::ptr_eq(&self.graph, &indices.graph) && Arc::ptr_eq(&self.graph, &src.graph),
8664 "scatter_add: all tensors must live on the same graph; use `const_*_like` to build on an existing graph",
8665 );
8666 assert_eq!(
8667 indices.dtype(),
8668 DType::U32,
8669 "scatter_add: index must be U32"
8670 );
8671 assert_eq!(
8672 self.dtype(),
8673 src.dtype(),
8674 "scatter_add: base and src dtypes must match"
8675 );
8676 assert_eq!(
8677 indices.shape().dims(),
8678 src.shape().dims(),
8679 "scatter_add: index and src must have the same shape",
8680 );
8681 let dtype = self.dtype();
8682 let out_shape = self.shape();
8683 let id = self.graph.write().unwrap().push(Node {
8684 op: Op::ScatterAdd { dim },
8685 inputs: vec![self.id, indices.id, src.id],
8686 shape: out_shape,
8687 dtype,
8688 });
8689 Self {
8690 graph: self.graph.clone(),
8691 id,
8692 }
8693 }
8694
8695 // --- internal helpers for the new builders ---
8696
8697 fn scalar_reduction(&self, op: Op) -> NodeHandle {
8698 let (shape, dtype) = crate::shape::primitive_shape(&op, &[self.shape()], &[self.dtype()])
8699 .expect("scalar_reduction: single input always infers a rank-0 shape");
8700 let id = self.graph.write().unwrap().push(Node {
8701 op,
8702 inputs: vec![self.id],
8703 shape,
8704 dtype,
8705 });
8706 Self {
8707 graph: self.graph.clone(),
8708 id,
8709 }
8710 }
8711
8712 fn axis_reduction(&self, name: &'static str, op: Op, dim: usize) -> NodeHandle {
8713 let in_shape = self.shape();
8714 assert!(
8715 dim < in_shape.dims().len(),
8716 "{name}: dim {dim} out of bounds for shape {:?}",
8717 in_shape.dims(),
8718 );
8719 let (shape, dtype) = crate::shape::primitive_shape(&op, &[in_shape], &[self.dtype()])
8720 .expect("axis_reduction: dim validated above");
8721 let id = self.graph.write().unwrap().push(Node {
8722 op,
8723 inputs: vec![self.id],
8724 shape,
8725 dtype,
8726 });
8727 Self {
8728 graph: self.graph.clone(),
8729 id,
8730 }
8731 }
8732
8733 // Internal helpers. Both shape-validate and append.
8734
8735 /// Build-time graph-affinity check for a `Result`-returning builder.
8736 ///
8737 /// Node ids index ONE graph's arena, so an operand from a different graph
8738 /// records an id pointing at an unrelated node — a malformed dependency
8739 /// graph whose failure mode is a **realize-time hang**, not a panic or an
8740 /// error. Checking here converts a silent deadlock into a typed build-time
8741 /// error naming both graphs, per "validate at graph-build time".
8742 fn require_same_graph(
8743 &self,
8744 other: &NodeHandle,
8745 op: &str,
8746 role: &str,
8747 ) -> std::result::Result<(), fuel_ir::Error> {
8748 if !Arc::ptr_eq(&self.graph, &other.graph) {
8749 return Err(fuel_ir::Error::Msg(format!(
8750 "{op}: operands must live on the same graph — self is on graph #{}, \
8751 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8752 build the other operand with `from_*_on(self.graph(), ..)` or \
8753 `const_*_like`",
8754 self.graph_id(),
8755 other.graph_id(),
8756 ))
8757 .bt());
8758 }
8759 Ok(())
8760 }
8761
8762 /// Panicking sibling of [`Self::require_same_graph`] for the builders that
8763 /// return `NodeHandle` rather than `Result` — same convention as `matmul`,
8764 /// `qmatmul`, `conv2d` and `paged_attn`. A panic at the build site is far
8765 /// better than the hang it replaces: it names the operand and both graphs.
8766 fn assert_same_graph(&self, other: &NodeHandle, op: &str, role: &str) {
8767 assert!(
8768 Arc::ptr_eq(&self.graph, &other.graph),
8769 "{op}: operands must live on the same graph — self is on graph #{}, \
8770 {role} on graph #{}; each `from_*` constructor mints a NEW graph, so \
8771 build the other operand with `from_*_on(self.graph(), ..)` or \
8772 `const_*_like`",
8773 self.graph_id(),
8774 other.graph_id(),
8775 );
8776 }
8777
8778 fn binary_op(
8779 &self,
8780 name: &'static str,
8781 op: Op,
8782 other: &NodeHandle,
8783 out_shape: Shape,
8784 ) -> NodeHandle {
8785 assert!(
8786 Arc::ptr_eq(&self.graph, &other.graph),
8787 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8788 each `from_*` constructor mints a NEW graph, so build the second operand with \
8789 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8790 self.graph_id(),
8791 other.graph_id(),
8792 );
8793 assert_eq!(
8794 self.dtype(),
8795 other.dtype(),
8796 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8797 self.dtype(),
8798 other.dtype(),
8799 );
8800 assert_eq!(
8801 self.shape().dims(),
8802 other.shape().dims(),
8803 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8804 self.shape().dims(),
8805 other.shape().dims(),
8806 );
8807 let dtype = self.dtype();
8808 let id = self.graph.write().unwrap().push(Node {
8809 op,
8810 inputs: vec![self.id, other.id],
8811 shape: out_shape,
8812 dtype,
8813 });
8814 Self {
8815 graph: self.graph.clone(),
8816 id,
8817 }
8818 }
8819
8820 /// Result-returning sibling of [`Self::binary_op`]. Validates the
8821 /// graph/dtype/shape preconditions and returns `Err` rather than
8822 /// panicking — the production-correct shape new builders should
8823 /// use. Existing panicking sites are kept for back-compat; new
8824 /// ops should call this directly.
8825 fn try_binary_op(
8826 &self,
8827 name: &'static str,
8828 op: Op,
8829 other: &NodeHandle,
8830 out_shape: Shape,
8831 ) -> std::result::Result<NodeHandle, fuel_ir::Error> {
8832 if !Arc::ptr_eq(&self.graph, &other.graph) {
8833 return Err(fuel_ir::Error::Msg(format!(
8834 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8835 each `from_*` constructor mints a NEW graph, so build the second operand with \
8836 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8837 self.graph_id(),
8838 other.graph_id(),
8839 )).bt());
8840 }
8841 if self.dtype() != other.dtype() {
8842 return Err(fuel_ir::Error::Msg(format!(
8843 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8844 self.dtype(),
8845 other.dtype(),
8846 ))
8847 .bt());
8848 }
8849 if self.shape().dims() != other.shape().dims() {
8850 return Err(fuel_ir::Error::Msg(format!(
8851 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8852 self.shape().dims(),
8853 other.shape().dims(),
8854 ))
8855 .bt());
8856 }
8857 let dtype = self.dtype();
8858 let id = self.graph.write().unwrap().push(Node {
8859 op,
8860 inputs: vec![self.id, other.id],
8861 shape: out_shape,
8862 dtype,
8863 });
8864 Ok(Self {
8865 graph: self.graph.clone(),
8866 id,
8867 })
8868 }
8869
8870 fn unary_op(&self, op: Op) -> NodeHandle {
8871 let shape = self.shape();
8872 let dtype = self.dtype();
8873 let id = self.graph.write().unwrap().push(Node {
8874 op,
8875 inputs: vec![self.id],
8876 shape,
8877 dtype,
8878 });
8879 Self {
8880 graph: self.graph.clone(),
8881 id,
8882 }
8883 }
8884
8885 /// Binary builder for ops whose inputs share dtype/shape but whose
8886 /// output is a `U8` mask (`Op::Equal` and the rest of the
8887 /// comparison family). Differs from [`Self::binary_op`] only in the
8888 /// node's output dtype: always `DType::U8` regardless of input
8889 /// dtype.
8890 fn binary_compare_op(&self, name: &'static str, op: Op, other: &NodeHandle) -> NodeHandle {
8891 assert!(
8892 Arc::ptr_eq(&self.graph, &other.graph),
8893 "{name}: tensors must live on the same graph — lhs is on graph #{}, rhs on graph #{}; \
8894 each `from_*` constructor mints a NEW graph, so build the second operand with \
8895 `from_*_on(lhs.graph(), ..)` or `const_*_like`",
8896 self.graph_id(),
8897 other.graph_id(),
8898 );
8899 assert_eq!(
8900 self.dtype(),
8901 other.dtype(),
8902 "{name}: dtype mismatch: lhs={:?}, rhs={:?}",
8903 self.dtype(),
8904 other.dtype(),
8905 );
8906 assert_eq!(
8907 self.shape().dims(),
8908 other.shape().dims(),
8909 "{name}: shape mismatch: lhs={:?}, rhs={:?}",
8910 self.shape().dims(),
8911 other.shape().dims(),
8912 );
8913 let shape = self.shape();
8914 let id = self.graph.write().unwrap().push(Node {
8915 op,
8916 inputs: vec![self.id, other.id],
8917 shape,
8918 // GAP-168(c): comparisons yield a `Bool` mask. This BUILDER path is
8919 // the one eq/ne/lt/le/gt/ge take; it must agree with the
8920 // `primitive_shape` comparison arm (fuel-graph/src/shape.rs), which
8921 // is the OTHER site that decides this dtype (reached on re-lowering).
8922 dtype: DType::Bool,
8923 });
8924 Self {
8925 graph: self.graph.clone(),
8926 id,
8927 }
8928 }
8929
8930 /// Build the backward graph from `self`, treating `self` as the output
8931 /// whose gradient drives the rest of the computation.
8932 ///
8933 /// Walks the forward graph in reverse topological order, applies the
8934 /// per-op gradient rule to each node, and emits new graph nodes for
8935 /// the gradient with respect to every node reachable from `self`. The
8936 /// returned [`GradMap`] lets you look up the gradient tensor for any
8937 /// forward tensor from the same graph.
8938 ///
8939 /// The initial upstream gradient is a ones tensor of the same shape
8940 /// and dtype as `self` — the conventional `dL/dL = 1` seed for
8941 /// backprop. For a scalar loss this is `[1.0]`; for a non-scalar
8942 /// output it is "each element of the output contributes with weight 1
8943 /// to the total derivative."
8944 ///
8945 /// ## Supported ops in the MVP
8946 ///
8947 /// `Const`, `Add`, `Mul`, `MatMul`, `Transpose`, `Sqr`, `Exp` all have
8948 /// gradient rules implemented. `Relu` panics — its gradient needs a
8949 /// `Step`/`Where`/`Sign` op that is not yet in the catalog and will
8950 /// land in a follow-up once an indicator-valued op is defined.
8951 ///
8952 /// ## Ownership and the forward graph
8953 ///
8954 /// Backward extends the same graph that held the forward pass. The
8955 /// gradient nodes live alongside the forward nodes in one arena. After
8956 /// `backward()`, realizing a gradient tensor re-executes whatever part
8957 /// of the forward pass the gradient depends on — the executor walks
8958 /// the combined graph as one.
8959 pub fn backward(&self) -> GradMap {
8960 let graph_handle = self.graph.clone();
8961
8962 // C3 pre-pass (Op::Scan Phase 2): lower every reachable Op::Scan to
8963 // primitives + decompose the SSM fused recipes BEFORE the topo order is
8964 // taken, so the reverse walk sees only differentiable primitives. On a
8965 // scan-free graph it is a near-no-op — two topo scans (Pass 1's SSM
8966 // collect + Pass 2's first iteration, which finds no scans and breaks),
8967 // no rewiring. The (possibly remapped) root replaces self.id below.
8968 let root = lower_scans_for_backward(&graph_handle, self.id);
8969
8970 // Compute topological order of reachable nodes, then reverse it
8971 // so we walk from the root (output) toward the leaves (inputs).
8972 let mut order = topo_order(&graph_handle.read().unwrap(), root);
8973 order.reverse();
8974
8975 // Initial upstream gradient for the root: ones tensor of matching
8976 // shape and dtype. For a scalar loss this is [1.0]; for vector
8977 // outputs it seeds each element with weight 1.
8978 let (root_shape, root_dtype) = {
8979 let g = graph_handle.read().unwrap();
8980 let n = g.node(root);
8981 (n.shape.clone(), n.dtype)
8982 };
8983 let ones_id = build_ones(&graph_handle, root_shape, root_dtype);
8984
8985 let mut upstream: HashMap<NodeId, NodeId> = HashMap::new();
8986 upstream.insert(root, ones_id);
8987
8988 for id in order {
8989 let up_id = match upstream.get(&id).copied() {
8990 Some(v) => v,
8991 None => continue, // unreachable from the root, no gradient to propagate
8992 };
8993 // Snapshot the op and its input IDs so we can drop the read
8994 // borrow before taking a mutable borrow to append new nodes.
8995 let (op, inputs) = {
8996 let g = graph_handle.read().unwrap();
8997 let node = g.node(id);
8998 (node.op.clone(), node.inputs.clone())
8999 };
9000
9001 // Symbolic-autograd dispatch (Phase 6d Track 2). If a
9002 // `GradientRule` is registered for this op, use it. Ops
9003 // that haven't migrated yet fall through to the legacy
9004 // inline `match` below.
9005 if let Some(grads) =
9006 crate::grad::dispatch_gradient(&graph_handle, &op, &inputs, id, up_id)
9007 {
9008 debug_assert_eq!(
9009 grads.len(),
9010 inputs.len(),
9011 "GradientRule for {:?} returned {} gradients but op has {} inputs",
9012 op.short_name(),
9013 grads.len(),
9014 inputs.len(),
9015 );
9016 for (input_id, grad) in inputs.iter().zip(grads.iter()) {
9017 if let Some(g) = grad {
9018 accumulate_grad(&mut upstream, *input_id, *g, &graph_handle);
9019 }
9020 }
9021 continue;
9022 }
9023
9024 match op {
9025 Op::Const => {
9026 // Leaf. The upstream value has already been stored and
9027 // is what `GradMap::get` will return for this input.
9028 }
9029 Op::Iota { .. } => {
9030 // Leaf, non-differentiable: a constant position
9031 // generator with no inputs — no gradient to propagate.
9032 }
9033 Op::NonZeroIndices { .. } => {
9034 // Produces discrete indices + a runtime count; both
9035 // are integer/non-differentiable. No gradient flows to
9036 // the input. (A differentiated graph that reaches this
9037 // op surfaces as a usage error in the grad-emitting
9038 // pass, matching the ArgMaxDim/ArgMinDim precedent.)
9039 }
9040 Op::Add => {
9041 // d(a + b)/da = 1, d(a + b)/db = 1.
9042 // Upstream flows unchanged into both inputs.
9043 accumulate_grad(&mut upstream, inputs[0], up_id, &graph_handle);
9044 accumulate_grad(&mut upstream, inputs[1], up_id, &graph_handle);
9045 }
9046 Op::Mul => {
9047 // d(a * b)/da = b, d(a * b)/db = a.
9048 // Upstream * b goes to a; upstream * a goes to b.
9049 let a = inputs[0];
9050 let b = inputs[1];
9051 let a_shape = node_shape(&graph_handle, a);
9052 let b_shape = node_shape(&graph_handle, b);
9053 let dtype = node_dtype(&graph_handle, a);
9054 let grad_a = push_node(&graph_handle, Op::Mul, vec![up_id, b], a_shape, dtype);
9055 let grad_b = push_node(&graph_handle, Op::Mul, vec![up_id, a], b_shape, dtype);
9056 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9057 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9058 }
9059 Op::MatMul => {
9060 // Forward: Y = A @ B, A: [m, k], B: [k, n], Y: [m, n]
9061 // Backward: dA = dY @ B^T, dB = A^T @ dY.
9062 let a = inputs[0];
9063 let b = inputs[1];
9064 let a_shape = node_shape(&graph_handle, a);
9065 let b_shape = node_shape(&graph_handle, b);
9066 let dtype = node_dtype(&graph_handle, a);
9067 // B^T: shape [n, k]
9068 let b_t_shape = transposed_shape(&b_shape);
9069 let b_t = push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
9070 // dA = upstream @ B^T, shape [m, k] = a_shape
9071 let grad_a = push_node(
9072 &graph_handle,
9073 Op::MatMul,
9074 vec![up_id, b_t],
9075 a_shape.clone(),
9076 dtype,
9077 );
9078 // A^T: shape [k, m]
9079 let a_t_shape = transposed_shape(&a_shape);
9080 let a_t = push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
9081 // dB = A^T @ upstream, shape [k, n] = b_shape
9082 let grad_b =
9083 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
9084 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9085 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9086 }
9087 Op::Transpose => {
9088 // d(x^T)/dx is a transpose on the way back.
9089 let x = inputs[0];
9090 let x_shape = node_shape(&graph_handle, x);
9091 let dtype = node_dtype(&graph_handle, x);
9092 let grad_x =
9093 push_node(&graph_handle, Op::Transpose, vec![up_id], x_shape, dtype);
9094 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9095 }
9096 Op::Permute(ref axes) => {
9097 // Backward: apply the inverse permutation to upstream.
9098 // If forward permutes with `axes` (out[i] = in[axes[i]]),
9099 // the inverse `inv` satisfies `inv[axes[i]] = i`.
9100 let x = inputs[0];
9101 let x_shape = node_shape(&graph_handle, x);
9102 let dtype = node_dtype(&graph_handle, x);
9103 let mut inv = vec![0_usize; axes.len()];
9104 for (i, &ax) in axes.iter().enumerate() {
9105 inv[ax] = i;
9106 }
9107 let grad_x =
9108 push_node(&graph_handle, Op::Permute(inv), vec![up_id], x_shape, dtype);
9109 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9110 }
9111 Op::Sqr => {
9112 // d(x^2)/dx = 2x. Expressed as `x + x` to avoid
9113 // needing a scalar constant broadcast — both sums
9114 // have the same shape as x, the existing Add op
9115 // handles them natively.
9116 let x = inputs[0];
9117 let x_shape = node_shape(&graph_handle, x);
9118 let dtype = node_dtype(&graph_handle, x);
9119 let two_x =
9120 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
9121 let grad_x =
9122 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
9123 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9124 }
9125 Op::Exp => {
9126 // d(e^x)/dx = e^x, which is the forward output — i.e.
9127 // this node `id`. Reuse it directly instead of
9128 // recomputing.
9129 let x = inputs[0];
9130 let out_shape = node_shape(&graph_handle, id);
9131 let dtype = node_dtype(&graph_handle, id);
9132 let grad_x =
9133 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
9134 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9135 }
9136 Op::Sub => {
9137 // d(a - b)/da = 1, d(a - b)/db = -1.
9138 let a = inputs[0];
9139 let b = inputs[1];
9140 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9141 let b_shape = node_shape(&graph_handle, b);
9142 let dtype = node_dtype(&graph_handle, b);
9143 let neg_up = push_node(&graph_handle, Op::Neg, vec![up_id], b_shape, dtype);
9144 accumulate_grad(&mut upstream, b, neg_up, &graph_handle);
9145 }
9146 Op::Div => {
9147 // y = a / b
9148 // dy/da = 1/b → grad_a = upstream / b
9149 // dy/db = -a/b² → grad_b = -(upstream * a / (b*b))
9150 let a = inputs[0];
9151 let b = inputs[1];
9152 let a_shape = node_shape(&graph_handle, a);
9153 let b_shape = node_shape(&graph_handle, b);
9154 let dtype = node_dtype(&graph_handle, a);
9155 // grad_a
9156 let grad_a = push_node(
9157 &graph_handle,
9158 Op::Div,
9159 vec![up_id, b],
9160 a_shape.clone(),
9161 dtype,
9162 );
9163 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9164 // grad_b: -(upstream * a / (b*b))
9165 let b_sq = push_node(&graph_handle, Op::Sqr, vec![b], b_shape.clone(), dtype);
9166 let up_times_a =
9167 push_node(&graph_handle, Op::Mul, vec![up_id, a], a_shape, dtype);
9168 let quotient = push_node(
9169 &graph_handle,
9170 Op::Div,
9171 vec![up_times_a, b_sq],
9172 b_shape.clone(),
9173 dtype,
9174 );
9175 let grad_b = push_node(&graph_handle, Op::Neg, vec![quotient], b_shape, dtype);
9176 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9177 }
9178 Op::Neg => {
9179 // d(-x)/dx = -1. grad_x = -upstream.
9180 let x = inputs[0];
9181 let x_shape = node_shape(&graph_handle, x);
9182 let dtype = node_dtype(&graph_handle, x);
9183 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
9184 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9185 }
9186 Op::Sqrt => {
9187 // y = sqrt(x), dy/dx = 1/(2*sqrt(x)) = 1/(2y).
9188 // grad_x = upstream / (y + y). Reuse the forward node.
9189 let x = inputs[0];
9190 let x_shape = node_shape(&graph_handle, x);
9191 let dtype = node_dtype(&graph_handle, x);
9192 let two_y =
9193 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
9194 let grad_x =
9195 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
9196 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9197 }
9198 Op::Log => {
9199 // d(ln(x))/dx = 1/x. grad_x = upstream / x.
9200 let x = inputs[0];
9201 let x_shape = node_shape(&graph_handle, x);
9202 let dtype = node_dtype(&graph_handle, x);
9203 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
9204 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9205 }
9206 Op::Sin => {
9207 // d(sin(x))/dx = cos(x). grad_x = upstream * cos(x).
9208 let x = inputs[0];
9209 let x_shape = node_shape(&graph_handle, x);
9210 let dtype = node_dtype(&graph_handle, x);
9211 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
9212 let grad_x =
9213 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
9214 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9215 }
9216 Op::Cos => {
9217 // d(cos(x))/dx = -sin(x). grad_x = -(upstream * sin(x)).
9218 let x = inputs[0];
9219 let x_shape = node_shape(&graph_handle, x);
9220 let dtype = node_dtype(&graph_handle, x);
9221 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
9222 let up_sin = push_node(
9223 &graph_handle,
9224 Op::Mul,
9225 vec![up_id, sin_x],
9226 x_shape.clone(),
9227 dtype,
9228 );
9229 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
9230 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9231 }
9232 Op::Tanh => {
9233 // y = tanh(x), dy/dx = 1 - y². grad_x = upstream * (1 - y*y).
9234 // Build: ones_of_y_shape - y*y, then multiply by upstream.
9235 let x = inputs[0];
9236 let y_shape = node_shape(&graph_handle, id);
9237 let dtype = node_dtype(&graph_handle, id);
9238 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
9239 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9240 let one_minus_sq = push_node(
9241 &graph_handle,
9242 Op::Sub,
9243 vec![ones, y_sq],
9244 y_shape.clone(),
9245 dtype,
9246 );
9247 let grad_x = push_node(
9248 &graph_handle,
9249 Op::Mul,
9250 vec![up_id, one_minus_sq],
9251 y_shape,
9252 dtype,
9253 );
9254 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9255 }
9256 Op::Sigmoid => {
9257 // y = sigmoid(x), dy/dx = y * (1 - y).
9258 // grad_x = upstream * y * (1 - y).
9259 let x = inputs[0];
9260 let y_shape = node_shape(&graph_handle, id);
9261 let dtype = node_dtype(&graph_handle, id);
9262 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
9263 let one_minus_y = push_node(
9264 &graph_handle,
9265 Op::Sub,
9266 vec![ones, id],
9267 y_shape.clone(),
9268 dtype,
9269 );
9270 let y_times_1my = push_node(
9271 &graph_handle,
9272 Op::Mul,
9273 vec![id, one_minus_y],
9274 y_shape.clone(),
9275 dtype,
9276 );
9277 let grad_x = push_node(
9278 &graph_handle,
9279 Op::Mul,
9280 vec![up_id, y_times_1my],
9281 y_shape,
9282 dtype,
9283 );
9284 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9285 }
9286 Op::Silu => {
9287 // y = x * sigmoid(x)
9288 // dy/dx = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
9289 // = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
9290 //
9291 // Simpler: let s = sigmoid(x). dy/dx = s + y * (1 - s),
9292 // where y = x * s is the forward output (this node).
9293 // grad_x = upstream * (s + y * (1 - s)).
9294 let x = inputs[0];
9295 let x_shape = node_shape(&graph_handle, x);
9296 let dtype = node_dtype(&graph_handle, x);
9297 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
9298 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
9299 let one_minus_s = push_node(
9300 &graph_handle,
9301 Op::Sub,
9302 vec![ones, s],
9303 x_shape.clone(),
9304 dtype,
9305 );
9306 let y_times_1ms = push_node(
9307 &graph_handle,
9308 Op::Mul,
9309 vec![id, one_minus_s],
9310 x_shape.clone(),
9311 dtype,
9312 );
9313 let inner = push_node(
9314 &graph_handle,
9315 Op::Add,
9316 vec![s, y_times_1ms],
9317 x_shape.clone(),
9318 dtype,
9319 );
9320 let grad_x =
9321 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
9322 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9323 }
9324 Op::GeluTanh => {
9325 // GELU's tanh-approximation backward is non-trivial.
9326 // For the MVP, compute it numerically stable via
9327 // central differences — no, that's wrong for
9328 // backward. The proper rule differentiates
9329 // `0.5 x (1 + tanh(c * (x + 0.044715 x³)))` by chain
9330 // rule. That requires several new intermediate
9331 // nodes. Implemented below:
9332 //
9333 // Let u = c * (x + 0.044715 x³), t = tanh(u).
9334 // y = 0.5 x (1 + t)
9335 // du/dx = c * (1 + 3 * 0.044715 * x²)
9336 // = c + 3 c * 0.044715 * x²
9337 // dt/dx = (1 - t²) * du/dx
9338 // dy/dx = 0.5 * (1 + t) + 0.5 * x * dt/dx
9339 //
9340 // This is enough ops that it deserves a dedicated
9341 // backward node. For the MVP, panic — users who need
9342 // GELU backward should use Silu, which we just
9343 // implemented properly.
9344 panic!(
9345 "backward: GeluTanh gradient is not yet supported. \
9346 Use Silu for differentiable training; GeluTanh is \
9347 currently inference-only."
9348 );
9349 }
9350 Op::Relu => {
9351 // d(relu(x))/dx = step(x). grad_x = upstream * step(x).
9352 let x = inputs[0];
9353 let x_shape = node_shape(&graph_handle, x);
9354 let dtype = node_dtype(&graph_handle, x);
9355 let step_x =
9356 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
9357 let grad_x =
9358 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
9359 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9360 }
9361 Op::Step => {
9362 // d(step(x))/dx is 0 almost everywhere (and a Dirac
9363 // delta at 0 which has no finite representation). The
9364 // standard move is to treat the derivative as 0 and
9365 // stop propagation — Step's backward is silently a
9366 // no-op. Callers that need a smooth surrogate should
9367 // use Sigmoid or Tanh instead.
9368 }
9369 Op::Recip => {
9370 // y = 1/x, dy/dx = -1/x² = -y².
9371 // grad_x = -upstream * y * y. Reuse forward output (id)
9372 // so we don't recompute the reciprocal.
9373 let x = inputs[0];
9374 let x_shape = node_shape(&graph_handle, x);
9375 let dtype = node_dtype(&graph_handle, x);
9376 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9377 let up_y_sq = push_node(
9378 &graph_handle,
9379 Op::Mul,
9380 vec![up_id, y_sq],
9381 x_shape.clone(),
9382 dtype,
9383 );
9384 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
9385 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9386 }
9387 Op::Abs => {
9388 // y = |x|, dy/dx = sign(x), with sign(0)=0 by
9389 // subgradient convention. Simplified to a direct
9390 // `Op::Sign` use after Op::Sign landed in PR B2;
9391 // the previous form synthesized `step(x) - step(-x)`
9392 // (5 backward nodes) but Sign expresses the same
9393 // function in 1 node, so the chain shrinks to
9394 // `Mul(upstream, Sign(x))` — 2 nodes total.
9395 let x = inputs[0];
9396 let x_shape = node_shape(&graph_handle, x);
9397 let dtype = node_dtype(&graph_handle, x);
9398 let sign_x =
9399 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
9400 let grad_x =
9401 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
9402 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9403 }
9404 Op::Where => {
9405 // Handled by `WhereRule` via `dispatch_gradient`;
9406 // this arm only exists for exhaustiveness.
9407 }
9408 Op::Floor | Op::Ceil | Op::Round | Op::Sign => {
9409 // d(floor(x))/dx, d(ceil(x))/dx, d(round(x))/dx,
9410 // d(sign(x))/dx are all 0 almost everywhere (with
9411 // a Dirac train at integer / half-integer / zero
9412 // that has no finite representation). Treat the
9413 // derivative as 0 and stop propagation — mirrors
9414 // `Op::Step`'s backward.
9415 }
9416 Op::Erf => {
9417 // y = erf(x). dy/dx = (2/√π) * exp(-x²).
9418 // grad_x = upstream * (2/√π) * exp(-x²).
9419 // Decomposes to: Sqr(x) → Neg → Exp → MulScalar(2/√π)
9420 // → Mul(upstream, .).
9421 // 2/√π = 1.1283791670955125738961589031...
9422 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
9423 let x = inputs[0];
9424 let x_shape = node_shape(&graph_handle, x);
9425 let dtype = node_dtype(&graph_handle, x);
9426 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9427 let neg_x_sq =
9428 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
9429 let exp_neg_x_sq = push_node(
9430 &graph_handle,
9431 Op::Exp,
9432 vec![neg_x_sq],
9433 x_shape.clone(),
9434 dtype,
9435 );
9436 let scaled = push_node(
9437 &graph_handle,
9438 Op::MulScalar(TWO_OVER_SQRT_PI),
9439 vec![exp_neg_x_sq],
9440 x_shape.clone(),
9441 dtype,
9442 );
9443 let grad_x =
9444 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9445 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9446 }
9447 Op::Flip { dim } => {
9448 // y = flip(x, dim). Backward is another Flip on
9449 // the same dim — Flip is its own inverse
9450 // (involutive). One backward node, exact gradient.
9451 let x = inputs[0];
9452 let x_shape = node_shape(&graph_handle, x);
9453 let dtype = node_dtype(&graph_handle, x);
9454 let grad_x =
9455 push_node(&graph_handle, Op::Flip { dim }, vec![up_id], x_shape, dtype);
9456 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9457 }
9458 Op::Pad {
9459 padding,
9460 mode,
9461 value: _,
9462 } => {
9463 // Backward delegates to Op::PadBackward — a single
9464 // node that handles all three modes uniformly via
9465 // its kernel. Constant: slice the unpadded region.
9466 // Reflect/Replicate: accumulate gradient at the
9467 // mirrored / replicated positions.
9468 let padding = padding.clone();
9469 let x = inputs[0];
9470 let x_shape = node_shape(&graph_handle, x);
9471 let dtype = node_dtype(&graph_handle, x);
9472 let grad_x = push_node(
9473 &graph_handle,
9474 Op::PadBackward {
9475 in_shape: x_shape.clone(),
9476 padding,
9477 mode,
9478 },
9479 vec![up_id],
9480 x_shape,
9481 dtype,
9482 );
9483 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9484 }
9485 Op::PadBackward { .. } => {
9486 // Backward helper — typically a leaf in autograd
9487 // (the upstream gradient itself never gets a
9488 // higher-order backward in v1). No-op arm for
9489 // exhaustiveness; if higher-order autograd needs
9490 // PadBackward's backward, that's its own scope.
9491 }
9492 Op::CumSum { dim } => {
9493 // y[..., i, ...] = sum_{k=0..=i} x[..., k, ...]
9494 // dL/dx[..., i, ...] = sum_{k=i..n} dL/dy[..., k, ...]
9495 // i.e. reverse cumsum. Express via Flip → CumSum → Flip.
9496 let x = inputs[0];
9497 let x_shape = node_shape(&graph_handle, x);
9498 let dtype = node_dtype(&graph_handle, x);
9499 let flip1 = push_node(
9500 &graph_handle,
9501 Op::Flip { dim },
9502 vec![up_id],
9503 x_shape.clone(),
9504 dtype,
9505 );
9506 let cs = push_node(
9507 &graph_handle,
9508 Op::CumSum { dim },
9509 vec![flip1],
9510 x_shape.clone(),
9511 dtype,
9512 );
9513 let grad_x =
9514 push_node(&graph_handle, Op::Flip { dim }, vec![cs], x_shape, dtype);
9515 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9516 }
9517 Op::Roll { dim, shift } => {
9518 // y = roll(x, dim, shift). Backward is the opposite
9519 // shift along the same dim. One backward node.
9520 let x = inputs[0];
9521 let x_shape = node_shape(&graph_handle, x);
9522 let dtype = node_dtype(&graph_handle, x);
9523 let grad_x = push_node(
9524 &graph_handle,
9525 Op::Roll { dim, shift: -shift },
9526 vec![up_id],
9527 x_shape,
9528 dtype,
9529 );
9530 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9531 }
9532 Op::Triu { diagonal } => {
9533 // y = triu(x, diagonal). Mask is a binary indicator
9534 // — gradient passes through kept positions and is
9535 // zero on the masked half. Same op on the upstream.
9536 let x = inputs[0];
9537 let x_shape = node_shape(&graph_handle, x);
9538 let dtype = node_dtype(&graph_handle, x);
9539 let grad_x = push_node(
9540 &graph_handle,
9541 Op::Triu { diagonal },
9542 vec![up_id],
9543 x_shape,
9544 dtype,
9545 );
9546 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9547 }
9548 Op::Tril { diagonal } => {
9549 // Mirror of Op::Triu — same mask gradient.
9550 let x = inputs[0];
9551 let x_shape = node_shape(&graph_handle, x);
9552 let dtype = node_dtype(&graph_handle, x);
9553 let grad_x = push_node(
9554 &graph_handle,
9555 Op::Tril { diagonal },
9556 vec![up_id],
9557 x_shape,
9558 dtype,
9559 );
9560 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9561 }
9562 Op::LogSoftmaxLastDim => {
9563 // grad_x = upstream - exp(y) * sum(upstream, last_dim, keepdim).
9564 // Folded into Op::LogSoftmaxLastDimBackward — takes
9565 // (forward_output, upstream), avoids re-evaluating
9566 // the softmax outside the kernel.
9567 let x = inputs[0];
9568 let x_shape = node_shape(&graph_handle, x);
9569 let dtype = node_dtype(&graph_handle, x);
9570 let grad_x = push_node(
9571 &graph_handle,
9572 Op::LogSoftmaxLastDimBackward,
9573 vec![id, up_id],
9574 x_shape,
9575 dtype,
9576 );
9577 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9578 }
9579 Op::LogSoftmaxLastDimBackward => {
9580 // Backward helper — no higher-order autograd in v1.
9581 }
9582 Op::MaskedFill { value: _ } => {
9583 // y = mask ? value : x. dy/dx = (mask == 0).
9584 // grad_x = MaskedFill(upstream, mask, value=0_of_dtype).
9585 // The mask is integer-only; no gradient flows to it.
9586 let x = inputs[0];
9587 let mask = inputs[1];
9588 let x_shape = node_shape(&graph_handle, x);
9589 let dtype = node_dtype(&graph_handle, x);
9590 let zero = match fuel_ir::Scalar::zero(dtype) {
9591 Ok(z) => z,
9592 Err(_) => {
9593 // A packed/scale dtype has no zero scalar. MaskedFill
9594 // on such a dtype is a build-time bug (a future D5
9595 // graph-build guard forbids it), so this is
9596 // unreachable in a well-formed graph. debug_assert
9597 // catches it in debug; release skips this gradient
9598 // rather than panicking (never-panic invariant).
9599 debug_assert!(false, "MaskedFill backward on non-real dtype {dtype:?}");
9600 continue;
9601 }
9602 };
9603 let grad_x = push_node(
9604 &graph_handle,
9605 Op::MaskedFill { value: zero },
9606 vec![up_id, mask],
9607 x_shape,
9608 dtype,
9609 );
9610 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9611 // No gradient to mask: it's discrete.
9612 }
9613 Op::Rem => {
9614 // y = a - floor(a/b) * b (PyTorch convention).
9615 // d/da = 1 (the floor term is treated as a constant
9616 // w.r.t. a almost everywhere; the actual
9617 // derivative has a Dirac component at
9618 // integer a/b ratios that we drop, matching
9619 // PyTorch's autograd convention).
9620 // d/db = -floor(a/b)
9621 // grad_a = upstream
9622 // grad_b = upstream * (-floor(a/b))
9623 let a = inputs[0];
9624 let b = inputs[1];
9625 let a_shape = node_shape(&graph_handle, a);
9626 let dtype = node_dtype(&graph_handle, a);
9627 accumulate_grad(&mut upstream, a, up_id, &graph_handle);
9628 let div_ab =
9629 push_node(&graph_handle, Op::Div, vec![a, b], a_shape.clone(), dtype);
9630 let floor_div = push_node(
9631 &graph_handle,
9632 Op::Floor,
9633 vec![div_ab],
9634 a_shape.clone(),
9635 dtype,
9636 );
9637 let neg_floor = push_node(
9638 &graph_handle,
9639 Op::Neg,
9640 vec![floor_div],
9641 a_shape.clone(),
9642 dtype,
9643 );
9644 let grad_b = push_node(
9645 &graph_handle,
9646 Op::Mul,
9647 vec![up_id, neg_floor],
9648 a_shape,
9649 dtype,
9650 );
9651 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9652 }
9653 Op::Rsqrt => {
9654 // y = x^(-1/2). dy/dx = -0.5 * x^(-3/2).
9655 // Identity: y² = 1/x, so x^(-3/2) = y/x = y * y² = y³.
9656 // grad_x = -0.5 * upstream * y³.
9657 // Reuses the forward output id for y; never touches
9658 // x directly (avoids the divide-by-zero singularity
9659 // that the obvious `-0.5 * upstream * y / x` form
9660 // would have).
9661 let x = inputs[0];
9662 let x_shape = node_shape(&graph_handle, x);
9663 let dtype = node_dtype(&graph_handle, x);
9664 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
9665 let y_cu = push_node(
9666 &graph_handle,
9667 Op::Mul,
9668 vec![id, y_sq],
9669 x_shape.clone(),
9670 dtype,
9671 );
9672 let scaled = push_node(
9673 &graph_handle,
9674 Op::MulScalar(-0.5),
9675 vec![y_cu],
9676 x_shape.clone(),
9677 dtype,
9678 );
9679 let grad_x =
9680 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
9681 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9682 }
9683 Op::Pow => {
9684 // y = pow(a, b).
9685 // d/da = b * pow(a, b-1)
9686 // d/db = y * ln(a)
9687 // grad_a = upstream * b * pow(a, b-1)
9688 // grad_b = upstream * y * ln(a)
9689 // The forward output `id` IS y; we reuse it.
9690 let a = inputs[0];
9691 let b = inputs[1];
9692 let a_shape = node_shape(&graph_handle, a);
9693 let dtype = node_dtype(&graph_handle, a);
9694 // d/da branch: pow(a, b - 1)
9695 let b_minus_one = push_node(
9696 &graph_handle,
9697 Op::AddScalar(-1.0),
9698 vec![b],
9699 a_shape.clone(),
9700 dtype,
9701 );
9702 let pow_a_bm1 = push_node(
9703 &graph_handle,
9704 Op::Pow,
9705 vec![a, b_minus_one],
9706 a_shape.clone(),
9707 dtype,
9708 );
9709 let b_times_pow = push_node(
9710 &graph_handle,
9711 Op::Mul,
9712 vec![b, pow_a_bm1],
9713 a_shape.clone(),
9714 dtype,
9715 );
9716 let grad_a = push_node(
9717 &graph_handle,
9718 Op::Mul,
9719 vec![up_id, b_times_pow],
9720 a_shape.clone(),
9721 dtype,
9722 );
9723 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
9724 // d/db branch: y * ln(a)
9725 let log_a = push_node(&graph_handle, Op::Log, vec![a], a_shape.clone(), dtype);
9726 let y_log_a = push_node(
9727 &graph_handle,
9728 Op::Mul,
9729 vec![id, log_a],
9730 a_shape.clone(),
9731 dtype,
9732 );
9733 let grad_b =
9734 push_node(&graph_handle, Op::Mul, vec![up_id, y_log_a], a_shape, dtype);
9735 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
9736 }
9737 Op::Gelu => {
9738 // y = 0.5 * x * (1 + erf(x/√2)).
9739 // dy/dx = Φ(x) + x · φ(x)
9740 // = 0.5 * (1 + erf(x/√2))
9741 // + x * (1/√(2π)) * exp(-x²/2)
9742 // where Φ is the standard-normal CDF (= y/x for x≠0;
9743 // we recompute it explicitly so the backward stays
9744 // safe at x=0) and φ is the PDF.
9745 //
9746 // Chain (12 nodes):
9747 // x_over_sqrt2 = MulScalar(1/√2)(x)
9748 // erf_arg = Erf(x_over_sqrt2)
9749 // plus_one = AddScalar(1.0)(erf_arg)
9750 // cdf_term = MulScalar(0.5)(plus_one)
9751 // x_sq = Sqr(x)
9752 // half_x_sq = MulScalar(0.5)(x_sq)
9753 // neg_half_x_sq= Neg(half_x_sq)
9754 // exp_term = Exp(neg_half_x_sq)
9755 // phi = MulScalar(1/√(2π))(exp_term)
9756 // pdf_term = Mul(x, phi)
9757 // d_gelu = Add(cdf_term, pdf_term)
9758 // grad_x = Mul(upstream, d_gelu)
9759 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
9760 // 1/√(2π) = 0.39894228040143267793994605993...
9761 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
9762 let x = inputs[0];
9763 let x_shape = node_shape(&graph_handle, x);
9764 let dtype = node_dtype(&graph_handle, x);
9765 // CDF half: 0.5 * (1 + erf(x/√2)).
9766 let x_over_sqrt2 = push_node(
9767 &graph_handle,
9768 Op::MulScalar(INV_SQRT_2),
9769 vec![x],
9770 x_shape.clone(),
9771 dtype,
9772 );
9773 let erf_arg = push_node(
9774 &graph_handle,
9775 Op::Erf,
9776 vec![x_over_sqrt2],
9777 x_shape.clone(),
9778 dtype,
9779 );
9780 let plus_one = push_node(
9781 &graph_handle,
9782 Op::AddScalar(1.0),
9783 vec![erf_arg],
9784 x_shape.clone(),
9785 dtype,
9786 );
9787 let cdf_term = push_node(
9788 &graph_handle,
9789 Op::MulScalar(0.5),
9790 vec![plus_one],
9791 x_shape.clone(),
9792 dtype,
9793 );
9794 // PDF half: x * (1/√(2π)) * exp(-x²/2).
9795 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
9796 let half_x_sq = push_node(
9797 &graph_handle,
9798 Op::MulScalar(0.5),
9799 vec![x_sq],
9800 x_shape.clone(),
9801 dtype,
9802 );
9803 let neg_half_x_sq = push_node(
9804 &graph_handle,
9805 Op::Neg,
9806 vec![half_x_sq],
9807 x_shape.clone(),
9808 dtype,
9809 );
9810 let exp_term = push_node(
9811 &graph_handle,
9812 Op::Exp,
9813 vec![neg_half_x_sq],
9814 x_shape.clone(),
9815 dtype,
9816 );
9817 let phi = push_node(
9818 &graph_handle,
9819 Op::MulScalar(INV_SQRT_2PI),
9820 vec![exp_term],
9821 x_shape.clone(),
9822 dtype,
9823 );
9824 let pdf_term =
9825 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
9826 // Sum the two halves and apply upstream.
9827 let d_gelu = push_node(
9828 &graph_handle,
9829 Op::Add,
9830 vec![cdf_term, pdf_term],
9831 x_shape.clone(),
9832 dtype,
9833 );
9834 let grad_x =
9835 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
9836 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9837 }
9838 Op::Equal | Op::Ne | Op::Lt | Op::Le | Op::Gt | Op::Ge => {
9839 // Comparison family: handled by `NoGradientBinaryRule`
9840 // via `dispatch_gradient`. The `if let Some(grads) =
9841 // dispatch_gradient(...) { continue; }` block above
9842 // intercepts before we get here. This arm exists only
9843 // for exhaustiveness; it should be unreachable in
9844 // practice. Keeping it as a no-op rather than
9845 // `unreachable!()` defends against a future hand-edit
9846 // that removes the dispatcher arm by mistake — the
9847 // graph still terminates traversal cleanly.
9848 }
9849 Op::Cast(_) => {
9850 // Forward: y = cast(x, target_dtype).
9851 // Backward: dL/dx = cast(upstream, source_dtype).
9852 let x = inputs[0];
9853 let x_dtype = node_dtype(&graph_handle, x);
9854 let x_shape = node_shape(&graph_handle, x);
9855 let grad_x = push_node(
9856 &graph_handle,
9857 Op::Cast(x_dtype),
9858 vec![up_id],
9859 x_shape,
9860 x_dtype,
9861 );
9862 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9863 }
9864 Op::SumAll => {
9865 // Forward: y = sum(x), scalar.
9866 // Backward: dL/dx = broadcast_to(upstream, x.shape).
9867 let x = inputs[0];
9868 let x_shape = node_shape(&graph_handle, x);
9869 let dtype = node_dtype(&graph_handle, x);
9870 let grad_x = push_node(
9871 &graph_handle,
9872 Op::BroadcastTo(x_shape.clone()),
9873 vec![up_id],
9874 x_shape,
9875 dtype,
9876 );
9877 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9878 }
9879 Op::MeanAll => {
9880 // Forward: y = mean(x) = sum(x) / n, scalar.
9881 // Backward: dL/dx = broadcast_to(upstream / n, x.shape).
9882 // We build `ones / n` as a constant of shape x.shape
9883 // and multiply by broadcast_to(upstream, x.shape).
9884 // Simpler: broadcast upstream, then divide by an n-const.
9885 let x = inputs[0];
9886 let x_shape = node_shape(&graph_handle, x);
9887 let dtype = node_dtype(&graph_handle, x);
9888 let n_elem = x_shape.elem_count();
9889 let broadcast_up = push_node(
9890 &graph_handle,
9891 Op::BroadcastTo(x_shape.clone()),
9892 vec![up_id],
9893 x_shape.clone(),
9894 dtype,
9895 );
9896 let n_const =
9897 build_filled_const(&graph_handle, x_shape.clone(), dtype, n_elem as f64);
9898 let grad_x = push_node(
9899 &graph_handle,
9900 Op::Div,
9901 vec![broadcast_up, n_const],
9902 x_shape,
9903 dtype,
9904 );
9905 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9906 }
9907 Op::BroadcastTo(_) => {
9908 // Forward: y = broadcast_to(x, target).
9909 // Backward: dL/dx = reduce_sum_to(upstream, x.shape) —
9910 // sum away every dim that was expanded or newly added.
9911 let x = inputs[0];
9912 let x_shape = node_shape(&graph_handle, x);
9913 let dtype = node_dtype(&graph_handle, x);
9914 let grad_x = push_node(
9915 &graph_handle,
9916 Op::ReduceSumTo(x_shape.clone()),
9917 vec![up_id],
9918 x_shape,
9919 dtype,
9920 );
9921 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9922 }
9923 Op::Reshape(_) => {
9924 // Forward: y = reshape(x, target). Data unchanged.
9925 // Backward: reshape upstream back to x.shape.
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::Contiguize => {
9939 // Forward: y = contiguize(x). Identity at the
9940 // value level; only the layout differs. Backward:
9941 // pass upstream through unchanged. The
9942 // downstream `accumulate_grad` will sum this
9943 // into x's gradient regardless of x's own layout.
9944 let x = inputs[0];
9945 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
9946 }
9947 Op::Unsqueeze { dim: _ } => {
9948 // Forward: y = unsqueeze(x, dim) — inserts a size-1
9949 // axis without touching bytes. Backward: drop that
9950 // axis. Bytes are unchanged either direction; a
9951 // Reshape to x.shape is the simplest expression of
9952 // "same bytes, different rank" that the executor
9953 // handles natively.
9954 let x = inputs[0];
9955 let x_shape = node_shape(&graph_handle, x);
9956 let dtype = node_dtype(&graph_handle, x);
9957 let grad_x = push_node(
9958 &graph_handle,
9959 Op::Reshape(x_shape.clone()),
9960 vec![up_id],
9961 x_shape,
9962 dtype,
9963 );
9964 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9965 }
9966 Op::Squeeze { dim } => {
9967 // Forward: y = squeeze(x, dim) — drops a size-1 axis,
9968 // metadata-only. Backward: re-insert the axis at the
9969 // same position via Unsqueeze. Both directions are
9970 // metadata-only views (no bytes touched).
9971 let x = inputs[0];
9972 let x_shape = node_shape(&graph_handle, x);
9973 let dtype = node_dtype(&graph_handle, x);
9974 let grad_x = push_node(
9975 &graph_handle,
9976 Op::Unsqueeze { dim },
9977 vec![up_id],
9978 x_shape,
9979 dtype,
9980 );
9981 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9982 }
9983 Op::ReduceSumTo(_) => {
9984 // Forward: y = reduce_sum_to(x, target).
9985 // Backward: broadcast upstream back to x.shape.
9986 let x = inputs[0];
9987 let x_shape = node_shape(&graph_handle, x);
9988 let dtype = node_dtype(&graph_handle, x);
9989 let grad_x = push_node(
9990 &graph_handle,
9991 Op::BroadcastTo(x_shape.clone()),
9992 vec![up_id],
9993 x_shape,
9994 dtype,
9995 );
9996 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
9997 }
9998 Op::MaxAll | Op::MinAll => {
9999 // For y = max(x) (or min), the gradient is an
10000 // indicator at the argmax positions, distributed
10001 // across ties. Expressed without a dedicated argmax
10002 // op using the Step trick:
10003 //
10004 // broadcasted_y = broadcast_to(y, x.shape)
10005 // diff = broadcasted_y - x (for Max)
10006 // | x - broadcasted_y (for Min)
10007 // indicator = ones - step(diff)
10008 // grad_x = broadcast_to(upstream, x.shape) * indicator
10009 //
10010 // At argmax positions `diff == 0`, `step(0) == 0`, so
10011 // the indicator is 1. Elsewhere `diff > 0` so step is
10012 // 1 and the indicator is 0. Ties share the gradient.
10013 let x = inputs[0];
10014 let x_shape = node_shape(&graph_handle, x);
10015 let dtype = node_dtype(&graph_handle, x);
10016 let is_max = matches!(op, Op::MaxAll);
10017 let broadcasted_y = push_node(
10018 &graph_handle,
10019 Op::BroadcastTo(x_shape.clone()),
10020 vec![id],
10021 x_shape.clone(),
10022 dtype,
10023 );
10024 let diff = if is_max {
10025 push_node(
10026 &graph_handle,
10027 Op::Sub,
10028 vec![broadcasted_y, x],
10029 x_shape.clone(),
10030 dtype,
10031 )
10032 } else {
10033 push_node(
10034 &graph_handle,
10035 Op::Sub,
10036 vec![x, broadcasted_y],
10037 x_shape.clone(),
10038 dtype,
10039 )
10040 };
10041 let step_diff =
10042 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10043 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10044 let indicator = push_node(
10045 &graph_handle,
10046 Op::Sub,
10047 vec![ones, step_diff],
10048 x_shape.clone(),
10049 dtype,
10050 );
10051 let broadcast_up = push_node(
10052 &graph_handle,
10053 Op::BroadcastTo(x_shape.clone()),
10054 vec![up_id],
10055 x_shape.clone(),
10056 dtype,
10057 );
10058 let grad_x = push_node(
10059 &graph_handle,
10060 Op::Mul,
10061 vec![broadcast_up, indicator],
10062 x_shape,
10063 dtype,
10064 );
10065 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10066 }
10067 Op::SumDim(dim) => {
10068 // Insert a size-1 at `dim` via reshape, then broadcast
10069 // back to x.shape.
10070 let x = inputs[0];
10071 let x_shape = node_shape(&graph_handle, x);
10072 let dtype = node_dtype(&graph_handle, x);
10073 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10074 let reshaped = push_node(
10075 &graph_handle,
10076 Op::Reshape(keepdim_shape.clone()),
10077 vec![up_id],
10078 keepdim_shape,
10079 dtype,
10080 );
10081 let grad_x = push_node(
10082 &graph_handle,
10083 Op::BroadcastTo(x_shape.clone()),
10084 vec![reshaped],
10085 x_shape,
10086 dtype,
10087 );
10088 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10089 }
10090 Op::MeanDim(dim) => {
10091 // SumDim-style backward, then divide by the reduced dim size.
10092 let x = inputs[0];
10093 let x_shape = node_shape(&graph_handle, x);
10094 let dtype = node_dtype(&graph_handle, x);
10095 let reduced_size = x_shape.dims()[dim];
10096 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10097 let reshaped = push_node(
10098 &graph_handle,
10099 Op::Reshape(keepdim_shape.clone()),
10100 vec![up_id],
10101 keepdim_shape,
10102 dtype,
10103 );
10104 let broadcast = push_node(
10105 &graph_handle,
10106 Op::BroadcastTo(x_shape.clone()),
10107 vec![reshaped],
10108 x_shape.clone(),
10109 dtype,
10110 );
10111 let n_const = build_filled_const(
10112 &graph_handle,
10113 x_shape.clone(),
10114 dtype,
10115 reduced_size as f64,
10116 );
10117 let grad_x = push_node(
10118 &graph_handle,
10119 Op::Div,
10120 vec![broadcast, n_const],
10121 x_shape,
10122 dtype,
10123 );
10124 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10125 }
10126 Op::MaxDim(dim) | Op::MinDim(dim) => {
10127 // Same indicator trick as MaxAll/MinAll, but apply the
10128 // "reshape to keepdim then broadcast" pattern to both
10129 // the forward output and upstream before multiplying.
10130 let x = inputs[0];
10131 let x_shape = node_shape(&graph_handle, x);
10132 let dtype = node_dtype(&graph_handle, x);
10133 let is_max = matches!(op, Op::MaxDim(_));
10134 let keepdim_shape = reshape_to_keepdim(x_shape.dims(), dim);
10135 let y_keepdim = push_node(
10136 &graph_handle,
10137 Op::Reshape(keepdim_shape.clone()),
10138 vec![id],
10139 keepdim_shape.clone(),
10140 dtype,
10141 );
10142 let broadcasted_y = push_node(
10143 &graph_handle,
10144 Op::BroadcastTo(x_shape.clone()),
10145 vec![y_keepdim],
10146 x_shape.clone(),
10147 dtype,
10148 );
10149 let diff = if is_max {
10150 push_node(
10151 &graph_handle,
10152 Op::Sub,
10153 vec![broadcasted_y, x],
10154 x_shape.clone(),
10155 dtype,
10156 )
10157 } else {
10158 push_node(
10159 &graph_handle,
10160 Op::Sub,
10161 vec![x, broadcasted_y],
10162 x_shape.clone(),
10163 dtype,
10164 )
10165 };
10166 let step_diff =
10167 push_node(&graph_handle, Op::Step, vec![diff], x_shape.clone(), dtype);
10168 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
10169 let indicator = push_node(
10170 &graph_handle,
10171 Op::Sub,
10172 vec![ones, step_diff],
10173 x_shape.clone(),
10174 dtype,
10175 );
10176 let up_keepdim = push_node(
10177 &graph_handle,
10178 Op::Reshape(keepdim_shape.clone()),
10179 vec![up_id],
10180 keepdim_shape,
10181 dtype,
10182 );
10183 let broadcast_up = push_node(
10184 &graph_handle,
10185 Op::BroadcastTo(x_shape.clone()),
10186 vec![up_keepdim],
10187 x_shape.clone(),
10188 dtype,
10189 );
10190 let grad_x = push_node(
10191 &graph_handle,
10192 Op::Mul,
10193 vec![broadcast_up, indicator],
10194 x_shape,
10195 dtype,
10196 );
10197 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10198 }
10199 // Phase 7.6 step 5 (2026-05-11): the legacy
10200 // `Op::SoftmaxLastDim` / `Op::LayerNormLastDim` /
10201 // `Op::RmsNormLastDim` / `Op::Rope` /
10202 // `Op::Conv2D` / `Op::FusedLinear` arms have been
10203 // dropped together with the variants themselves; the
10204 // `Op::Fused(fid, _)` arm below dispatches per id and
10205 // is the single source of truth for migrated forward
10206 // ops' backward.
10207 Op::ArgMaxDim(_) | Op::ArgMinDim(_) => {
10208 // Argmax/argmin produce integer indices, which are
10209 // non-differentiable. Panic rather than silently
10210 // zero-propagating — if the user has one of these in
10211 // their differentiated graph, they've almost
10212 // certainly made a mistake.
10213 panic!(
10214 "backward: ArgMaxDim/ArgMinDim produce integer \
10215 indices and cannot be differentiated through. \
10216 Use MaxDim/MinDim if you want a differentiable \
10217 selection."
10218 );
10219 }
10220 Op::ReduceMaxTo(_) => {
10221 // Forward: y = reduce_max_to(x, target).
10222 // Backward: route upstream to position(s) where
10223 // x equals its per-window max via the fused
10224 // backward helper Op::Fused(REDUCE_MAX_TO_BACKWARD,
10225 // _) (takes (x, upstream) and emits grad_x of
10226 // x.shape). Tied maxes share the gradient equally
10227 // (fair-share subgradient). Note this is the
10228 // backward of a *primitive* (Op::ReduceMaxTo),
10229 // not a fused forward — no BackwardKind::Fused
10230 // edge in the registry drives this; the explicit
10231 // emission is the source of truth.
10232 let x = inputs[0];
10233 let x_shape = node_shape(&graph_handle, x);
10234 let dtype = node_dtype(&graph_handle, x);
10235 let grad_x = push_node(
10236 &graph_handle,
10237 Op::Fused(
10238 crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD,
10239 crate::registry::FusedOpParams::ReduceMaxToBackward,
10240 ),
10241 vec![x, up_id],
10242 x_shape,
10243 dtype,
10244 );
10245 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10246 }
10247 // Phase 7.6 step 5 (final, 2026-05-11): legacy
10248 // `Op::QMatMul` arm dropped with the variant; QMatMul
10249 // backward panics via the Op::Fused arm below.
10250 // Phase 7.6 step 5 (2026-05-11): the legacy
10251 // `Op::SoftmaxLastDimBackward | Op::LayerNormLastDimBackward |
10252 // Op::RmsNormLastDimBackward | Op::ReduceMaxToBackward`
10253 // higher-order panic arm has been dropped together
10254 // with the variants themselves. The Op::Fused arm
10255 // below panics for those four ids.
10256 Op::IndexSelect { dim } => {
10257 // Forward: out = index_select(data, dim, indices).
10258 // Backward: grad_data = index_add(zeros_like(data), dim, indices, upstream).
10259 let data = inputs[0];
10260 let idx = inputs[1];
10261 let data_shape = node_shape(&graph_handle, data);
10262 let dtype = node_dtype(&graph_handle, data);
10263 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10264 let grad_data = push_node(
10265 &graph_handle,
10266 Op::IndexAdd { dim },
10267 vec![zeros, idx, up_id],
10268 data_shape,
10269 dtype,
10270 );
10271 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10272 // Index tensor is itself non-differentiable (integer dtype).
10273 }
10274 Op::Gather { dim } => {
10275 // Forward: out = gather(data, dim, indices).
10276 // Backward: grad_data = scatter_add(zeros_like(data), dim, indices, upstream).
10277 let data = inputs[0];
10278 let idx = inputs[1];
10279 let data_shape = node_shape(&graph_handle, data);
10280 let dtype = node_dtype(&graph_handle, data);
10281 let zeros = build_filled_const(&graph_handle, data_shape.clone(), dtype, 0.0);
10282 let grad_data = push_node(
10283 &graph_handle,
10284 Op::ScatterAdd { dim },
10285 vec![zeros, idx, up_id],
10286 data_shape,
10287 dtype,
10288 );
10289 accumulate_grad(&mut upstream, data, grad_data, &graph_handle);
10290 }
10291 Op::IndexAdd { dim } => {
10292 // Forward: out = index_add(base, dim, indices, src).
10293 // Backward:
10294 // grad_base = upstream (pass-through — base flows
10295 // through the non-indexed positions and
10296 // the accumulated positions don't zero
10297 // it out, they add to it)
10298 // grad_src = index_select(upstream, dim, indices)
10299 // (the pieces of upstream that came from
10300 // src in the forward).
10301 let base = inputs[0];
10302 let idx = inputs[1];
10303 let src = inputs[2];
10304 let src_shape = node_shape(&graph_handle, src);
10305 let dtype = node_dtype(&graph_handle, src);
10306 // grad_base: upstream passes through.
10307 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10308 // grad_src: select from upstream at the indices.
10309 let grad_src = push_node(
10310 &graph_handle,
10311 Op::IndexSelect { dim },
10312 vec![up_id, idx],
10313 src_shape,
10314 dtype,
10315 );
10316 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10317 }
10318 Op::Concat { dim } => {
10319 // Forward: out = concat(inputs.., dim).
10320 // Backward: split upstream along `dim` into one slice per
10321 // input at the cumulative offset, routing each slice to its
10322 // input. N-ary (unroll_scan stacks N per-step ys into a
10323 // single Concat; the SSM/Hopfield BPTT unroll relies on
10324 // this). Duplicate inputs accumulate via accumulate_grad.
10325 let mut start = 0usize;
10326 for &inp in &inputs {
10327 let in_shape = node_shape(&graph_handle, inp);
10328 let dtype = node_dtype(&graph_handle, inp);
10329 let len = in_shape.dims()[dim];
10330 let grad_in = push_node(
10331 &graph_handle,
10332 Op::Slice { dim, start, len },
10333 vec![up_id],
10334 in_shape,
10335 dtype,
10336 );
10337 accumulate_grad(&mut upstream, inp, grad_in, &graph_handle);
10338 start += len;
10339 }
10340 }
10341 Op::Slice { dim, start, len: _ } => {
10342 // Forward: out = slice(x, dim, start, len).
10343 // Backward: build a zeros tensor of x.shape, then
10344 // scatter the upstream into the slice range. We use
10345 // a concat of three pieces: left zeros, upstream,
10346 // right zeros (along `dim`).
10347 let x = inputs[0];
10348 let x_shape = node_shape(&graph_handle, x);
10349 let dtype = node_dtype(&graph_handle, x);
10350 let x_dims = x_shape.dims();
10351 let dim_size = x_dims[dim];
10352 let up_len = x_dims[dim].min(node_shape(&graph_handle, up_id).dims()[dim]);
10353 let left_len = start;
10354 let right_len = dim_size - start - up_len;
10355 // Build left zero pad if needed.
10356 let mut pieces: Vec<NodeId> = Vec::new();
10357 if left_len > 0 {
10358 let mut left_dims: Vec<usize> = x_dims.to_vec();
10359 left_dims[dim] = left_len;
10360 let left_shape = Shape::from_dims(&left_dims);
10361 pieces.push(build_filled_const(&graph_handle, left_shape, dtype, 0.0));
10362 }
10363 pieces.push(up_id);
10364 if right_len > 0 {
10365 let mut right_dims: Vec<usize> = x_dims.to_vec();
10366 right_dims[dim] = right_len;
10367 let right_shape = Shape::from_dims(&right_dims);
10368 pieces.push(build_filled_const(&graph_handle, right_shape, dtype, 0.0));
10369 }
10370 // Fold concat-left-to-right.
10371 let mut current = pieces[0];
10372 let mut current_dims: Vec<usize> = {
10373 let n = graph_handle.read().unwrap();
10374 n.node(current).shape.dims().to_vec()
10375 };
10376 for &next in &pieces[1..] {
10377 let next_dims: Vec<usize> = {
10378 let n = graph_handle.read().unwrap();
10379 n.node(next).shape.dims().to_vec()
10380 };
10381 let mut combined = current_dims.clone();
10382 combined[dim] = current_dims[dim] + next_dims[dim];
10383 let combined_shape = Shape::from_dims(&combined);
10384 current = push_node(
10385 &graph_handle,
10386 Op::Concat { dim },
10387 vec![current, next],
10388 combined_shape,
10389 dtype,
10390 );
10391 current_dims = combined;
10392 }
10393 accumulate_grad(&mut upstream, x, current, &graph_handle);
10394 }
10395 Op::AddScalar(_) => {
10396 // y = x + c, dy/dx = 1. Upstream passes through.
10397 let x = inputs[0];
10398 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10399 }
10400 Op::MulScalar(c) => {
10401 // y = x * c, dy/dx = c. Multiply upstream by c via
10402 // another MulScalar node.
10403 let x = inputs[0];
10404 let x_shape = node_shape(&graph_handle, x);
10405 let dtype = node_dtype(&graph_handle, x);
10406 let grad_x =
10407 push_node(&graph_handle, Op::MulScalar(c), vec![up_id], x_shape, dtype);
10408 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10409 }
10410 Op::PowI(n) => {
10411 // y = x^n, dy/dx = n * x^(n-1).
10412 // grad_x = upstream * n * x^(n-1). Emitted as a
10413 // single fused PowIBackward node; the executor
10414 // routes it to baracuda's `unary_powi_backward_*`
10415 // kernel (alpha.31) on CUDA, or falls back to the
10416 // primitive decomposition (PowI(n-1) → MulScalar →
10417 // Mul) on backends that haven't registered the
10418 // fused kernel.
10419 let x = inputs[0];
10420 let x_shape = node_shape(&graph_handle, x);
10421 let dtype = node_dtype(&graph_handle, x);
10422 let grad_x = push_node(
10423 &graph_handle,
10424 Op::Fused(
10425 crate::registry::FusedOps::POWI_BACKWARD,
10426 crate::registry::FusedOpParams::PowIBackward { exp: n },
10427 ),
10428 vec![x, up_id],
10429 x_shape,
10430 dtype,
10431 );
10432 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10433 }
10434 Op::Clamp { min, max } => {
10435 // Subgradient: 1 where min <= x <= max, 0 elsewhere.
10436 // Expressed via (step(x - min) - step(x - max))
10437 // which is 1 in the interior (x > min and x <= max...
10438 // actually step(0) = 0, so the right end is a bit
10439 // tricky). For a reference implementation the
10440 // simplest approach is a dedicated "clamp backward"
10441 // indicator. We build it out of the existing ops:
10442 //
10443 // lower_ok = step(x - min) // 1 where x > min
10444 // upper_ok = step(max - x) // 1 where x < max
10445 // indicator = lower_ok * upper_ok
10446 // grad_x = upstream * indicator
10447 //
10448 // This underestimates the gradient on the exact
10449 // boundary by a measure-zero amount — standard.
10450 let x = inputs[0];
10451 let x_shape = node_shape(&graph_handle, x);
10452 let dtype = node_dtype(&graph_handle, x);
10453 let min_shifted = push_node(
10454 &graph_handle,
10455 Op::AddScalar(-min),
10456 vec![x],
10457 x_shape.clone(),
10458 dtype,
10459 );
10460 let lower_ok = push_node(
10461 &graph_handle,
10462 Op::Step,
10463 vec![min_shifted],
10464 x_shape.clone(),
10465 dtype,
10466 );
10467 let max_minus_x = push_node(
10468 &graph_handle,
10469 Op::MulScalar(-1.0),
10470 vec![x],
10471 x_shape.clone(),
10472 dtype,
10473 );
10474 let max_minus_x = push_node(
10475 &graph_handle,
10476 Op::AddScalar(max),
10477 vec![max_minus_x],
10478 x_shape.clone(),
10479 dtype,
10480 );
10481 let upper_ok = push_node(
10482 &graph_handle,
10483 Op::Step,
10484 vec![max_minus_x],
10485 x_shape.clone(),
10486 dtype,
10487 );
10488 let indicator = push_node(
10489 &graph_handle,
10490 Op::Mul,
10491 vec![lower_ok, upper_ok],
10492 x_shape.clone(),
10493 dtype,
10494 );
10495 let grad_x = push_node(
10496 &graph_handle,
10497 Op::Mul,
10498 vec![up_id, indicator],
10499 x_shape,
10500 dtype,
10501 );
10502 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10503 }
10504 Op::Maximum => {
10505 // y_i = max(a_i, b_i). Gradient flows to whichever
10506 // input was the max at that position:
10507 // mask_a = step(a - b) (1 where a > b, else 0)
10508 // mask_b = 1 - mask_a (approximately — at ties
10509 // gradient goes to b due to
10510 // step(0) = 0)
10511 // grad_a = upstream * mask_a
10512 // grad_b = upstream * mask_b
10513 let a = inputs[0];
10514 let b = inputs[1];
10515 let shape = node_shape(&graph_handle, a);
10516 let dtype = node_dtype(&graph_handle, a);
10517 let diff = push_node(&graph_handle, Op::Sub, vec![a, b], shape.clone(), dtype);
10518 let mask_a =
10519 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10520 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10521 let mask_b = push_node(
10522 &graph_handle,
10523 Op::Sub,
10524 vec![ones, mask_a],
10525 shape.clone(),
10526 dtype,
10527 );
10528 let grad_a = push_node(
10529 &graph_handle,
10530 Op::Mul,
10531 vec![up_id, mask_a],
10532 shape.clone(),
10533 dtype,
10534 );
10535 let grad_b =
10536 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10537 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10538 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10539 }
10540 Op::Minimum => {
10541 // Symmetric to Maximum. mask_a = step(b - a).
10542 let a = inputs[0];
10543 let b = inputs[1];
10544 let shape = node_shape(&graph_handle, a);
10545 let dtype = node_dtype(&graph_handle, a);
10546 let diff = push_node(&graph_handle, Op::Sub, vec![b, a], shape.clone(), dtype);
10547 let mask_a =
10548 push_node(&graph_handle, Op::Step, vec![diff], shape.clone(), dtype);
10549 let ones = build_ones(&graph_handle, shape.clone(), dtype);
10550 let mask_b = push_node(
10551 &graph_handle,
10552 Op::Sub,
10553 vec![ones, mask_a],
10554 shape.clone(),
10555 dtype,
10556 );
10557 let grad_a = push_node(
10558 &graph_handle,
10559 Op::Mul,
10560 vec![up_id, mask_a],
10561 shape.clone(),
10562 dtype,
10563 );
10564 let grad_b =
10565 push_node(&graph_handle, Op::Mul, vec![up_id, mask_b], shape, dtype);
10566 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10567 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10568 }
10569 Op::ScatterAdd { dim } => {
10570 // Forward: out = scatter_add(base, dim, indices, src).
10571 // Backward:
10572 // grad_base = upstream (pass-through)
10573 // grad_src = gather(upstream, dim, indices)
10574 let base = inputs[0];
10575 let idx = inputs[1];
10576 let src = inputs[2];
10577 let src_shape = node_shape(&graph_handle, src);
10578 let dtype = node_dtype(&graph_handle, src);
10579 accumulate_grad(&mut upstream, base, up_id, &graph_handle);
10580 let grad_src = push_node(
10581 &graph_handle,
10582 Op::Gather { dim },
10583 vec![up_id, idx],
10584 src_shape,
10585 dtype,
10586 );
10587 accumulate_grad(&mut upstream, src, grad_src, &graph_handle);
10588 }
10589 Op::Copy { .. } => {
10590 // Forward: out = copy(x, target). Backward: the
10591 // gradient flows back to `x`'s original device, so
10592 // the reverse would be another Copy. The source
10593 // device is x's residency — we don't have the typed
10594 // "where was x?" here without tracking it, so we
10595 // fall back to the graph's placement hint on x (if
10596 // any) or trust the scheduler to re-insert the
10597 // correct copy during Phase 4. For Phase 3 we
10598 // assume inference-only use and pass upstream through.
10599 let x = inputs[0];
10600 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10601 }
10602 Op::Release => {
10603 // Release has no data output and no gradient to
10604 // propagate. Input is destroyed; any downstream
10605 // node that needs gradient through the original
10606 // tensor must get it from a sibling Copy's backward
10607 // path, not this one.
10608 }
10609 Op::Move { .. } => {
10610 // Move is Copy + destroy-source. For backward,
10611 // treat it the same as Copy — gradient flows back
10612 // through the move. The Phase 3-style assumption
10613 // still applies: we pass upstream through and rely
10614 // on the scheduler to re-insert the correct reverse
10615 // transfer in a training pass. For inference-only
10616 // use (the current case), this is a no-op.
10617 let x = inputs[0];
10618 accumulate_grad(&mut upstream, x, up_id, &graph_handle);
10619 }
10620 Op::WriteSlice { .. } => {
10621 // KV-cache writes are forward-only — the slab being
10622 // written *into* gets mutated in place, and the
10623 // source slab is read non-destructively. There is
10624 // no meaningful gradient through a mutating write
10625 // in fuel's tape-based autograd model. If a use
10626 // case needs differentiable scatter, the gradient
10627 // path is a `Gather` (read the slab back) plus an
10628 // accumulating `IndexAdd` on the destination —
10629 // express that explicitly in forward.
10630 panic!(
10631 "NodeHandle::backward: Op::WriteSlice is non-differentiable. \
10632 Use Gather + IndexAdd if you need a differentiable scatter."
10633 );
10634 }
10635 Op::WriteSliceRotating { .. } => {
10636 // Same forward-only contract as WriteSlice — the
10637 // ring buffer's bytes are mutated in place at a
10638 // dynamic offset. Sliding-window KV caches don't
10639 // need a gradient path; a differentiable scatter
10640 // is expressible as Gather + IndexAdd in forward.
10641 panic!(
10642 "NodeHandle::backward: Op::WriteSliceRotating is non-differentiable. \
10643 Use Gather + IndexAdd if you need a differentiable scatter."
10644 );
10645 }
10646 Op::WriteSliceDoff { .. } => {
10647 // Forward-only, like WriteSlice/WriteSliceRotating —
10648 // the KV-cache buffer is mutated in place at a
10649 // device-resident offset. Decode-time append; no
10650 // gradient path.
10651 panic!(
10652 "NodeHandle::backward: Op::WriteSliceDoff is non-differentiable. \
10653 Use Gather + IndexAdd if you need a differentiable scatter."
10654 );
10655 }
10656 // Phase 7.6 step 5 (2026-05-11): the legacy
10657 // `Op::Conv2D { stride, padding, groups }` backward
10658 // arm has been dropped together with the variant;
10659 // `Op::Fused(CONV2D, _)` below carries the full
10660 // backward logic (including the inner dW Conv2D
10661 // emission, which itself goes through Op::Fused).
10662 // Phase 7.6 step 4 (final): the builders for
10663 // ConvTranspose2D, FlashAttn, and PagedAttn now emit
10664 // `Op::Fused(<id>, _)`; these legacy backward arms
10665 // still fire for direct legacy-variant constructions
10666 // Phase 7.6 step 5 (final, 2026-05-11): the legacy
10667 // `Op::ConvTranspose2D` / `Op::FlashAttn` /
10668 // `Op::PagedAttn` / `Op::FusedLinear` backward arms
10669 // have all been dropped together with the variants;
10670 // `Op::Fused(<id>, _)` below panics for each id.
10671 Op::Fused(fid, params) => {
10672 // Per-id backward dispatch. Each migrated fused op
10673 // gets a branch here that emits the appropriate
10674 // gradient subgraph.
10675 if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM {
10676 // grad_x = softmax_last_dim_backward(y, upstream).
10677 // Phase 7.6 step 4 (backward-helper batch):
10678 // emits Op::Fused(SOFTMAX_LAST_DIM_BACKWARD, _)
10679 // — the architecturally-correct registry form,
10680 // matching the BackwardKind::Fused edge on
10681 // SOFTMAX_LAST_DIM's entry.
10682 let x = inputs[0];
10683 let y_shape = node_shape(&graph_handle, id);
10684 let dtype = node_dtype(&graph_handle, id);
10685 let grad_x = push_node(
10686 &graph_handle,
10687 Op::Fused(
10688 crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
10689 crate::registry::FusedOpParams::SoftmaxLastDimBackward,
10690 ),
10691 vec![id, up_id],
10692 y_shape,
10693 dtype,
10694 );
10695 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10696 } else if fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM {
10697 // grad_x = layer_norm_last_dim_backward(x, upstream, eps).
10698 // Phase 7.6 step 4 (backward-helper batch): emits
10699 // registry form Op::Fused(LAYER_NORM_LAST_DIM_BACKWARD, _).
10700 let eps = match params {
10701 crate::registry::FusedOpParams::LayerNormLastDim { eps } => eps,
10702 _ => panic!(
10703 "NodeHandle::backward: Op::Fused(LAYER_NORM_LAST_DIM, _) \
10704 expected FusedOpParams::LayerNormLastDim, got {params:?}",
10705 ),
10706 };
10707 let x = inputs[0];
10708 let x_shape = node_shape(&graph_handle, x);
10709 let dtype = node_dtype(&graph_handle, x);
10710 let grad_x = push_node(
10711 &graph_handle,
10712 Op::Fused(
10713 crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
10714 crate::registry::FusedOpParams::LayerNormLastDimBackward { eps },
10715 ),
10716 vec![x, up_id],
10717 x_shape,
10718 dtype,
10719 );
10720 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10721 } else if fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM {
10722 // grad_x = rms_norm_last_dim_backward(x, upstream, eps).
10723 // Phase 7.6 step 4 (backward-helper batch): emits
10724 // registry form Op::Fused(RMS_NORM_LAST_DIM_BACKWARD, _).
10725 let eps = match params {
10726 crate::registry::FusedOpParams::RmsNormLastDim { eps } => eps,
10727 _ => panic!(
10728 "NodeHandle::backward: Op::Fused(RMS_NORM_LAST_DIM, _) \
10729 expected FusedOpParams::RmsNormLastDim, got {params:?}",
10730 ),
10731 };
10732 let x = inputs[0];
10733 let x_shape = node_shape(&graph_handle, x);
10734 let dtype = node_dtype(&graph_handle, x);
10735 let grad_x = push_node(
10736 &graph_handle,
10737 Op::Fused(
10738 crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
10739 crate::registry::FusedOpParams::RmsNormLastDimBackward { eps },
10740 ),
10741 vec![x, up_id],
10742 x_shape,
10743 dtype,
10744 );
10745 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10746 } else if fid == crate::registry::FusedOps::ROPE {
10747 // grad_x = rope(upstream, cos, -sin) — same
10748 // formula as the legacy Op::Rope arm above.
10749 // Emit the registry form for the backward
10750 // Rope node so the gradient subgraph routes
10751 // through the same Op::Fused dispatch as the
10752 // forward.
10753 let x = inputs[0];
10754 let cos = inputs[1];
10755 let sin = inputs[2];
10756 let x_shape = node_shape(&graph_handle, x);
10757 let sin_shape = node_shape(&graph_handle, sin);
10758 let dtype = node_dtype(&graph_handle, x);
10759 let neg_sin =
10760 push_node(&graph_handle, Op::Neg, vec![sin], sin_shape, dtype);
10761 let grad_x = push_node(
10762 &graph_handle,
10763 Op::Fused(
10764 crate::registry::FusedOps::ROPE,
10765 crate::registry::FusedOpParams::Rope,
10766 ),
10767 vec![up_id, cos, neg_sin],
10768 x_shape,
10769 dtype,
10770 );
10771 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10772 } else if fid == crate::registry::FusedOps::FUSED_LINEAR {
10773 // (a @ b) + bias backward — same three-grad
10774 // decomposition as the legacy Op::FusedLinear
10775 // arm above. We reuse MatMul backward (no
10776 // intermediate matmul output is cached, so the
10777 // grad computes from upstream + a, b directly).
10778 let a = inputs[0];
10779 let b = inputs[1];
10780 let bias = inputs[2];
10781 let a_shape = node_shape(&graph_handle, a);
10782 let b_shape = node_shape(&graph_handle, b);
10783 let bias_shape = node_shape(&graph_handle, bias);
10784 let dtype = node_dtype(&graph_handle, a);
10785 let b_t_shape = transposed_shape(&b_shape);
10786 let b_t =
10787 push_node(&graph_handle, Op::Transpose, vec![b], b_t_shape, dtype);
10788 let grad_a = push_node(
10789 &graph_handle,
10790 Op::MatMul,
10791 vec![up_id, b_t],
10792 a_shape.clone(),
10793 dtype,
10794 );
10795 let a_t_shape = transposed_shape(&a_shape);
10796 let a_t =
10797 push_node(&graph_handle, Op::Transpose, vec![a], a_t_shape, dtype);
10798 let grad_b =
10799 push_node(&graph_handle, Op::MatMul, vec![a_t, up_id], b_shape, dtype);
10800 let grad_bias = push_node(
10801 &graph_handle,
10802 Op::ReduceSumTo(bias_shape.clone()),
10803 vec![up_id],
10804 bias_shape,
10805 dtype,
10806 );
10807 accumulate_grad(&mut upstream, a, grad_a, &graph_handle);
10808 accumulate_grad(&mut upstream, b, grad_b, &graph_handle);
10809 accumulate_grad(&mut upstream, bias, grad_bias, &graph_handle);
10810 } else if fid == crate::registry::FusedOps::CONV2D {
10811 // Same backward formulation as the legacy
10812 // Op::Conv2D arm above. The inner Conv2D node
10813 // emitted for grad_w also goes through the
10814 // registry (Op::Fused(CONV2D, _)) so the
10815 // gradient subgraph routes consistently. The
10816 // ConvTranspose2D node stays as a primitive
10817 // variant until that op migrates in its own
10818 // step-4 commit.
10819 let (stride, padding, groups) = match params {
10820 crate::registry::FusedOpParams::Conv2D {
10821 stride,
10822 padding,
10823 groups,
10824 } => (stride, padding, groups),
10825 _ => panic!(
10826 "NodeHandle::backward: Op::Fused(CONV2D, _) \
10827 expected FusedOpParams::Conv2D, got {params:?}",
10828 ),
10829 };
10830 let x = inputs[0];
10831 let weight = inputs[1];
10832 let x_shape = node_shape(&graph_handle, x);
10833 let w_shape = node_shape(&graph_handle, weight);
10834 let dtype = node_dtype(&graph_handle, x);
10835
10836 // dX via transposed conv (see legacy arm for derivation).
10837 let x_dims = x_shape.dims();
10838 let w_dims = w_shape.dims();
10839 let dy_dims = node_shape(&graph_handle, id).dims().to_vec();
10840 let (sh, sw) = stride;
10841 let (ph, pw) = padding;
10842 let (kh, kw) = (w_dims[2], w_dims[3]);
10843 let (h_in, w_in) = (x_dims[2], x_dims[3]);
10844 let (dy_h, dy_w) = (dy_dims[2], dy_dims[3]);
10845 let base_h = (dy_h - 1) * sh + (kh - 1) + 1;
10846 let base_w = (dy_w - 1) * sw + (kw - 1) + 1;
10847 let want_h = h_in + 2 * ph;
10848 let want_w = w_in + 2 * pw;
10849 let out_pad_h = want_h.saturating_sub(base_h);
10850 let out_pad_w = want_w.saturating_sub(base_w);
10851 if groups != 1 {
10852 panic!(
10853 "NodeHandle::backward: Op::Fused(CONV2D) groups>1 \
10854 backward not yet implemented (got groups={groups}). \
10855 The stride/padding/groups=1 case is wired; grouped \
10856 backward needs a per-group weight reshape.",
10857 );
10858 }
10859 let perm_01 = vec![1usize, 0, 2, 3];
10860 // Phase 7.6 step 4 (final): emit registry form
10861 // for the inner dX node so the gradient subgraph
10862 // routes consistently through Op::Fused dispatch.
10863 let grad_x = push_node(
10864 &graph_handle,
10865 Op::Fused(
10866 crate::registry::FusedOps::CONV_TRANSPOSE2D,
10867 crate::registry::FusedOpParams::ConvTranspose2D {
10868 stride,
10869 padding,
10870 output_padding: (out_pad_h, out_pad_w),
10871 dilation: (1, 1),
10872 groups,
10873 },
10874 ),
10875 vec![up_id, weight],
10876 x_shape.clone(),
10877 dtype,
10878 );
10879 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
10880
10881 // dW via correlation expressed as a conv2d.
10882 if sh != 1 || sw != 1 {
10883 panic!(
10884 "NodeHandle::backward: Op::Fused(CONV2D) stride>1 \
10885 backward not yet implemented (got stride={stride:?}). \
10886 Conv2D needs a `dilation` field to express this \
10887 without composing extra ops.",
10888 );
10889 }
10890 let x_swapped_shape = {
10891 let d = x_dims;
10892 Shape::from_dims(&[d[1], d[0], d[2], d[3]])
10893 };
10894 let x_swapped = push_node(
10895 &graph_handle,
10896 Op::Permute(perm_01.clone()),
10897 vec![x],
10898 x_swapped_shape,
10899 dtype,
10900 );
10901 let dy_swapped_shape =
10902 Shape::from_dims(&[dy_dims[1], dy_dims[0], dy_dims[2], dy_dims[3]]);
10903 let dy_swapped = push_node(
10904 &graph_handle,
10905 Op::Permute(perm_01.clone()),
10906 vec![up_id],
10907 dy_swapped_shape,
10908 dtype,
10909 );
10910 let conv_out_shape =
10911 Shape::from_dims(&[w_dims[1], w_dims[0], w_dims[2], w_dims[3]]);
10912 let grad_w_pre_transpose = push_node(
10913 &graph_handle,
10914 Op::Fused(
10915 crate::registry::FusedOps::CONV2D,
10916 crate::registry::FusedOpParams::Conv2D {
10917 stride: (1, 1),
10918 padding,
10919 groups: 1,
10920 },
10921 ),
10922 vec![x_swapped, dy_swapped],
10923 conv_out_shape,
10924 dtype,
10925 );
10926 let grad_w = push_node(
10927 &graph_handle,
10928 Op::Permute(perm_01),
10929 vec![grad_w_pre_transpose],
10930 w_shape,
10931 dtype,
10932 );
10933 accumulate_grad(&mut upstream, weight, grad_w, &graph_handle);
10934
10935 // Bias (if present): sum dY over N, H, W via
10936 // ReduceSumTo([1, Cout, 1, 1]) then reshape to
10937 // [Cout]. Same path as the legacy arm.
10938 if inputs.len() >= 3 {
10939 let bias = inputs[2];
10940 let bias_shape = node_shape(&graph_handle, bias);
10941 let cout_4d = Shape::from_dims(&[1, dy_dims[1], 1, 1]);
10942 let reduced = push_node(
10943 &graph_handle,
10944 Op::ReduceSumTo(cout_4d.clone()),
10945 vec![up_id],
10946 cout_4d,
10947 dtype,
10948 );
10949 let grad_b = push_node(
10950 &graph_handle,
10951 Op::Reshape(bias_shape.clone()),
10952 vec![reduced],
10953 bias_shape,
10954 dtype,
10955 );
10956 accumulate_grad(&mut upstream, bias, grad_b, &graph_handle);
10957 }
10958 } else if fid == crate::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD
10959 || fid == crate::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD
10960 || fid == crate::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
10961 || fid == crate::registry::FusedOps::REDUCE_MAX_TO_BACKWARD
10962 {
10963 // Higher-order gradients through backward
10964 // helpers panic.
10965 panic!(
10966 "backward: higher-order gradients through \
10967 softmax/layer_norm/rms_norm/reduce_max_to backward \
10968 helpers are not yet supported in the MVP."
10969 );
10970 } else if fid == crate::registry::FusedOps::CONV_TRANSPOSE2D {
10971 // Higher-order grad of the transposed conv
10972 // isn't needed for Conv2D's backward (which
10973 // only consumes the forward output). Adding
10974 // it requires the same dilation-as-stride
10975 // trick as Conv2D's dW. Punt until a real
10976 // consumer asks for it.
10977 panic!(
10978 "NodeHandle::backward: ConvTranspose2D does \
10979 not yet have its own gradient rule \
10980 (only used in the forward path of \
10981 Conv2D's backward).",
10982 );
10983 } else if fid == crate::registry::FusedOps::FLASH_ATTN {
10984 // Emit three backward nodes: dQ via
10985 // FLASH_ATTN_BACKWARD_Q, dK via _K, dV via _V.
10986 // Each takes (q, k, v, dO, [alibi]) and
10987 // recomputes the softmax state independently
10988 // in CPU's math-definition path. GPU kernels
10989 // (when they ship) can fuse the recompute.
10990 let q = inputs[0];
10991 let k = inputs[1];
10992 let v = inputs[2];
10993 let alibi = inputs.get(3).copied();
10994 let q_shape = node_shape(&graph_handle, q);
10995 let k_shape = node_shape(&graph_handle, k);
10996 let v_shape = node_shape(&graph_handle, v);
10997 let dtype = node_dtype(&graph_handle, q);
10998 let (scale, causal, wl, wr, sc) = match params {
10999 crate::registry::FusedOpParams::FlashAttn {
11000 softmax_scale,
11001 causal,
11002 window_size_left,
11003 window_size_right,
11004 softcap,
11005 // Backward over the static (full-K) flash
11006 // only; the runtime-k_len capacity form is
11007 // forward-only (decode). k_len is ignored
11008 // here.
11009 k_len: _,
11010 } => (
11011 softmax_scale,
11012 causal,
11013 window_size_left,
11014 window_size_right,
11015 softcap,
11016 ),
11017 other => panic!(
11018 "NodeHandle::backward: FlashAttn node carries \
11019 unexpected params {other:?}",
11020 ),
11021 };
11022 let bw_params = crate::registry::FusedOpParams::FlashAttnBackward {
11023 softmax_scale: scale,
11024 causal,
11025 window_size_left: wl,
11026 window_size_right: wr,
11027 softcap: sc,
11028 };
11029 let mut bw_inputs = vec![q, k, v, up_id];
11030 if let Some(a) = alibi {
11031 bw_inputs.push(a);
11032 }
11033 let grad_q = push_node(
11034 &graph_handle,
11035 Op::Fused(
11036 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_Q,
11037 bw_params.clone(),
11038 ),
11039 bw_inputs.clone(),
11040 q_shape,
11041 dtype,
11042 );
11043 let grad_k = push_node(
11044 &graph_handle,
11045 Op::Fused(
11046 crate::registry::FusedOps::FLASH_ATTN_BACKWARD_K,
11047 bw_params.clone(),
11048 ),
11049 bw_inputs.clone(),
11050 k_shape,
11051 dtype,
11052 );
11053 let grad_v = push_node(
11054 &graph_handle,
11055 Op::Fused(crate::registry::FusedOps::FLASH_ATTN_BACKWARD_V, bw_params),
11056 bw_inputs,
11057 v_shape,
11058 dtype,
11059 );
11060 accumulate_grad(&mut upstream, q, grad_q, &graph_handle);
11061 accumulate_grad(&mut upstream, k, grad_k, &graph_handle);
11062 accumulate_grad(&mut upstream, v, grad_v, &graph_handle);
11063 } else if fid == crate::registry::FusedOps::PAGED_ATTN {
11064 // Paged attention is decode-side only by
11065 // construction (variable-length KV cache, no
11066 // training pass writes through it). No
11067 // gradient rule.
11068 panic!(
11069 "NodeHandle::backward: PagedAttn is \
11070 decode-only; no gradient rule exists.",
11071 );
11072 } else if fid == crate::registry::FusedOps::QMATMUL {
11073 // Quantized matmul: weights are frozen
11074 // bytes; activation gradient isn't
11075 // implemented today. Dequantize-then-matmul
11076 // is the workaround if differentiable
11077 // quantized inference is needed.
11078 panic!(
11079 "backward: QMatMul is not differentiable \
11080 (quantized weights are frozen). Use a \
11081 dequantize + standard matmul if you \
11082 need gradients through this input."
11083 );
11084 } else {
11085 panic!(
11086 "NodeHandle::backward: Op::Fused id {fid:?} has no \
11087 backward arm wired yet. This is a programming \
11088 bug — extend the match when the op migrates \
11089 to the registry.",
11090 );
11091 }
11092 }
11093 Op::Alloc { .. } => {
11094 // Op::Alloc is a source op (zero inputs) that
11095 // produces a fresh zero-init buffer. No upstream
11096 // gradient to propagate — the alloc's "input" is
11097 // the abstract notion of fresh memory, which has
11098 // no derivative. Mirrors Op::Const's treatment.
11099 // (Phase 3a of bridge-retirement; see
11100 // `WorkItemKind::Alloc` in fuel-storage.)
11101 }
11102 Op::ZeroFill => {
11103 // Op::ZeroFill writes deterministic constants
11104 // (zeros) to its input's bytes. The output is
11105 // a constant tensor; gradient w.r.t. it is
11106 // meaningless. Like Op::Const / Op::Alloc, no
11107 // gradient propagates back.
11108 }
11109 Op::ScatterIntoSlot { .. } => {
11110 // Item 4 IR-only scaffold — the backward graph
11111 // emits this op as the producer's gradient
11112 // assembler, but `ScatterIntoSlot` itself has no
11113 // backward (it's a structural op composing
11114 // already-differentiated slot gradients). No
11115 // gradient propagates back; matches the
11116 // Op::Const / Op::Alloc / Op::ZeroFill treatment.
11117 }
11118 Op::Branch { .. } => {
11119 // PR-A0 inert scaffold. `Op::Branch` is the
11120 // multi-path phi/merge node; it is never constructed
11121 // in A0, so this arm is unreachable today. When the
11122 // PR-A1 builders land, gradient flow through a Branch
11123 // routes via its arms (each an `inputs[i]` route exit)
11124 // and reconverges at `reconverge_at` — not through the
11125 // merge node itself. `backward` is infallible
11126 // (`-> GradMap`), so the no-panic inert handling is to
11127 // drop the gradient at the structural node, matching
11128 // the Op::Const / Op::ScatterIntoSlot treatment above.
11129 // The real per-arm routing lands with the builders.
11130 }
11131 Op::Scan { .. } => {
11132 // Defensive `panic!` — `backward() -> GradMap` is infallible
11133 // (no Err channel), so this is an internal-error guard in the
11134 // same infallible walk that already panics for QMatMul /
11135 // PagedAttn, NOT a recoverable typed error. It is unreachable
11136 // via the public builders: the C3 pre-pass
11137 // (lower_scans_for_backward) unrolls every Op::Scan to
11138 // primitives before the topo order is taken, and the builders
11139 // always emit the View consumers the pre-pass's remap +
11140 // never-hang guard lower away. Reaching here means the
11141 // pre-pass did not run (an internal bug).
11142 panic!(
11143 "NodeHandle::backward: Op::Scan reached the reverse walk un-lowered — \
11144 the C3 lower_scans_for_backward pre-pass did not run (internal bug)."
11145 );
11146 }
11147 Op::ScanPlaceholder { .. } => {
11148 // Inert body-hole leaf (no inputs) — never a real
11149 // differentiation target. Drop gradient like Op::Const /
11150 // Op::Iota; a live backward never reaches it (the body is
11151 // materialized by unroll_scan before any realize).
11152 }
11153 Op::View { slot } | Op::ViewOwned { slot } => {
11154 // Multi-output projection — item 4 backward
11155 // composition (Option C, 2026-06-01).
11156 //
11157 // Forward (Op::View): shares the producer's
11158 // bundled Storage Arc and exposes one slot's
11159 // typed window. Forward (Op::ViewOwned): memcpys
11160 // the slot's bytes into a fresh Storage.
11161 //
11162 // Backward: scatter the upstream gradient into
11163 // the slot's byte range of a fresh zero-bundle of
11164 // the producer's primary shape, then accumulate
11165 // that partial-bundle gradient as the producer's
11166 // input gradient. Multiple View consumers of the
11167 // same producer accumulate via the standard
11168 // sum-of-partials path:
11169 // bundle_grad =
11170 // ScatterIntoSlot{0}(0, g_y) +
11171 // ScatterIntoSlot{1}(0, g_state) + ...
11172 //
11173 // **Status (item 4)**: IR-level wiring only —
11174 // emits the scatter chain in the backward graph,
11175 // but no Op::ScatterIntoSlot kernel is registered.
11176 // The production multi-output producers
11177 // (SelectiveScan, SsdChunkScan) are
11178 // `BackwardKind::NotDifferentiable`, so autograd
11179 // panics at the producer before this scatter is
11180 // realized. When a differentiable multi-output op
11181 // materializes (Mamba training, FSCE loss+grad
11182 // fused), it lights up the ScatterIntoSlot CPU
11183 // kernel + tests alongside its own backward.
11184 let producer = inputs[0];
11185 let producer_shape = node_shape(&graph_handle, producer);
11186 let producer_dtype = node_dtype(&graph_handle, producer);
11187 let zero = build_filled_const(
11188 &graph_handle,
11189 producer_shape.clone(),
11190 producer_dtype,
11191 0.0,
11192 );
11193 let scattered = push_node(
11194 &graph_handle,
11195 Op::ScatterIntoSlot { slot },
11196 vec![zero, up_id],
11197 producer_shape,
11198 producer_dtype,
11199 );
11200 accumulate_grad(&mut upstream, producer, scattered, &graph_handle);
11201 }
11202 Op::ReluInplace => {
11203 // Same backward as Op::Relu — d(relu(x))/dx = step(x).
11204 // The view-aware `derive_ordering` (Phase 4a) pins
11205 // `Op::Step(x)` to run BEFORE Op::ReluInplace, so the
11206 // step kernel sees x's original bytes.
11207 let x = inputs[0];
11208 let x_shape = node_shape(&graph_handle, x);
11209 let dtype = node_dtype(&graph_handle, x);
11210 let step_x =
11211 push_node(&graph_handle, Op::Step, vec![x], x_shape.clone(), dtype);
11212 let grad_x =
11213 push_node(&graph_handle, Op::Mul, vec![up_id, step_x], x_shape, dtype);
11214 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11215 }
11216 Op::SiluInplace => {
11217 // Same backward as Op::Silu — grad_x = upstream * (s + y*(1-s))
11218 // where s = sigmoid(x) and y = silu(x) = this in-place node's
11219 // output. The post-mutation bytes at `id` ARE silu(x) (the
11220 // in-place op runs after the Sigmoid(x) read because of the
11221 // alias-aware ordering pass). `Op::Sigmoid(x)` reads x's
11222 // pre-mutation bytes; `Op::Mul(id, ...)` reads post-mutation
11223 // bytes — both correct.
11224 let x = inputs[0];
11225 let x_shape = node_shape(&graph_handle, x);
11226 let dtype = node_dtype(&graph_handle, x);
11227 let s = push_node(&graph_handle, Op::Sigmoid, vec![x], x_shape.clone(), dtype);
11228 let ones = build_ones(&graph_handle, x_shape.clone(), dtype);
11229 let one_minus_s = push_node(
11230 &graph_handle,
11231 Op::Sub,
11232 vec![ones, s],
11233 x_shape.clone(),
11234 dtype,
11235 );
11236 let y_times_1ms = push_node(
11237 &graph_handle,
11238 Op::Mul,
11239 vec![id, one_minus_s],
11240 x_shape.clone(),
11241 dtype,
11242 );
11243 let inner = push_node(
11244 &graph_handle,
11245 Op::Add,
11246 vec![s, y_times_1ms],
11247 x_shape.clone(),
11248 dtype,
11249 );
11250 let grad_x =
11251 push_node(&graph_handle, Op::Mul, vec![up_id, inner], x_shape, dtype);
11252 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11253 }
11254 Op::TanhInplace => {
11255 // Same backward as Op::Tanh — grad_x = upstream * (1 - y²)
11256 // where y = tanh(x) = this in-place node's output. `Op::Sqr(id)`
11257 // reads post-mutation bytes (= tanh(x) by definition of the
11258 // in-place op); no need to reference x at all.
11259 let x = inputs[0];
11260 let y_shape = node_shape(&graph_handle, id);
11261 let dtype = node_dtype(&graph_handle, id);
11262 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], y_shape.clone(), dtype);
11263 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11264 let one_minus_sq = push_node(
11265 &graph_handle,
11266 Op::Sub,
11267 vec![ones, y_sq],
11268 y_shape.clone(),
11269 dtype,
11270 );
11271 let grad_x = push_node(
11272 &graph_handle,
11273 Op::Mul,
11274 vec![up_id, one_minus_sq],
11275 y_shape,
11276 dtype,
11277 );
11278 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11279 }
11280 Op::SigmoidInplace => {
11281 // Same backward as Op::Sigmoid — grad_x = upstream * y * (1 - y)
11282 // where y = sigmoid(x) = this in-place node's output.
11283 let x = inputs[0];
11284 let y_shape = node_shape(&graph_handle, id);
11285 let dtype = node_dtype(&graph_handle, id);
11286 let ones = build_ones(&graph_handle, y_shape.clone(), dtype);
11287 let one_minus_y = push_node(
11288 &graph_handle,
11289 Op::Sub,
11290 vec![ones, id],
11291 y_shape.clone(),
11292 dtype,
11293 );
11294 let y_times_1my = push_node(
11295 &graph_handle,
11296 Op::Mul,
11297 vec![id, one_minus_y],
11298 y_shape.clone(),
11299 dtype,
11300 );
11301 let grad_x = push_node(
11302 &graph_handle,
11303 Op::Mul,
11304 vec![up_id, y_times_1my],
11305 y_shape,
11306 dtype,
11307 );
11308 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11309 }
11310 Op::GeluTanhInplace => {
11311 // Mirrors Op::GeluTanh's panic — the tanh-approximation
11312 // gradient is non-trivial and not yet implemented
11313 // for the non-inplace variant either. Users who
11314 // need a differentiable GELU should use SiluInplace
11315 // (which has a proper backward).
11316 panic!(
11317 "backward: GeluTanhInplace gradient is not yet supported. \
11318 Use SiluInplace for differentiable training; GeluTanhInplace \
11319 is currently inference-only (mirrors Op::GeluTanh's status)."
11320 );
11321 }
11322 Op::NegInplace => {
11323 // Same backward as Op::Neg — grad_x = -upstream. No
11324 // dependency on x or y; Phase 4a ordering not needed.
11325 let x = inputs[0];
11326 let x_shape = node_shape(&graph_handle, x);
11327 let dtype = node_dtype(&graph_handle, x);
11328 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_id], x_shape, dtype);
11329 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11330 }
11331 Op::AbsInplace => {
11332 // Same backward as Op::Abs — grad_x = sign(x) * upstream.
11333 // `Op::Sign(x)` reads x's pre-mutation bytes (Phase 4a
11334 // pins the in-place op after the Sign read).
11335 let x = inputs[0];
11336 let x_shape = node_shape(&graph_handle, x);
11337 let dtype = node_dtype(&graph_handle, x);
11338 let sign_x =
11339 push_node(&graph_handle, Op::Sign, vec![x], x_shape.clone(), dtype);
11340 let grad_x =
11341 push_node(&graph_handle, Op::Mul, vec![up_id, sign_x], x_shape, dtype);
11342 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11343 }
11344 Op::SqrInplace => {
11345 // Same backward as Op::Sqr — grad_x = 2x * upstream,
11346 // expressed as `x + x` to avoid a scalar broadcast.
11347 // `x + x` reads pre-mutation bytes (Phase 4a).
11348 let x = inputs[0];
11349 let x_shape = node_shape(&graph_handle, x);
11350 let dtype = node_dtype(&graph_handle, x);
11351 let two_x =
11352 push_node(&graph_handle, Op::Add, vec![x, x], x_shape.clone(), dtype);
11353 let grad_x =
11354 push_node(&graph_handle, Op::Mul, vec![up_id, two_x], x_shape, dtype);
11355 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11356 }
11357 Op::SqrtInplace => {
11358 // Same backward as Op::Sqrt — y = √x, grad_x = upstream/(2y).
11359 // Reads only the forward output `id`, which is post-mutation =
11360 // √x by definition; no pre-mutation x access needed.
11361 let x = inputs[0];
11362 let x_shape = node_shape(&graph_handle, x);
11363 let dtype = node_dtype(&graph_handle, x);
11364 let two_y =
11365 push_node(&graph_handle, Op::Add, vec![id, id], x_shape.clone(), dtype);
11366 let grad_x =
11367 push_node(&graph_handle, Op::Div, vec![up_id, two_y], x_shape, dtype);
11368 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11369 }
11370 Op::RsqrtInplace => {
11371 // Same backward as Op::Rsqrt — y = x^(-1/2),
11372 // grad_x = -0.5 * upstream * y³. Reads forward output (id)
11373 // only — post-mutation = y by definition.
11374 let x = inputs[0];
11375 let x_shape = node_shape(&graph_handle, x);
11376 let dtype = node_dtype(&graph_handle, x);
11377 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11378 let y_cu = push_node(
11379 &graph_handle,
11380 Op::Mul,
11381 vec![id, y_sq],
11382 x_shape.clone(),
11383 dtype,
11384 );
11385 let scaled = push_node(
11386 &graph_handle,
11387 Op::MulScalar(-0.5),
11388 vec![y_cu],
11389 x_shape.clone(),
11390 dtype,
11391 );
11392 let grad_x =
11393 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11394 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11395 }
11396 Op::RecipInplace => {
11397 // Same backward as Op::Recip — y = 1/x, grad_x = -upstream * y².
11398 // Reads forward output (id) only — post-mutation = 1/x.
11399 let x = inputs[0];
11400 let x_shape = node_shape(&graph_handle, x);
11401 let dtype = node_dtype(&graph_handle, x);
11402 let y_sq = push_node(&graph_handle, Op::Sqr, vec![id], x_shape.clone(), dtype);
11403 let up_y_sq = push_node(
11404 &graph_handle,
11405 Op::Mul,
11406 vec![up_id, y_sq],
11407 x_shape.clone(),
11408 dtype,
11409 );
11410 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_y_sq], x_shape, dtype);
11411 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11412 }
11413 Op::ExpInplace => {
11414 // Same backward as Op::Exp — d(exp(x))/dx = exp(x) = y = id.
11415 // grad_x = upstream * y. Reads forward output (id) only.
11416 let x = inputs[0];
11417 let out_shape = node_shape(&graph_handle, id);
11418 let dtype = node_dtype(&graph_handle, id);
11419 let grad_x =
11420 push_node(&graph_handle, Op::Mul, vec![up_id, id], out_shape, dtype);
11421 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11422 }
11423 Op::LogInplace => {
11424 // Same backward as Op::Log — grad_x = upstream / x.
11425 // `Op::Div(up, x)` reads pre-mutation bytes of x (Phase 4a).
11426 let x = inputs[0];
11427 let x_shape = node_shape(&graph_handle, x);
11428 let dtype = node_dtype(&graph_handle, x);
11429 let grad_x = push_node(&graph_handle, Op::Div, vec![up_id, x], x_shape, dtype);
11430 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11431 }
11432 Op::SinInplace => {
11433 // Same backward as Op::Sin — grad_x = upstream * cos(x).
11434 // `Op::Cos(x)` reads pre-mutation x via Phase 4a ordering.
11435 let x = inputs[0];
11436 let x_shape = node_shape(&graph_handle, x);
11437 let dtype = node_dtype(&graph_handle, x);
11438 let cos_x = push_node(&graph_handle, Op::Cos, vec![x], x_shape.clone(), dtype);
11439 let grad_x =
11440 push_node(&graph_handle, Op::Mul, vec![up_id, cos_x], x_shape, dtype);
11441 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11442 }
11443 Op::CosInplace => {
11444 // Same backward as Op::Cos — grad_x = -(upstream * sin(x)).
11445 let x = inputs[0];
11446 let x_shape = node_shape(&graph_handle, x);
11447 let dtype = node_dtype(&graph_handle, x);
11448 let sin_x = push_node(&graph_handle, Op::Sin, vec![x], x_shape.clone(), dtype);
11449 let up_sin = push_node(
11450 &graph_handle,
11451 Op::Mul,
11452 vec![up_id, sin_x],
11453 x_shape.clone(),
11454 dtype,
11455 );
11456 let grad_x = push_node(&graph_handle, Op::Neg, vec![up_sin], x_shape, dtype);
11457 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11458 }
11459 Op::SignInplace | Op::FloorInplace | Op::CeilInplace | Op::RoundInplace => {
11460 // Same backward as Op::{Sign, Floor, Ceil, Round} —
11461 // derivative is 0 almost everywhere; drop gradient
11462 // (no accumulation, mirroring Op::Step's pattern).
11463 }
11464 Op::ErfInplace => {
11465 // Same backward as Op::Erf — grad_x = upstream * (2/√π) * exp(-x²).
11466 // `Op::Sqr(x)` reads pre-mutation x via Phase 4a ordering.
11467 const TWO_OVER_SQRT_PI: f64 = std::f64::consts::FRAC_2_SQRT_PI;
11468 let x = inputs[0];
11469 let x_shape = node_shape(&graph_handle, x);
11470 let dtype = node_dtype(&graph_handle, x);
11471 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11472 let neg_x_sq =
11473 push_node(&graph_handle, Op::Neg, vec![x_sq], x_shape.clone(), dtype);
11474 let exp_neg = push_node(
11475 &graph_handle,
11476 Op::Exp,
11477 vec![neg_x_sq],
11478 x_shape.clone(),
11479 dtype,
11480 );
11481 let scaled = push_node(
11482 &graph_handle,
11483 Op::MulScalar(TWO_OVER_SQRT_PI),
11484 vec![exp_neg],
11485 x_shape.clone(),
11486 dtype,
11487 );
11488 let grad_x =
11489 push_node(&graph_handle, Op::Mul, vec![up_id, scaled], x_shape, dtype);
11490 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11491 }
11492 Op::ClampInplace { min, max } => {
11493 // Same backward as Op::Clamp — indicator is 1 where
11494 // min ≤ x ≤ max, 0 elsewhere. Reads pre-mutation x via
11495 // Phase 4a ordering.
11496 let x = inputs[0];
11497 let x_shape = node_shape(&graph_handle, x);
11498 let dtype = node_dtype(&graph_handle, x);
11499 let min_shifted = push_node(
11500 &graph_handle,
11501 Op::AddScalar(-min),
11502 vec![x],
11503 x_shape.clone(),
11504 dtype,
11505 );
11506 let lower_ok = push_node(
11507 &graph_handle,
11508 Op::Step,
11509 vec![min_shifted],
11510 x_shape.clone(),
11511 dtype,
11512 );
11513 let neg_x = push_node(
11514 &graph_handle,
11515 Op::MulScalar(-1.0),
11516 vec![x],
11517 x_shape.clone(),
11518 dtype,
11519 );
11520 let max_minus_x = push_node(
11521 &graph_handle,
11522 Op::AddScalar(max),
11523 vec![neg_x],
11524 x_shape.clone(),
11525 dtype,
11526 );
11527 let upper_ok = push_node(
11528 &graph_handle,
11529 Op::Step,
11530 vec![max_minus_x],
11531 x_shape.clone(),
11532 dtype,
11533 );
11534 let indicator = push_node(
11535 &graph_handle,
11536 Op::Mul,
11537 vec![lower_ok, upper_ok],
11538 x_shape.clone(),
11539 dtype,
11540 );
11541 let grad_x = push_node(
11542 &graph_handle,
11543 Op::Mul,
11544 vec![up_id, indicator],
11545 x_shape,
11546 dtype,
11547 );
11548 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11549 }
11550 Op::PowIInplace(n) => {
11551 // Same backward as Op::PowI — single fused
11552 // POWI_BACKWARD node `(x, upstream) → exp · x^(exp-1) ·
11553 // upstream`. Reads pre-mutation x via Phase 4a ordering.
11554 let x = inputs[0];
11555 let x_shape = node_shape(&graph_handle, x);
11556 let dtype = node_dtype(&graph_handle, x);
11557 let grad_x = push_node(
11558 &graph_handle,
11559 Op::Fused(
11560 crate::registry::FusedOps::POWI_BACKWARD,
11561 crate::registry::FusedOpParams::PowIBackward { exp: n },
11562 ),
11563 vec![x, up_id],
11564 x_shape,
11565 dtype,
11566 );
11567 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11568 }
11569 Op::GeluInplace => {
11570 // Same backward as Op::Gelu — exact-GELU derivative
11571 // is Φ(x) + x·φ(x). Both halves read pre-mutation x via
11572 // Phase 4a ordering. Identical 12-node chain to Op::Gelu.
11573 const INV_SQRT_2: f64 = std::f64::consts::FRAC_1_SQRT_2;
11574 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7_f64;
11575 let x = inputs[0];
11576 let x_shape = node_shape(&graph_handle, x);
11577 let dtype = node_dtype(&graph_handle, x);
11578 let x_over_sqrt2 = push_node(
11579 &graph_handle,
11580 Op::MulScalar(INV_SQRT_2),
11581 vec![x],
11582 x_shape.clone(),
11583 dtype,
11584 );
11585 let erf_arg = push_node(
11586 &graph_handle,
11587 Op::Erf,
11588 vec![x_over_sqrt2],
11589 x_shape.clone(),
11590 dtype,
11591 );
11592 let plus_one = push_node(
11593 &graph_handle,
11594 Op::AddScalar(1.0),
11595 vec![erf_arg],
11596 x_shape.clone(),
11597 dtype,
11598 );
11599 let cdf_term = push_node(
11600 &graph_handle,
11601 Op::MulScalar(0.5),
11602 vec![plus_one],
11603 x_shape.clone(),
11604 dtype,
11605 );
11606 let x_sq = push_node(&graph_handle, Op::Sqr, vec![x], x_shape.clone(), dtype);
11607 let half_x_sq = push_node(
11608 &graph_handle,
11609 Op::MulScalar(0.5),
11610 vec![x_sq],
11611 x_shape.clone(),
11612 dtype,
11613 );
11614 let neg_half = push_node(
11615 &graph_handle,
11616 Op::Neg,
11617 vec![half_x_sq],
11618 x_shape.clone(),
11619 dtype,
11620 );
11621 let exp_term = push_node(
11622 &graph_handle,
11623 Op::Exp,
11624 vec![neg_half],
11625 x_shape.clone(),
11626 dtype,
11627 );
11628 let phi = push_node(
11629 &graph_handle,
11630 Op::MulScalar(INV_SQRT_2PI),
11631 vec![exp_term],
11632 x_shape.clone(),
11633 dtype,
11634 );
11635 let pdf_term =
11636 push_node(&graph_handle, Op::Mul, vec![x, phi], x_shape.clone(), dtype);
11637 let d_gelu = push_node(
11638 &graph_handle,
11639 Op::Add,
11640 vec![cdf_term, pdf_term],
11641 x_shape.clone(),
11642 dtype,
11643 );
11644 let grad_x =
11645 push_node(&graph_handle, Op::Mul, vec![up_id, d_gelu], x_shape, dtype);
11646 accumulate_grad(&mut upstream, x, grad_x, &graph_handle);
11647 }
11648 }
11649 }
11650
11651 GradMap {
11652 graph: graph_handle,
11653 forward_to_grad: upstream,
11654 }
11655 }
11656}
11657
11658/// Map from forward-graph node IDs to the IDs of their accumulated
11659/// backward-graph gradient nodes, returned by [`NodeHandle::backward`].
11660///
11661/// All gradient nodes live on the same graph as the forward nodes. Getting
11662/// a gradient by calling [`GradMap::get`] returns a new [`NodeHandle`] handle
11663/// pointing at the gradient node so callers can realize it, plug it into
11664/// further computation, or back-propagate through it again.
11665pub struct GradMap {
11666 graph: SharedGraph,
11667 forward_to_grad: HashMap<NodeId, NodeId>,
11668}
11669
11670impl GradMap {
11671 /// Get the gradient tensor for a forward tensor from the same graph.
11672 ///
11673 /// Returns `None` if the forward tensor was not reachable from the
11674 /// root passed to `backward` (i.e. not part of the computation being
11675 /// differentiated).
11676 ///
11677 /// # Panics
11678 ///
11679 /// Panics if any operand belongs to a different [`Graph`] than the one this
11680 /// builder is building into. Operand identity is graph-scoped and checked by
11681 /// pointer identity (`Arc::ptr_eq`), which cannot alias; the panic is
11682 /// deliberate and replaces the hang a cross-graph handle used to produce.
11683 /// Build every operand from one graph, or use a `Result`-returning entry
11684 /// point where one exists.
11685 pub fn get(&self, forward: &NodeHandle) -> Option<NodeHandle> {
11686 assert!(
11687 Arc::ptr_eq(&self.graph, &forward.graph),
11688 "GradMap::get: tensor is from a different graph",
11689 );
11690 let &grad_id = self.forward_to_grad.get(&forward.id)?;
11691 Some(NodeHandle {
11692 graph: self.graph.clone(),
11693 id: grad_id,
11694 })
11695 }
11696
11697 /// Number of forward nodes that have a recorded gradient.
11698 pub fn len(&self) -> usize {
11699 self.forward_to_grad.len()
11700 }
11701
11702 /// Whether this map has no gradients (e.g. a backward over a lone const).
11703 pub fn is_empty(&self) -> bool {
11704 self.forward_to_grad.is_empty()
11705 }
11706}
11707
11708// -------- internal helpers shared by the backward pass --------------------
11709
11710/// The generic decompose-backward hook (Op::Scan Phase 2, C3): before the
11711/// reverse walk takes its topo order, lower every reachable `Op::Scan` to
11712/// `bound` primitives and decompose the two SSM `Op::Fused` recipes into their
11713/// `Op::Scan` form, rewiring consumers so the walk sees only differentiable
11714/// primitives. BPTT differentiates the static-`bound` unroll (the runtime
11715/// early-exit predicate is a forward-only optimization, ignored here — spec C3
11716/// static-horizon note). Operates in place on the shared graph (a `backward()`
11717/// caller is a training step that wants the unrolled activations anyway).
11718/// Returns the (possibly remapped) root NodeId to walk from.
11719fn lower_scans_for_backward(graph: &SharedGraph, root: NodeId) -> NodeId {
11720 use std::collections::HashMap;
11721 let mut root = root;
11722 // helper: apply a remap to every consumer's inputs + the root, in place.
11723 fn apply_remap(graph: &SharedGraph, remap: &HashMap<NodeId, NodeId>, root: &mut NodeId) {
11724 if remap.is_empty() {
11725 return;
11726 }
11727 let mut g = graph.write().unwrap();
11728 let n = g.len();
11729 for nid in 0..n {
11730 let ilen = g.node(NodeId(nid)).inputs.len();
11731 for i in 0..ilen {
11732 let cur = g.node(NodeId(nid)).inputs[i];
11733 if let Some(&new) = remap.get(&cur) {
11734 g.rewrite_input(NodeId(nid), cur, new);
11735 }
11736 }
11737 }
11738 if let Some(&new) = remap.get(root) {
11739 *root = new;
11740 }
11741 }
11742
11743 // --- Pass 1: decompose SSM Op::Fused(SELECTIVE_SCAN|SSD_CHUNK_SCAN) into Op::Scan.
11744 {
11745 let ssm = [
11746 crate::registry::FusedOps::SELECTIVE_SCAN,
11747 crate::registry::FusedOps::SSD_CHUNK_SCAN,
11748 ];
11749 let targets: Vec<(
11750 NodeId,
11751 crate::registry::FusedOpId,
11752 crate::registry::FusedOpParams,
11753 )> = {
11754 let g = graph.read().unwrap();
11755 crate::topo_order(&g, root)
11756 .into_iter()
11757 .filter_map(|id| match &g.node(id).op {
11758 Op::Fused(fid, params) if ssm.contains(fid) => Some((id, *fid, params.clone())),
11759 _ => None,
11760 })
11761 .collect()
11762 };
11763 let mut remap = HashMap::new();
11764 for (id, fid, params) in targets {
11765 if let Some(entry) = crate::registry::default_registry().entry(fid) {
11766 let y = {
11767 let mut g = graph.write().unwrap();
11768 (entry.decompose)(&mut g, id, ¶ms)
11769 };
11770 if y != id {
11771 remap.insert(id, y);
11772 // Collapse the fused node's slot-0 View consumers DIRECTLY to
11773 // the decompose output. Slot 0 is the primary value (the
11774 // multi-output authoring contract: Node.shape == slot-0
11775 // shape), and the SSM decompose re-presents its primary AS
11776 // slot 0, so `View{0}(y) == y`. Without this collapse the
11777 // outer View{0} survives into the reverse walk and emits an
11778 // `Op::ScatterIntoSlot` (which has no CPU realize kernel),
11779 // so realizing the gradient would fail. Slot-1 (last_state)
11780 // consumers keep their `View{1}(y)` re-projection via the
11781 // default input rewrite (remap[id] = y) and are not
11782 // differentiated on this path.
11783 let g = graph.read().unwrap();
11784 for nid in 0..g.len() {
11785 let node = g.node(NodeId(nid));
11786 if let Op::View { slot: 0 } | Op::ViewOwned { slot: 0 } = node.op
11787 && node.inputs.first() == Some(&id)
11788 {
11789 remap.insert(NodeId(nid), y);
11790 }
11791 }
11792 }
11793 }
11794 }
11795 apply_remap(graph, &remap, &mut root);
11796 }
11797
11798 // --- Pass 2: unroll every reachable Op::Scan to `bound` primitives.
11799 loop {
11800 let scans: Vec<(NodeId, usize, ScanEmit)> = {
11801 let g = graph.read().unwrap();
11802 crate::topo_order(&g, root)
11803 .into_iter()
11804 .filter_map(|id| match &g.node(id).op {
11805 Op::Scan { bound, emit, .. } => Some((id, *bound, *emit)),
11806 _ => None,
11807 })
11808 .collect()
11809 };
11810 if scans.is_empty() {
11811 break;
11812 }
11813 let mut remap = HashMap::new();
11814 for (scan_id, bound, emit) in scans {
11815 let (a, b) = {
11816 let mut g = graph.write().unwrap();
11817 match crate::scan::unroll_scan(&mut g, scan_id, bound) {
11818 Ok(pair) => pair,
11819 Err(_) => continue, // malformed scan: leave it; the C4 guard describes it.
11820 }
11821 };
11822 // Normalize to (slot 0 = stacked_ys, slots 1.. = final carries).
11823 //
11824 // GAP-303: `unroll_scan` now returns (selected, complementary) as
11825 // VECS. The `ys` side is always exactly one node; the carry side is
11826 // `n_carries` wide. At `n_carries == 1` this is byte-for-byte the old
11827 // behaviour -- one ys, one carry, slot 1 the only carry slot.
11828 let (ys_v, carries) = match emit {
11829 ScanEmit::All => (a, b),
11830 ScanEmit::Final => (b, a),
11831 };
11832 let Some(&slot0) = ys_v.first() else {
11833 continue; // malformed: no stacked ys; the C4 guard describes it.
11834 };
11835 // Remap the scan's View{slot}/ViewOwned{slot} consumers to the unroll outputs.
11836 let g = graph.read().unwrap();
11837 for nid in 0..g.len() {
11838 let node = g.node(NodeId(nid));
11839 if let Op::View { slot } | Op::ViewOwned { slot } = node.op
11840 && node.inputs.first() == Some(&scan_id)
11841 {
11842 // ⚠️ Slot 0 is `ys`; slot k>=1 is carry k-1. The old form was
11843 // `if slot == 0 { slot0 } else { slot1 }`, which folded EVERY
11844 // slot above 0 onto the single carry -- a fifth site of the
11845 // 2-slot assumption. Out-of-range slots are LEFT UNMAPPED for
11846 // the C4 guard rather than indexed (never-panic).
11847 let target = if slot == 0 {
11848 Some(slot0)
11849 } else {
11850 carries.get(slot as usize - 1).copied()
11851 };
11852 if let Some(t) = target {
11853 remap.insert(NodeId(nid), t);
11854 }
11855 }
11856 }
11857 }
11858 // Defensive never-hang guard: if a full pass lowered no scan to a
11859 // consumer remap (e.g. a malformed scan that unroll rejects, or a raw
11860 // scan producer with no View consumers), stop rather than re-scanning
11861 // the same unchanged graph forever. Any residual Op::Scan then reaches
11862 // the C4 defensive `panic!` guard (backward is infallible, so it cannot
11863 // return an error) — an internal-bug signal, never an infinite loop.
11864 if remap.is_empty() {
11865 break;
11866 }
11867 apply_remap(graph, &remap, &mut root);
11868 // Unrolled graphs contain no Op::Scan, so a well-formed graph terminates
11869 // in <= 2 iterations (the loop re-scans in case a decomposed body itself
11870 // contained a scan; the current SSM decompose does not).
11871 }
11872 root
11873}
11874
11875/// Read a node's shape without holding the borrow past the call site.
11876fn node_shape(graph: &SharedGraph, id: NodeId) -> Shape {
11877 graph.read().unwrap().node(id).shape.clone()
11878}
11879
11880/// Read a node's dtype without holding the borrow past the call site.
11881fn node_dtype(graph: &SharedGraph, id: NodeId) -> DType {
11882 graph.read().unwrap().node(id).dtype
11883}
11884
11885/// Shape with its last two dims swapped. Used by MatMul's backward rule
11886/// to construct transpose-node output shapes for any rank ≥ 2.
11887fn transposed_shape(shape: &Shape) -> Shape {
11888 let d = shape.dims();
11889 assert!(
11890 d.len() >= 2,
11891 "transposed_shape: expected rank ≥ 2, got {d:?}",
11892 );
11893 let rank = d.len();
11894 let mut out: Vec<usize> = d.to_vec();
11895 out.swap(rank - 2, rank - 1);
11896 Shape::from_dims(&out)
11897}
11898
11899/// Given a full tensor shape and a dim that was reduced away, produce the
11900/// keepdim shape — i.e. the full shape with size 1 at `dim`. Used by
11901/// axis-reduction backward rules to reshape the reduced upstream back to
11902/// a shape that broadcasts against the original input.
11903fn reshape_to_keepdim(full_dims: &[usize], dim: usize) -> Shape {
11904 assert!(
11905 dim < full_dims.len(),
11906 "reshape_to_keepdim: dim {dim} out of bounds for {full_dims:?}",
11907 );
11908 let mut out: Vec<usize> = full_dims.to_vec();
11909 out[dim] = 1;
11910 Shape::from_dims(&out)
11911}
11912
11913/// Validate that `src` can be broadcast to `dst` using NumPy rules:
11914/// right-align, pad the shorter shape with 1s on the left, and for each
11915/// aligned dimension the src size must equal the dst size or be 1.
11916fn check_broadcast_compatible(src: &[usize], dst: &[usize]) {
11917 assert!(
11918 src.len() <= dst.len(),
11919 "broadcast_to: source rank {} exceeds target rank {}",
11920 src.len(),
11921 dst.len(),
11922 );
11923 let pad = dst.len() - src.len();
11924 for (i, &s) in src.iter().enumerate() {
11925 let d = dst[pad + i];
11926 assert!(
11927 s == d || s == 1,
11928 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11929 pad + i,
11930 );
11931 }
11932}
11933
11934/// Result-returning sibling of [`check_broadcast_compatible`].
11935fn try_check_broadcast_compatible(
11936 src: &[usize],
11937 dst: &[usize],
11938) -> std::result::Result<(), fuel_ir::Error> {
11939 if src.len() > dst.len() {
11940 return Err(fuel_ir::Error::Msg(format!(
11941 "broadcast_to: source rank {} exceeds target rank {}",
11942 src.len(),
11943 dst.len(),
11944 ))
11945 .bt());
11946 }
11947 let pad = dst.len() - src.len();
11948 for (i, &s) in src.iter().enumerate() {
11949 let d = dst[pad + i];
11950 if s != d && s != 1 {
11951 return Err(fuel_ir::Error::Msg(format!(
11952 "broadcast_to: dim {i} of source ({s}) is incompatible with dim {} of target ({d})",
11953 pad + i,
11954 ))
11955 .bt());
11956 }
11957 }
11958 Ok(())
11959}
11960
11961/// Compute the NumPy broadcast shape of two input shapes. Right-align,
11962/// pad the shorter with leading 1s, and take the element-wise max at
11963/// each position. Panics if the shapes are incompatible (neither can
11964/// expand to match the other at some dim).
11965fn compute_broadcast_shape(a: &[usize], b: &[usize]) -> Vec<usize> {
11966 let n = a.len().max(b.len());
11967 let a_pad = n - a.len();
11968 let b_pad = n - b.len();
11969 let mut out = Vec::with_capacity(n);
11970 for i in 0..n {
11971 let ai = if i < a_pad { 1 } else { a[i - a_pad] };
11972 let bi = if i < b_pad { 1 } else { b[i - b_pad] };
11973 let oi = if ai == bi {
11974 ai
11975 } else if ai == 1 {
11976 bi
11977 } else if bi == 1 {
11978 ai
11979 } else {
11980 panic!(
11981 "compute_broadcast_shape: incompatible shapes {a:?} vs {b:?} at axis {i}: {ai} vs {bi}",
11982 );
11983 };
11984 out.push(oi);
11985 }
11986 out
11987}
11988
11989/// Push a node to the graph and return its ID. Used by backward to append
11990/// gradient-computing nodes without going through the public builders,
11991/// which would re-validate shapes the backward pass has already derived.
11992fn push_node(
11993 graph: &SharedGraph,
11994 op: Op,
11995 inputs: Vec<NodeId>,
11996 shape: Shape,
11997 dtype: DType,
11998) -> NodeId {
11999 graph.write().unwrap().push(Node {
12000 op,
12001 inputs,
12002 shape,
12003 dtype,
12004 })
12005}
12006
12007/// Build a ones tensor of the given shape and dtype as a `Const` node.
12008/// Used to seed the initial upstream gradient at the root of the backward
12009/// pass (`dL/dL = 1`).
12010fn build_ones(graph: &SharedGraph, shape: Shape, dtype: DType) -> NodeId {
12011 build_filled_const(graph, shape, dtype, 1.0)
12012}
12013
12014/// Build a constant tensor of the given shape and dtype filled with
12015/// `value` (expressed as `f64` and converted to the target dtype). Used
12016/// by backward rules that need a scalar-valued broadcast, for example
12017/// `MeanAll`'s `1/n` factor expressed as "divide by an n-filled const."
12018///
12019/// Build RoPE cos/sin tables for a given `(base, start_pos, seq,
12020/// head_dim)`. Each returned `Vec<f32>` has shape `[seq, head_dim]`
12021/// (row-major) in the half-split layout [`NodeHandle::rope_with_tables`]
12022/// expects: positions `[:, :half]` and `[:, half:]` hold the same
12023/// value for the same `(p, i)`, so a single elementwise multiply with
12024/// `self` does the right thing alongside `rotate_half(self) * sin`.
12025///
12026/// Exposed as a free function so callers can share the tables across
12027/// many RoPE applications (e.g. every attention layer in a transformer
12028/// forward pass).
12029pub fn build_rope_tables(
12030 base: f64,
12031 start_pos: usize,
12032 seq: usize,
12033 head_dim: usize,
12034) -> (Vec<f32>, Vec<f32>) {
12035 assert!(
12036 head_dim.is_multiple_of(2),
12037 "build_rope_tables: head_dim {head_dim} must be even",
12038 );
12039 let half = head_dim / 2;
12040 let inv_freq: Vec<f64> = (0..half)
12041 .map(|i| base.powf(-2.0 * (i as f64) / (head_dim as f64)))
12042 .collect();
12043 build_rope_tables_with_inv_freq(&inv_freq, start_pos, seq, head_dim)
12044}
12045
12046/// [`build_rope_tables`] with the inverse frequencies supplied directly rather
12047/// than derived from a single `base`.
12048///
12049/// Every RoPE variant Fuel supports differs from the default in **exactly** this
12050/// vector: LLaMA-3.1's long-context scaling is a per-dimension transform of the
12051/// same `head_dim / 2` values, and the position loop below is bit-identical
12052/// either way. Splitting the frequency choice out is what lets a scaled model
12053/// reuse the whole decode path — the KV-cache forward, the held-graph persistent
12054/// forward, and their per-token rebinds — instead of needing a parallel copy of
12055/// each.
12056///
12057/// `inv_freq.len()` must be `head_dim / 2`.
12058pub fn build_rope_tables_with_inv_freq(
12059 inv_freq: &[f64],
12060 start_pos: usize,
12061 seq: usize,
12062 head_dim: usize,
12063) -> (Vec<f32>, Vec<f32>) {
12064 assert!(
12065 head_dim.is_multiple_of(2),
12066 "build_rope_tables_with_inv_freq: head_dim {head_dim} must be even",
12067 );
12068 let half = head_dim / 2;
12069 assert_eq!(
12070 inv_freq.len(),
12071 half,
12072 "build_rope_tables_with_inv_freq: inv_freq len {} != head_dim/2 {half}",
12073 inv_freq.len(),
12074 );
12075 let mut cos_data = vec![0.0_f32; seq * head_dim];
12076 let mut sin_data = vec![0.0_f32; seq * head_dim];
12077 for p in 0..seq {
12078 let pos = (start_pos + p) as f64;
12079 for (i, &freq) in inv_freq.iter().enumerate() {
12080 let theta = pos * freq;
12081 let c = theta.cos() as f32;
12082 let s = theta.sin() as f32;
12083 cos_data[p * head_dim + i] = c;
12084 cos_data[p * head_dim + i + half] = c;
12085 sin_data[p * head_dim + i] = s;
12086 sin_data[p * head_dim + i + half] = s;
12087 }
12088 }
12089 (cos_data, sin_data)
12090}
12091
12092/// Only float dtypes are supported here — integer/index tensors never
12093/// appear as gradients, so a `U32` call indicates a bug in a backward
12094/// rule rather than a missing feature.
12095///
12096/// Phase 7.5 G2: gradient consts are slot-populating Op::Const
12097/// nodes. Device is picked from any existing slot (the forward pass
12098/// always populated at least one slot-bearing leaf by the time
12099/// backward runs). For a CPU-rooted graph the device's
12100/// `storage_from_host_buffer_owned_dyn` is a zero-copy wrap; for
12101/// GPU-rooted, an H2D upload (matching today's eval_const path on
12102/// first realize).
12103fn build_filled_const(graph: &SharedGraph, shape: Shape, dtype: DType, value: f64) -> NodeId {
12104 let n = shape.elem_count();
12105 let buf = match dtype {
12106 DType::F32 => fuel_ir::HostBuffer::F32(vec![value as f32; n]),
12107 DType::F64 => fuel_ir::HostBuffer::F64(vec![value; n]),
12108 DType::BF16 => fuel_ir::HostBuffer::BF16(vec![bf16::from_f64(value); n]),
12109 DType::F16 => fuel_ir::HostBuffer::F16(vec![f16::from_f64(value); n]),
12110 other => panic!(
12111 "backward: build_filled_const: unsupported dtype {other:?} \
12112 (gradients are always floats — this would indicate a bug in \
12113 a backward rule that tried to differentiate through an \
12114 integer tensor)",
12115 ),
12116 };
12117 let device = pick_device_from_graph(graph);
12118 let backend_storage = device
12119 .storage_from_host_buffer_owned_dyn(buf)
12120 .expect("build_filled_const: storage_from_host_buffer_owned_dyn failed");
12121 let storage_arc = Arc::new(RwLock::new(Storage::from_dyn(backend_storage)));
12122 let id = push_node(graph, Op::Const, vec![], shape, dtype);
12123 graph.write().unwrap().set_storage(id, storage_arc);
12124 id
12125}
12126
12127/// G2 helper: walk the graph for any populated slot and return its
12128/// device. Used by gradient builders that don't have an explicit
12129/// device parameter — the graph always has at least one slot-bearing
12130/// Const leaf by the time backward() runs (the forward pass's inputs
12131/// are slot-rooted Const leaves), so this can be relied on.
12132fn pick_device_from_graph(graph: &SharedGraph) -> Arc<dyn fuel_backend_contract::DynBackendDevice> {
12133 let g = graph.read().unwrap();
12134 for i in 0..g.len() {
12135 if let Some(slot_arc) = g.storage_for(NodeId(i)) {
12136 return slot_arc.read().unwrap().device();
12137 }
12138 }
12139 panic!(
12140 "build_filled_const: graph has no populated storage slots; backward \
12141 requires at least one slot-bearing Const leaf to pick a gradient \
12142 device from. Was the forward pass built with G2-migrated \
12143 constructors (from_f32/etc. with explicit &Device)?"
12144 )
12145}
12146
12147/// Accumulate a new gradient contribution into the upstream map.
12148///
12149/// If `forward_id` already has an upstream gradient, emit an `Add` node to
12150/// sum the two contributions. If not, record the new one as-is. This is
12151/// the multi-variable chain rule in its operational form: when a forward
12152/// node has multiple downstream consumers, the gradients from each must
12153/// be summed.
12154fn accumulate_grad(
12155 upstream: &mut HashMap<NodeId, NodeId>,
12156 forward_id: NodeId,
12157 new_grad_id: NodeId,
12158 graph: &SharedGraph,
12159) {
12160 match upstream.get(&forward_id).copied() {
12161 None => {
12162 upstream.insert(forward_id, new_grad_id);
12163 }
12164 Some(existing_id) => {
12165 let shape = node_shape(graph, forward_id);
12166 let dtype = node_dtype(graph, forward_id);
12167 let combined = push_node(graph, Op::Add, vec![existing_id, new_grad_id], shape, dtype);
12168 upstream.insert(forward_id, combined);
12169 }
12170 }
12171}
12172
12173#[cfg(test)]
12174mod tests {
12175 use super::*;
12176
12177 /// Phase 7.5 G2: tests need a real device to allocate slot
12178 /// storage through the new constructor API. `cpu_dev()` returns a
12179 /// stable singleton CpuBackendDevice handle so every call site can
12180 /// just pass `cpu_dev()` without per-test boilerplate.
12181 fn cpu_dev() -> &'static Arc<dyn fuel_backend_contract::DynBackendDevice> {
12182 static D: std::sync::OnceLock<Arc<dyn fuel_backend_contract::DynBackendDevice>> =
12183 std::sync::OnceLock::new();
12184 D.get_or_init(|| Arc::new(fuel_cpu_backend::dyn_impl::CpuBackendDevice))
12185 }
12186
12187 /// `Tensor::awq_matmul`'s public builder end-to-end: a well-formed call
12188 /// produces a `Fused(AWQ_MATMUL, ..)` node with the right output
12189 /// shape/dtype. The decompose MATH is tested at the registry level
12190 /// (`registry::awq_matmul::tests`); this just confirms the builder's
12191 /// own validation + node construction work from the public API.
12192 #[test]
12193 fn awq_matmul_builder_produces_expected_node() {
12194 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12195 .unwrap();
12196 let qweight = act
12197 .const_u32_like(vec![0u32; 8], Shape::from_dims(&[8, 1]))
12198 .unwrap();
12199 let qzeros = act
12200 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12201 .unwrap();
12202 let scales = act
12203 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12204 .unwrap();
12205 let out = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12206 assert_eq!(out.shape().dims(), &[2, 8]);
12207 assert_eq!(out.dtype(), DType::F32);
12208 assert!(matches!(
12209 out.graph.read().unwrap().node(out.id).op,
12210 Op::Fused(id, _) if id == crate::registry::FusedOps::AWQ_MATMUL
12211 ));
12212 }
12213
12214 /// Born-red: a non-U32 `qweight` must panic with a clear message, not
12215 /// silently misinterpret bytes.
12216 #[test]
12217 #[should_panic(expected = "qweight must be U32")]
12218 fn awq_matmul_builder_panics_on_wrong_qweight_dtype() {
12219 let act = NodeHandle::from_f32(vec![0.0_f32; 2 * 8], Shape::from_dims(&[2, 8]), cpu_dev())
12220 .unwrap();
12221 let qweight = act
12222 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[8, 1]))
12223 .unwrap();
12224 let qzeros = act
12225 .const_u32_like(vec![0u32; 1], Shape::from_dims(&[1, 1]))
12226 .unwrap();
12227 let scales = act
12228 .const_f32_like(vec![1.0_f32; 8], Shape::from_dims(&[1, 8]))
12229 .unwrap();
12230 let _ = act.awq_matmul(&qweight, &qzeros, &scales, 8, 8);
12231 }
12232
12233 #[test]
12234 fn builders_agree_with_primitive_shape() {
12235 // No-drift guard (Convergence A, Task 6): every routed builder's output
12236 // shape/dtype must equal primitive_shape's answer for the same Op. If a
12237 // builder's inline math ever diverged from primitive_shape, this fails.
12238 let x = NodeHandle::from_f32(
12239 vec![0.0_f32; 2 * 3 * 4],
12240 Shape::from_dims(&[2, 3, 4]),
12241 cpu_dev(),
12242 )
12243 .unwrap();
12244 let checks: Vec<(NodeHandle, Op)> = vec![
12245 (
12246 x.slice(1, 0, 2),
12247 Op::Slice {
12248 dim: 1,
12249 start: 0,
12250 len: 2,
12251 },
12252 ),
12253 (x.mean_dim(2), Op::MeanDim(2)),
12254 (
12255 x.try_permute(&[2, 0, 1]).unwrap(),
12256 Op::Permute(vec![2, 0, 1]),
12257 ),
12258 (x.cast(DType::F16), Op::Cast(DType::F16)),
12259 ];
12260 for (t, op) in checks {
12261 let (ps_shape, ps_dtype) =
12262 crate::shape::primitive_shape(&op, &[x.shape()], &[x.dtype()]).unwrap();
12263 assert_eq!(t.shape(), ps_shape, "shape drift for {op:?}");
12264 assert_eq!(t.dtype(), ps_dtype, "dtype drift for {op:?}");
12265 }
12266 }
12267
12268 #[test]
12269 fn destructive_input_release_is_some_zero() {
12270 assert_eq!(Op::Release.destructive_input(), Some(0));
12271 }
12272
12273 /// Phase 7.5 storage-unification B2: target_backend side-table
12274 /// is sparse — empty by default, set explicitly per node.
12275 #[test]
12276 fn target_backend_side_table_starts_empty() {
12277 let mut g = Graph::new();
12278 let id = g.push(Node {
12279 op: Op::Const,
12280 inputs: vec![],
12281 shape: Shape::from_dims(&[1]),
12282 dtype: DType::F32,
12283 });
12284 assert_eq!(g.target_backend(id), None);
12285 assert_eq!(g.target_backend_count(), 0);
12286 }
12287
12288 /// set_target_backend then read returns the same value.
12289 #[test]
12290 fn target_backend_set_and_read() {
12291 let mut g = Graph::new();
12292 let id = g.push(Node {
12293 op: Op::Const,
12294 inputs: vec![],
12295 shape: Shape::from_dims(&[1]),
12296 dtype: DType::F32,
12297 });
12298 g.set_target_backend(id, BackendId::Cpu);
12299 assert_eq!(g.target_backend(id), Some(BackendId::Cpu));
12300 assert_eq!(g.target_backend_count(), 1);
12301 }
12302
12303 /// set_target_backend overwrites prior value.
12304 #[test]
12305 fn target_backend_overwrite() {
12306 let mut g = Graph::new();
12307 let id = g.push(Node {
12308 op: Op::Const,
12309 inputs: vec![],
12310 shape: Shape::from_dims(&[1]),
12311 dtype: DType::F32,
12312 });
12313 g.set_target_backend(id, BackendId::Cpu);
12314 g.set_target_backend(id, BackendId::Cuda);
12315 assert_eq!(g.target_backend(id), Some(BackendId::Cuda));
12316 assert_eq!(g.target_backend_count(), 1);
12317 }
12318
12319 /// Layouts side-table: default fallback returns
12320 /// `Layout::contiguous(node.shape)` for any node without an
12321 /// explicit entry.
12322 #[test]
12323 fn layout_default_is_contiguous_over_node_shape() {
12324 let mut g = Graph::new();
12325 let id = g.push(Node {
12326 op: Op::Const,
12327 inputs: vec![],
12328 shape: Shape::from_dims(&[2, 3]),
12329 dtype: DType::F32,
12330 });
12331 assert!(!g.has_explicit_layout(id));
12332 assert_eq!(g.explicit_layout_count(), 0);
12333 let l = g.layout(id);
12334 assert_eq!(l.shape().dims(), &[2, 3]);
12335 assert!(l.is_contiguous());
12336 assert_eq!(l.start_offset(), 0);
12337 }
12338
12339 /// set_layout records a strided Layout (e.g. for a transpose
12340 /// view). Subsequent reads return the explicit entry.
12341 #[test]
12342 fn layout_explicit_strided_is_remembered() {
12343 let mut g = Graph::new();
12344 let id = g.push(Node {
12345 op: Op::Transpose,
12346 inputs: vec![],
12347 shape: Shape::from_dims(&[3, 2]),
12348 dtype: DType::F32,
12349 });
12350 // Strided view: shape stays [3, 2] (the post-transpose view),
12351 // strides are [1, 3] (row-of-output is column-of-source).
12352 let l = Layout::new(
12353 Shape::from_dims(&[3, 2]),
12354 fuel_ir::StrideVec::from_slice(&[1_isize, 3]),
12355 0,
12356 );
12357 g.set_layout(id, l);
12358 assert!(g.has_explicit_layout(id));
12359 assert_eq!(g.explicit_layout_count(), 1);
12360 assert_eq!(g.layout(id).stride(), &[1, 3]);
12361 assert!(!g.layout(id).is_contiguous());
12362 }
12363
12364 /// set_layout twice with different layouts overwrites.
12365 #[test]
12366 fn layout_set_overwrites() {
12367 use fuel_ir::StrideVec;
12368 let mut g = Graph::new();
12369 let id = g.push(Node {
12370 op: Op::Transpose,
12371 inputs: vec![],
12372 shape: Shape::from_dims(&[2]),
12373 dtype: DType::F32,
12374 });
12375 g.set_layout(id, Layout::contiguous(Shape::from_dims(&[2])));
12376 g.set_layout(
12377 id,
12378 Layout::new(Shape::from_dims(&[2]), StrideVec::from_slice(&[3_isize]), 1),
12379 );
12380 assert_eq!(g.layout(id).start_offset(), 1);
12381 assert_eq!(g.explicit_layout_count(), 1);
12382 }
12383
12384 /// Phase 7.5 work item G — empty-map invariants. End-to-end
12385 /// tests of the storage map (with real `Storage` values) live in
12386 /// fuel-core's `tensor::node_handle_tests`, since constructing a
12387 /// real `Storage` requires a `DynBackendStorage` implementation
12388 /// from a backend crate, and fuel-graph deliberately depends only
12389 /// on fuel-core-types.
12390 #[test]
12391 fn graph_storage_map_starts_empty() {
12392 let g = Graph::new();
12393 assert_eq!(g.storage_len(), 0);
12394 assert!(!g.has_storage(NodeId(0)));
12395 assert!(g.storage_for(NodeId(0)).is_none());
12396 }
12397
12398 #[test]
12399 fn conv2d_builder_emits_conv2d_node_with_right_shape() {
12400 // k=3 s=1 p=1 keeps H and W.
12401 let x = NodeHandle::from_f32(
12402 vec![0.0_f32; 2 * 4 * 4],
12403 Shape::from_dims(&[1, 2, 4, 4]),
12404 cpu_dev(),
12405 )
12406 .unwrap();
12407 let w = x
12408 .const_f32_like(
12409 vec![0.0_f32; 3 * 2 * 3 * 3],
12410 Shape::from_dims(&[3, 2, 3, 3]),
12411 )
12412 .unwrap();
12413 let b = x
12414 .const_f32_like(vec![0.0_f32; 3], Shape::from_dims(&[3]))
12415 .unwrap();
12416 let y = x.conv2d(&w, Some(&b), (1, 1), (1, 1), 1);
12417 assert_eq!(y.shape().dims(), &[1, 3, 4, 4]);
12418 }
12419
12420 #[test]
12421 fn conv2d_builder_stride_and_no_padding() {
12422 // k=3 s=2 p=0 on H=W=8 gives (8-3)/2+1 = 3.
12423 let x = NodeHandle::from_f32(
12424 vec![0.0_f32; 2 * 8 * 8],
12425 Shape::from_dims(&[1, 2, 8, 8]),
12426 cpu_dev(),
12427 )
12428 .unwrap();
12429 let w = x
12430 .const_f32_like(
12431 vec![0.0_f32; 4 * 2 * 3 * 3],
12432 Shape::from_dims(&[4, 2, 3, 3]),
12433 )
12434 .unwrap();
12435 let y = x.conv2d(&w, None, (2, 2), (0, 0), 1);
12436 assert_eq!(y.shape().dims(), &[1, 4, 3, 3]);
12437 }
12438
12439 #[test]
12440 fn conv2d_builder_depthwise_groups() {
12441 // groups=Cin=Cout=4 is the depthwise case. Weight per channel is [Cin/groups=1, kH, kW].
12442 let x = NodeHandle::from_f32(
12443 vec![0.0_f32; 4 * 4 * 4],
12444 Shape::from_dims(&[1, 4, 4, 4]),
12445 cpu_dev(),
12446 )
12447 .unwrap();
12448 let w = x
12449 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 1, 3, 3]))
12450 .unwrap();
12451 let y = x.conv2d(&w, None, (1, 1), (1, 1), 4);
12452 assert_eq!(y.shape().dims(), &[1, 4, 4, 4]);
12453 }
12454
12455 #[test]
12456 fn conv_transpose2d_builder_emits_node_with_right_shape() {
12457 // Hin=4, Kh=3, s=2, pad=1, out_pad=1 → Hout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12458 let x = NodeHandle::from_f32(
12459 vec![0.0_f32; 2 * 4 * 4],
12460 Shape::from_dims(&[1, 2, 4, 4]),
12461 cpu_dev(),
12462 )
12463 .unwrap();
12464 let w = x
12465 .const_f32_like(
12466 vec![0.0_f32; 2 * 3 * 3 * 3],
12467 Shape::from_dims(&[2, 3, 3, 3]),
12468 )
12469 .unwrap();
12470 let y = x.conv_transpose2d(&w, (2, 2), (1, 1), (1, 1), (1, 1), 1);
12471 assert_eq!(y.shape().dims(), &[1, 3, 8, 8]);
12472 }
12473
12474 #[test]
12475 fn conv_transpose1d_builder_shape_stride_2_pad_1() {
12476 // Lin=4, K=3, s=2, pad=1, out_pad=1, dil=1
12477 // Lout = (4-1)*2 + (3-1) + 1 + 1 - 2 = 8.
12478 let x = NodeHandle::from_f32(
12479 vec![0.0_f32; 2 * 4],
12480 Shape::from_dims(&[1, 2, 4]),
12481 cpu_dev(),
12482 )
12483 .unwrap();
12484 let w = x
12485 .const_f32_like(vec![0.0_f32; 2 * 3 * 3], Shape::from_dims(&[2, 3, 3]))
12486 .unwrap();
12487 let y = x.conv_transpose1d(&w, 2, 1, 1, 1, 1);
12488 assert_eq!(y.shape().dims(), &[1, 3, 8]);
12489 }
12490
12491 #[test]
12492 fn conv_transpose1d_builder_shape_stride_4_no_pad() {
12493 // Lin=2, K=4, s=4, pad=0, out_pad=0, dil=1
12494 // Lout = (2-1)*4 + (4-1) + 0 + 1 - 0 = 8.
12495 let x = NodeHandle::from_f32(vec![0.0_f32; 2], Shape::from_dims(&[1, 1, 2]), cpu_dev())
12496 .unwrap();
12497 let w = x
12498 .const_f32_like(vec![0.0_f32; 4], Shape::from_dims(&[1, 1, 4]))
12499 .unwrap();
12500 let y = x.conv_transpose1d(&w, 4, 0, 0, 1, 1);
12501 assert_eq!(y.shape().dims(), &[1, 1, 8]);
12502 }
12503
12504 #[test]
12505 fn conv_transpose1d_builder_with_groups() {
12506 // groups=2: input Cin=4 splits into 2 groups of 2; weight
12507 // Cin=4 first dim matches input; Cout/group=3 → total Cout=6.
12508 // Lin=3, K=3, s=1, pad=0, out_pad=0, dil=1 → Lout = (3-1)*1 + 2 + 0 + 1 = 5.
12509 let x = NodeHandle::from_f32(
12510 vec![0.0_f32; 4 * 3],
12511 Shape::from_dims(&[1, 4, 3]),
12512 cpu_dev(),
12513 )
12514 .unwrap();
12515 let w = x
12516 .const_f32_like(vec![0.0_f32; 4 * 3 * 3], Shape::from_dims(&[4, 3, 3]))
12517 .unwrap();
12518 let y = x.conv_transpose1d(&w, 1, 0, 0, 1, 2);
12519 assert_eq!(y.shape().dims(), &[1, 6, 5]);
12520 }
12521
12522 #[test]
12523 fn conv2d_backward_grads_have_input_shapes() {
12524 // Forward Y = conv2d(X, W) with stride=1, pad=1, groups=1 keeps H,W.
12525 // Backward should produce dX with X's shape and dW with W's shape.
12526 let x = NodeHandle::from_f32(
12527 (0..(2 * 4 * 4))
12528 .map(|i| (i as f32) * 0.05 - 0.5)
12529 .collect::<Vec<f32>>(),
12530 Shape::from_dims(&[1, 2, 4, 4]),
12531 cpu_dev(),
12532 )
12533 .unwrap();
12534 let w = x
12535 .const_f32_like(
12536 (0..(3 * 2 * 3 * 3))
12537 .map(|i| (i as f32) * 0.07 - 0.4)
12538 .collect::<Vec<f32>>(),
12539 Shape::from_dims(&[3, 2, 3, 3]),
12540 )
12541 .unwrap();
12542 let y = x.conv2d(&w, None, (1, 1), (1, 1), 1);
12543 let scalar_out = y.sum_all();
12544 let grads = scalar_out.backward();
12545 let dx = grads.get(&x).expect("conv2d backward produced no dX");
12546 let dw = grads.get(&w).expect("conv2d backward produced no dW");
12547 assert_eq!(dx.shape().dims(), x.shape().dims());
12548 assert_eq!(dw.shape().dims(), w.shape().dims());
12549 }
12550
12551 #[test]
12552 fn destructive_input_move_is_some_zero() {
12553 assert_eq!(
12554 Op::Move {
12555 target: DeviceLocation::Cpu
12556 }
12557 .destructive_input(),
12558 Some(0)
12559 );
12560 }
12561
12562 #[test]
12563 fn destructive_input_non_destructive_ops_are_none() {
12564 assert_eq!(
12565 Op::Copy {
12566 target: DeviceLocation::Cpu
12567 }
12568 .destructive_input(),
12569 None
12570 );
12571 assert_eq!(Op::Add.destructive_input(), None);
12572 assert_eq!(Op::Mul.destructive_input(), None);
12573 assert_eq!(Op::MatMul.destructive_input(), None);
12574 assert_eq!(Op::Relu.destructive_input(), None);
12575 }
12576
12577 #[test]
12578 fn move_to_device_emits_op_move_node() {
12579 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12580 let moved = a.move_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12581 let g = moved.graph().read().unwrap();
12582 match &g.node(moved.id()).op {
12583 Op::Move { target } => {
12584 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12585 }
12586 other => panic!("expected Op::Move, got {other:?}"),
12587 }
12588 assert_eq!(g.node(moved.id()).inputs, vec![a.id()]);
12589 // Output has the input's shape (residency changes, data doesn't).
12590 assert_eq!(g.node(moved.id()).shape.elem_count(), 2);
12591 }
12592
12593 #[test]
12594 fn copy_to_device_emits_op_copy_node() {
12595 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12596 let b = a.copy_to_device(DeviceLocation::Vulkan { gpu_id: 0 });
12597 let g = b.graph().read().unwrap();
12598 match &g.node(b.id()).op {
12599 Op::Copy { target } => {
12600 assert_eq!(*target, DeviceLocation::Vulkan { gpu_id: 0 });
12601 }
12602 other => panic!("expected Op::Copy, got {other:?}"),
12603 }
12604 // Source stays resident: the original `a` node still in the graph
12605 // and is the input of the Copy node.
12606 assert_eq!(g.node(b.id()).inputs, vec![a.id()]);
12607 }
12608
12609 #[test]
12610 fn release_builder_emits_op_release_node() {
12611 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12612 let released = a.release();
12613 let g = released.graph().read().unwrap();
12614 assert!(matches!(g.node(released.id()).op, Op::Release));
12615 assert_eq!(g.node(released.id()).inputs, vec![a.id()]);
12616 // Output is a zero-element marker.
12617 assert_eq!(g.node(released.id()).shape.elem_count(), 0);
12618 }
12619
12620 #[test]
12621 fn placement_is_none_by_default() {
12622 let a =
12623 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12624 assert_eq!(a.placement(), None);
12625 }
12626
12627 #[test]
12628 fn on_device_sets_placement_hint() {
12629 let a =
12630 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12631 let b = a
12632 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12633 .unwrap();
12634 // Only tag the Add node; the const leaves remain unplaced.
12635 let c = a.add(&b).on_device(DeviceLocation::Vulkan { gpu_id: 0 });
12636 assert_eq!(c.placement(), Some(DeviceLocation::Vulkan { gpu_id: 0 }));
12637 assert_eq!(a.placement(), None);
12638 assert_eq!(b.placement(), None);
12639 }
12640
12641 #[test]
12642 fn placement_survives_graph_re_reads() {
12643 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12644 let tagged = a.clone().on_device(DeviceLocation::Cpu);
12645 // Re-read from a fresh borrow — round-trips through the side-table.
12646 assert_eq!(
12647 tagged.graph().read().unwrap().placement(tagged.id()),
12648 Some(DeviceLocation::Cpu)
12649 );
12650 }
12651
12652 #[test]
12653 fn from_f32_creates_single_const_node() {
12654 let a =
12655 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12656 assert_eq!(a.graph().read().unwrap().len(), 1);
12657 assert_eq!(a.shape().dims(), &[3]);
12658 assert_eq!(a.dtype(), DType::F32);
12659 let node = a.graph().read().unwrap().node(a.id()).clone();
12660 // Phase 7.5 G2: factory now emits Op::Const + slot.
12661 assert!(matches!(node.op, Op::Const));
12662 assert!(node.inputs.is_empty());
12663 // The slot is populated with F32 storage.
12664 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12665 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
12666 }
12667
12668 #[test]
12669 fn add_appends_a_node_and_tracks_inputs() {
12670 let a =
12671 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12672 let b = a
12673 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12674 .unwrap();
12675 let c = a.add(&b);
12676 assert_eq!(c.graph().read().unwrap().len(), 3); // const, const, add
12677 let node = c.graph().read().unwrap().node(c.id()).clone();
12678 assert!(matches!(node.op, Op::Add));
12679 assert_eq!(node.inputs.len(), 2);
12680 assert_eq!(node.inputs[0], a.id());
12681 assert_eq!(node.inputs[1], b.id());
12682 assert_eq!(c.shape().dims(), &[3]);
12683 }
12684
12685 #[test]
12686 fn chained_ops_all_share_one_graph() {
12687 let a =
12688 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12689 let b = a
12690 .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
12691 .unwrap();
12692 let c = a.add(&b).mul(&a).sqr().relu();
12693 assert_eq!(c.graph().read().unwrap().len(), 6); // 2 consts + add + mul + sqr + relu
12694 assert_eq!(c.shape().dims(), &[3]);
12695 }
12696
12697 #[test]
12698 fn matmul_validates_shapes_and_produces_correct_output_shape() {
12699 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12700 let b = a
12701 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
12702 .unwrap();
12703 let c = a.matmul(&b);
12704 assert_eq!(c.shape().dims(), &[2, 4]);
12705 }
12706
12707 #[test]
12708 #[should_panic(expected = "shape mismatch")]
12709 fn add_panics_on_shape_mismatch() {
12710 let a =
12711 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12712 let b = a
12713 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12714 .unwrap();
12715 let _ = a.add(&b);
12716 }
12717
12718 #[test]
12719 #[should_panic(expected = "inner dim mismatch")]
12720 fn matmul_panics_on_inner_dim_mismatch() {
12721 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12722 let b = a
12723 .const_f32_like(vec![1.0; 8], Shape::from_dims(&[4, 2]))
12724 .unwrap();
12725 let _ = a.matmul(&b);
12726 }
12727
12728 #[test]
12729 #[should_panic(expected = "must live on the same graph")]
12730 fn cross_graph_op_is_rejected() {
12731 let a =
12732 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12733 let b =
12734 NodeHandle::from_f32(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12735 let _ = a.add(&b);
12736 }
12737
12738 // ----- graph identity + graph-scoped construction -----
12739 //
12740 // Two changes land together: (1) every Graph carries a monotonic GraphId so
12741 // an affinity failure can name WHICH graphs rather than only that they
12742 // differ; (2) constructors accept an existing graph, so a consumer never has
12743 // to discover `const_*_like` to build a second tensor.
12744
12745 #[test]
12746 fn each_new_graph_gets_a_distinct_id() {
12747 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12748 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12749 assert_ne!(a.graph_id(), b.graph_id());
12750 }
12751
12752 #[test]
12753 fn same_graph_tensors_share_one_id() {
12754 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12755 let b = a.const_f32_like(vec![2.0], Shape::from_dims(&[1])).unwrap();
12756 assert_eq!(a.graph_id(), b.graph_id());
12757 }
12758
12759 #[test]
12760 fn affinity_panic_names_both_graph_ids() {
12761 let a = NodeHandle::from_f32(vec![1.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12762 let b = NodeHandle::from_f32(vec![2.0], Shape::from_dims(&[1]), cpu_dev()).unwrap();
12763 let (ia, ib) = (a.graph_id(), b.graph_id());
12764 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| a.add(&b)))
12765 .expect_err("cross-graph add must panic");
12766 let text = err
12767 .downcast_ref::<String>()
12768 .cloned()
12769 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
12770 .expect("panic payload is a string");
12771 assert!(
12772 text.contains(&format!("#{ia}")) && text.contains(&format!("#{ib}")),
12773 "affinity panic must name BOTH graph ids so the caller can see it made two; got: {text}",
12774 );
12775 }
12776
12777 #[test]
12778 fn from_f32_on_builds_into_the_given_graph() {
12779 let root =
12780 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12781 let w = NodeHandle::from_f32_on(
12782 root.graph(),
12783 vec![4.0, 5.0, 6.0],
12784 Shape::from_dims(&[3]),
12785 cpu_dev(),
12786 )
12787 .unwrap();
12788 assert_eq!(root.graph_id(), w.graph_id());
12789 assert!(Arc::ptr_eq(root.graph(), w.graph()));
12790 }
12791
12792 #[test]
12793 fn graph_scoped_construction_composes_without_an_anchor() {
12794 // The program that could not previously be written: build two tensors
12795 // and combine them, without discovering `const_*_like`.
12796 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12797 let a = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev())
12798 .unwrap();
12799 let b = NodeHandle::from_f32_on(&g, vec![1.0; 6], Shape::from_dims(&[3, 2]), cpu_dev())
12800 .unwrap();
12801 let y = a.matmul(&b);
12802 assert_eq!(y.shape().dims(), &[2, 2]);
12803 assert_eq!(y.graph_id(), a.graph_id());
12804 }
12805
12806 #[test]
12807 fn graph_scoped_constructors_cover_every_dtype() {
12808 let g: SharedGraph = Arc::new(RwLock::new(Graph::new()));
12809 let s = Shape::from_dims(&[1]);
12810 let f32t = NodeHandle::from_f32_on(&g, vec![1.0f32], s.clone(), cpu_dev()).unwrap();
12811 let f64t = NodeHandle::from_f64_on(&g, vec![1.0f64], s.clone(), cpu_dev()).unwrap();
12812 let bf16t =
12813 NodeHandle::from_bf16_on(&g, vec![half::bf16::from_f32(1.0)], s.clone(), cpu_dev())
12814 .unwrap();
12815 let f16t =
12816 NodeHandle::from_f16_on(&g, vec![half::f16::from_f32(1.0)], s.clone(), cpu_dev())
12817 .unwrap();
12818 let u32t = NodeHandle::from_u32_on(&g, vec![1u32], s, cpu_dev()).unwrap();
12819 for t in [&f64t, &bf16t, &f16t, &u32t] {
12820 assert_eq!(
12821 t.graph_id(),
12822 f32t.graph_id(),
12823 "all must share the given graph"
12824 );
12825 }
12826 assert_eq!(f64t.dtype(), DType::F64);
12827 assert_eq!(bf16t.dtype(), DType::BF16);
12828 assert_eq!(f16t.dtype(), DType::F16);
12829 assert_eq!(u32t.dtype(), DType::U32);
12830 }
12831
12832 // ----- multi-dtype graph builders -----
12833
12834 #[test]
12835 fn from_f64_tags_node_with_f64_dtype() {
12836 let a =
12837 NodeHandle::from_f64(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12838 assert_eq!(a.dtype(), DType::F64);
12839 let node = a.graph().read().unwrap().node(a.id()).clone();
12840 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
12841 assert!(matches!(node.op, Op::Const));
12842 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12843 assert_eq!(slot.read().unwrap().dtype(), DType::F64);
12844 }
12845
12846 #[test]
12847 fn from_bf16_tags_node_with_bf16_dtype() {
12848 let a = NodeHandle::from_bf16(
12849 vec![bf16::from_f32(1.0), bf16::from_f32(2.0)],
12850 Shape::from_dims(&[2]),
12851 cpu_dev(),
12852 )
12853 .unwrap();
12854 assert_eq!(a.dtype(), DType::BF16);
12855 let node = a.graph().read().unwrap().node(a.id()).clone();
12856 assert!(matches!(node.op, Op::Const));
12857 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12858 assert_eq!(slot.read().unwrap().dtype(), DType::BF16);
12859 }
12860
12861 #[test]
12862 fn from_f16_tags_node_with_f16_dtype() {
12863 let a = NodeHandle::from_f16(
12864 vec![f16::from_f32(1.0), f16::from_f32(2.0)],
12865 Shape::from_dims(&[2]),
12866 cpu_dev(),
12867 )
12868 .unwrap();
12869 assert_eq!(a.dtype(), DType::F16);
12870 let node = a.graph().read().unwrap().node(a.id()).clone();
12871 assert!(matches!(node.op, Op::Const));
12872 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
12873 assert_eq!(slot.read().unwrap().dtype(), DType::F16);
12874 }
12875
12876 #[test]
12877 #[should_panic(expected = "dtype mismatch")]
12878 fn add_panics_on_mixed_dtype() {
12879 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
12880 let b = a
12881 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
12882 .unwrap();
12883 let _ = a.add(&b);
12884 }
12885
12886 // ----- transpose -----
12887
12888 #[test]
12889 fn transpose_swaps_shape_dims() {
12890 let a = NodeHandle::from_f32(
12891 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
12892 Shape::from_dims(&[2, 3]),
12893 cpu_dev(),
12894 )
12895 .unwrap();
12896 let t = a.transpose();
12897 assert_eq!(t.shape().dims(), &[3, 2]);
12898 let node = t.graph().read().unwrap().node(t.id()).clone();
12899 assert!(matches!(node.op, Op::Transpose));
12900 assert_eq!(node.inputs, vec![a.id()]);
12901 }
12902
12903 #[test]
12904 #[should_panic(expected = "rank ≥ 2")]
12905 fn transpose_rejects_rank_1() {
12906 let a =
12907 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
12908 let _ = a.transpose();
12909 }
12910
12911 #[test]
12912 fn transpose_on_rank_3_swaps_last_two_dims() {
12913 // [2, 3, 4] → [2, 4, 3]
12914 let a = NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev())
12915 .unwrap();
12916 let t = a.transpose();
12917 assert_eq!(t.shape().dims(), &[2, 4, 3]);
12918 }
12919
12920 // ----- additional builder validation tests -----
12921
12922 #[test]
12923 fn matmul_rank_3_batched_shape() {
12924 // [2, 3, 4] @ [2, 4, 5] → [2, 3, 5]
12925 let a =
12926 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12927 let b = a
12928 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12929 .unwrap();
12930 let c = a.matmul(&b);
12931 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12932 }
12933
12934 #[test]
12935 #[should_panic(expected = "batch dim mismatch")]
12936 fn matmul_rank_3_rejects_batch_dim_mismatch() {
12937 let a =
12938 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12939 let b = a
12940 .const_f32_like(vec![0.0; 60], Shape::from_dims(&[3, 4, 5]))
12941 .unwrap();
12942 let _ = a.matmul(&b);
12943 }
12944
12945 #[test]
12946 fn matmul_auto_broadcasts_rank_2_rhs_against_batched_lhs() {
12947 // [batch=2, seq=3, k=4] @ [k=4, n=5] → [2, 3, 5]. This is the
12948 // canonical "linear layer across a batch" pattern and should
12949 // Just Work without an explicit broadcast_to on the RHS.
12950 let a =
12951 NodeHandle::from_f32(vec![0.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
12952 let b = a
12953 .const_f32_like(vec![0.0; 20], Shape::from_dims(&[4, 5]))
12954 .unwrap();
12955 let c = a.matmul(&b);
12956 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12957 }
12958
12959 #[test]
12960 fn matmul_auto_broadcasts_rank_2_lhs_against_batched_rhs() {
12961 // [m=3, k=4] @ [batch=2, k=4, n=5] → [2, 3, 5].
12962 let a = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
12963 let b = a
12964 .const_f32_like(vec![0.0; 40], Shape::from_dims(&[2, 4, 5]))
12965 .unwrap();
12966 let c = a.matmul(&b);
12967 assert_eq!(c.shape().dims(), &[2, 3, 5]);
12968 }
12969
12970 #[test]
12971 fn concat_output_shape_sums_along_dim() {
12972 // [2, 3] concat [2, 4] along dim 1 → [2, 7]
12973 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12974 let b = a
12975 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
12976 .unwrap();
12977 let c = a.concat(&b, 1);
12978 assert_eq!(c.shape().dims(), &[2, 7]);
12979 }
12980
12981 #[test]
12982 #[should_panic(expected = "non-dim shapes")]
12983 fn concat_rejects_nondim_shape_mismatch() {
12984 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12985 let b = a
12986 .const_f32_like(vec![0.0; 12], Shape::from_dims(&[3, 4]))
12987 .unwrap();
12988 let _ = a.concat(&b, 1);
12989 }
12990
12991 #[test]
12992 #[should_panic(expected = "rank mismatch")]
12993 fn concat_rejects_rank_mismatch() {
12994 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
12995 let b = a
12996 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[6]))
12997 .unwrap();
12998 let _ = a.concat(&b, 0);
12999 }
13000
13001 #[test]
13002 fn slice_shrinks_only_the_slice_dim() {
13003 // [3, 4] slice dim 1, start 1, len 2 → [3, 2]
13004 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13005 let s = x.slice(1, 1, 2);
13006 assert_eq!(s.shape().dims(), &[3, 2]);
13007 }
13008
13009 #[test]
13010 #[should_panic(expected = "exceeds dim size")]
13011 fn slice_rejects_out_of_bounds_range() {
13012 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13013 let _ = x.slice(1, 1, 3); // start=1, len=3 → would need dim>=4
13014 }
13015
13016 #[test]
13017 fn broadcast_add_shape_promotes_to_common_shape() {
13018 // [4, 1] + [1, 3] → [4, 3]
13019 let a = NodeHandle::from_f32(vec![0.0; 4], Shape::from_dims(&[4, 1]), cpu_dev()).unwrap();
13020 let b = a
13021 .const_f32_like(vec![0.0; 3], Shape::from_dims(&[1, 3]))
13022 .unwrap();
13023 let c = a.broadcast_add(&b);
13024 assert_eq!(c.shape().dims(), &[4, 3]);
13025 }
13026
13027 #[test]
13028 fn broadcast_sub_pads_shorter_shape_with_leading_ones() {
13029 // [3] - [2, 3] → [2, 3]
13030 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13031 let b = a
13032 .const_f32_like(vec![0.0; 6], Shape::from_dims(&[2, 3]))
13033 .unwrap();
13034 let c = a.broadcast_sub(&b);
13035 assert_eq!(c.shape().dims(), &[2, 3]);
13036 }
13037
13038 #[test]
13039 #[should_panic(expected = "incompatible shapes")]
13040 fn broadcast_add_rejects_incompatible_shapes() {
13041 let a = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13042 let b = a
13043 .const_f32_like(vec![0.0; 8], Shape::from_dims(&[2, 4]))
13044 .unwrap();
13045 let _ = a.broadcast_add(&b);
13046 }
13047
13048 #[test]
13049 fn argmax_dim_is_u32_and_removes_reduced_dim() {
13050 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13051 let am = x.argmax_dim(1);
13052 assert_eq!(am.dtype(), DType::U32);
13053 assert_eq!(am.shape().dims(), &[2]);
13054 }
13055
13056 #[test]
13057 #[should_panic(expected = "out of bounds")]
13058 fn argmax_dim_rejects_bad_dim() {
13059 let x = NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13060 let _ = x.argmax_dim(5);
13061 }
13062
13063 #[test]
13064 fn index_add_shape_validation() {
13065 let base = NodeHandle::from_f32(vec![0.0; 10], Shape::from_dims(&[10]), cpu_dev()).unwrap();
13066 let idx = base
13067 .const_u32_like(vec![1, 3, 5], Shape::from_dims(&[3]))
13068 .unwrap();
13069 let src = base
13070 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13071 .unwrap();
13072 let out = base.index_add(0, &idx, &src);
13073 assert_eq!(out.shape().dims(), &[10]);
13074 }
13075
13076 #[test]
13077 #[should_panic(expected = "dtypes must match")]
13078 fn index_add_rejects_dtype_mismatch() {
13079 let base = NodeHandle::from_f32(vec![0.0; 5], Shape::from_dims(&[5]), cpu_dev()).unwrap();
13080 let idx = base
13081 .const_u32_like(vec![0, 2], Shape::from_dims(&[2]))
13082 .unwrap();
13083 let src = base
13084 .const_f64_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13085 .unwrap();
13086 let _ = base.index_add(0, &idx, &src);
13087 }
13088
13089 #[test]
13090 fn scatter_add_validates_index_matches_src() {
13091 let base =
13092 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13093 let idx = base
13094 .const_u32_like(vec![0, 2, 1, 0], Shape::from_dims(&[2, 2]))
13095 .unwrap();
13096 let src = base
13097 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13098 .unwrap();
13099 let out = base.scatter_add(1, &idx, &src);
13100 assert_eq!(out.shape().dims(), &[2, 3]);
13101 }
13102
13103 #[test]
13104 #[should_panic(expected = "same shape")]
13105 fn scatter_add_rejects_index_src_shape_mismatch() {
13106 let base =
13107 NodeHandle::from_f32(vec![0.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13108 let idx = base
13109 .const_u32_like(vec![0, 1], Shape::from_dims(&[2]))
13110 .unwrap();
13111 let src = base
13112 .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[2, 2]))
13113 .unwrap();
13114 let _ = base.scatter_add(1, &idx, &src);
13115 }
13116
13117 #[test]
13118 fn reduce_sum_to_validates_compatibility() {
13119 // [3, 4] can reduce to [4] (sum along dim 0) or [3, 1] (sum along dim 1).
13120 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13121 let r1 = x.reduce_sum_to(Shape::from_dims(&[4]));
13122 assert_eq!(r1.shape().dims(), &[4]);
13123 let r2 = x.reduce_sum_to(Shape::from_dims(&[3, 1]));
13124 assert_eq!(r2.shape().dims(), &[3, 1]);
13125 }
13126
13127 #[test]
13128 #[should_panic(expected = "incompatible")]
13129 fn reduce_sum_to_rejects_non_broadcast_target() {
13130 // [3, 4] cannot reduce to [3, 2] — target must be broadcast-into-source.
13131 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13132 let _ = x.reduce_sum_to(Shape::from_dims(&[3, 2]));
13133 }
13134
13135 #[test]
13136 fn unsqueeze_inserts_size_one_dim() {
13137 let x = NodeHandle::from_f32(
13138 vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
13139 Shape::from_dims(&[2, 3]),
13140 cpu_dev(),
13141 )
13142 .unwrap();
13143 // Insert at position 0: [2, 3] -> [1, 2, 3]
13144 let y0 = x.unsqueeze(0);
13145 assert_eq!(y0.shape().dims(), &[1, 2, 3]);
13146 // Insert at position 1: [2, 3] -> [2, 1, 3]
13147 let y1 = x.unsqueeze(1);
13148 assert_eq!(y1.shape().dims(), &[2, 1, 3]);
13149 // Insert at the end (rank): [2, 3] -> [2, 3, 1]
13150 let y2 = x.unsqueeze(2);
13151 assert_eq!(y2.shape().dims(), &[2, 3, 1]);
13152 // Op variant correctness.
13153 let g = x.graph().read().unwrap();
13154 assert!(matches!(g.node(y0.id()).op, Op::Unsqueeze { dim: 0 }));
13155 assert!(matches!(g.node(y1.id()).op, Op::Unsqueeze { dim: 1 }));
13156 assert!(matches!(g.node(y2.id()).op, Op::Unsqueeze { dim: 2 }));
13157 }
13158
13159 #[test]
13160 #[should_panic(expected = "out of bounds")]
13161 fn unsqueeze_rejects_dim_above_rank() {
13162 let x = NodeHandle::from_f32(vec![1.0; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
13163 // dim=2 > rank=1 → panic.
13164 let _ = x.unsqueeze(2);
13165 }
13166
13167 #[test]
13168 fn unsqueeze_layout_side_table_populated() {
13169 // After Graph::push auto-derives the Layout side-table for view
13170 // ops, an unsqueeze node should have an explicit layout entry
13171 // with a stride-0 axis at the inserted position.
13172 let x = NodeHandle::from_f32(
13173 vec![1.0, 2.0, 3.0, 4.0],
13174 Shape::from_dims(&[2, 2]),
13175 cpu_dev(),
13176 )
13177 .unwrap();
13178 let y = x.unsqueeze(1);
13179 let g = x.graph().read().unwrap();
13180 assert!(
13181 g.has_explicit_layout(y.id()),
13182 "Graph::push should auto-populate layout for view ops"
13183 );
13184 let l = g.layout(y.id());
13185 assert_eq!(l.shape().dims(), &[2, 1, 2]);
13186 // Stride at the inserted axis should be 0 (per the convention
13187 // chosen in Layout::unsqueeze).
13188 assert_eq!(l.stride()[1], 0);
13189 }
13190
13191 #[test]
13192 fn reduce_max_to_validates_compatibility() {
13193 // [3, 4] can reduce to [4] (max along dim 0) or [3, 1] (max along dim 1).
13194 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13195 let r1 = x.reduce_max_to(Shape::from_dims(&[4]));
13196 assert_eq!(r1.shape().dims(), &[4]);
13197 assert!(matches!(
13198 r1.graph().read().unwrap().node(r1.id()).op,
13199 Op::ReduceMaxTo(_)
13200 ));
13201 let r2 = x.reduce_max_to(Shape::from_dims(&[3, 1]));
13202 assert_eq!(r2.shape().dims(), &[3, 1]);
13203 }
13204
13205 #[test]
13206 #[should_panic(expected = "incompatible")]
13207 fn reduce_max_to_rejects_non_broadcast_target() {
13208 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13209 let _ = x.reduce_max_to(Shape::from_dims(&[3, 2]));
13210 }
13211
13212 #[test]
13213 fn reshape_preserves_element_count() {
13214 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13215 let r = x.reshape(Shape::from_dims(&[2, 6]));
13216 assert_eq!(r.shape().dims(), &[2, 6]);
13217 }
13218
13219 #[test]
13220 #[should_panic(expected = "element count mismatch")]
13221 fn reshape_rejects_different_element_count() {
13222 let x = NodeHandle::from_f32(vec![0.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13223 let _ = x.reshape(Shape::from_dims(&[3, 3]));
13224 }
13225
13226 #[test]
13227 #[should_panic(expected = "same graph")]
13228 fn concat_across_graphs_panics() {
13229 let a = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13230 let b = NodeHandle::from_f32(vec![0.0; 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13231 let _ = a.concat(&b, 0);
13232 }
13233
13234 #[test]
13235 fn scalar_ops_preserve_shape_and_dtype() {
13236 let x =
13237 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13238 let y = x.add_scalar(5.0).mul_scalar(2.0).powi(2).clamp(0.0, 100.0);
13239 assert_eq!(y.shape().dims(), &[3]);
13240 assert_eq!(y.dtype(), DType::F32);
13241 }
13242
13243 #[test]
13244 fn maximum_requires_matching_shapes() {
13245 let a =
13246 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13247 let b = a
13248 .const_f32_like(vec![4.0, 1.0, 5.0], Shape::from_dims(&[3]))
13249 .unwrap();
13250 let m = a.maximum(&b);
13251 assert_eq!(m.shape().dims(), &[3]);
13252 }
13253
13254 #[test]
13255 #[should_panic(expected = "shape mismatch")]
13256 fn maximum_rejects_shape_mismatch() {
13257 let a =
13258 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13259 let b = a
13260 .const_f32_like(vec![1.0, 2.0], Shape::from_dims(&[2]))
13261 .unwrap();
13262 let _ = a.maximum(&b);
13263 }
13264
13265 // ----- topo_order -----
13266
13267 #[test]
13268 fn topo_order_places_inputs_before_dependents() {
13269 // Build: c = (a + b) * a
13270 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13271 let b = a
13272 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13273 .unwrap();
13274 let sum = a.add(&b);
13275 let c = sum.mul(&a);
13276 let order = topo_order(&c.graph().read().unwrap(), c.id());
13277 // The order should contain exactly 4 nodes (a, b, sum, c) and
13278 // place each input strictly before its dependents.
13279 assert_eq!(order.len(), 4);
13280 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13281 assert!(pos(a.id()) < pos(sum.id()));
13282 assert!(pos(b.id()) < pos(sum.id()));
13283 assert!(pos(sum.id()) < pos(c.id()));
13284 assert!(pos(a.id()) < pos(c.id()));
13285 }
13286
13287 #[test]
13288 fn topo_order_visits_each_node_once_when_shared() {
13289 // (a + a) — `a` appears twice in the Add's inputs but the topo
13290 // pass should still visit it exactly once.
13291 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13292 let double = a.add(&a);
13293 let order = topo_order(&double.graph().read().unwrap(), double.id());
13294 assert_eq!(order.len(), 2);
13295 assert_eq!(order[0], a.id());
13296 assert_eq!(order[1], double.id());
13297 }
13298
13299 #[test]
13300 fn topo_order_multi_unions_multiple_roots() {
13301 // Build a DAG where two "output" nodes share a common input.
13302 //
13303 // a ─┬─> add1 (= a + b) ← root_1
13304 // └─> add2 (= a + c) ← root_2
13305 // b ───> add1
13306 // c ───> add2
13307 //
13308 // topo_order_multi(&[add1, add2]) must contain all 5 nodes
13309 // (a, b, c, add1, add2) with a before add1/add2 and b before
13310 // add1 and c before add2.
13311 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13312 let b = a
13313 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13314 .unwrap();
13315 let c = a
13316 .const_f32_like(vec![5.0, 6.0], Shape::from_dims(&[2]))
13317 .unwrap();
13318 let add1 = a.add(&b);
13319 let add2 = a.add(&c);
13320 let order = topo_order_multi(&add1.graph().read().unwrap(), &[add1.id(), add2.id()]);
13321 assert_eq!(order.len(), 5);
13322 let pos = |id: NodeId| order.iter().position(|&x| x == id).unwrap();
13323 assert!(pos(a.id()) < pos(add1.id()));
13324 assert!(pos(a.id()) < pos(add2.id()));
13325 assert!(pos(b.id()) < pos(add1.id()));
13326 assert!(pos(c.id()) < pos(add2.id()));
13327 }
13328
13329 // ----- backward -----
13330
13331 #[test]
13332 fn backward_of_lone_const_seeds_ones() {
13333 // backward(a) gives a = 1s (the root's upstream is a ones tensor,
13334 // which is the gradient stored for the root itself).
13335 let a =
13336 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13337 let grads = a.backward();
13338 let g_a = grads.get(&a).expect("root gets a seed gradient");
13339 // The seed is a Const ones node of matching shape. Phase 7.5
13340 // G2: gradient consts are slot-rooted Op::Const — no
13341 // host-side ConstData on the node.
13342 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13343 assert!(matches!(node.op, Op::Const));
13344 let slot = g_a.graph().read().unwrap().storage_for(g_a.id()).unwrap();
13345 assert_eq!(slot.read().unwrap().dtype(), DType::F32);
13346 assert_eq!(g_a.shape().dims(), &[3]);
13347 }
13348
13349 #[test]
13350 fn backward_of_add_passes_upstream_through() {
13351 // c = a + b ⇒ dc/da = 1, dc/db = 1.
13352 // Upstream seed is a ones tensor. So grad_a and grad_b are both
13353 // the same ones node (no new math emitted for Add's backward).
13354 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13355 let b = a
13356 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
13357 .unwrap();
13358 let c = a.add(&b);
13359 let grads = c.backward();
13360 let g_a = grads.get(&a).unwrap();
13361 let g_b = grads.get(&b).unwrap();
13362 assert_eq!(g_a.id(), g_b.id(), "Add backward routes upstream unchanged");
13363 assert_eq!(g_a.shape().dims(), &[2]);
13364 }
13365
13366 #[test]
13367 fn backward_of_mul_emits_two_mul_nodes() {
13368 // c = a * b ⇒ dc/da = b, dc/db = a (upstream is 1s).
13369 // The backward pass should emit two new Mul nodes (upstream * b,
13370 // upstream * a).
13371 let a = NodeHandle::from_f32(vec![2.0, 3.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13372 let b = a
13373 .const_f32_like(vec![5.0, 7.0], Shape::from_dims(&[2]))
13374 .unwrap();
13375 let c = a.mul(&b);
13376 let nodes_before = c.graph().read().unwrap().len();
13377 let grads = c.backward();
13378 let nodes_after = grads.graph.read().unwrap().len();
13379 // Backward adds: one ones const + two Mul nodes = 3 new nodes.
13380 assert_eq!(nodes_after - nodes_before, 3);
13381 let g_a = grads.get(&a).unwrap();
13382 let g_b = grads.get(&b).unwrap();
13383 // Both gradient nodes should be Mul nodes.
13384 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13385 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13386 assert!(matches!(node_a.op, Op::Mul));
13387 assert!(matches!(node_b.op, Op::Mul));
13388 }
13389
13390 #[test]
13391 fn backward_accumulates_when_node_used_twice() {
13392 // c = a * a ⇒ dc/da = 2a via two separate contributions.
13393 // After backward, the gradient for a should be an Add node
13394 // combining the two Mul contributions (one from each input slot
13395 // of the forward Mul).
13396 let a = NodeHandle::from_f32(vec![3.0, 5.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13397 let c = a.mul(&a);
13398 let grads = c.backward();
13399 let g_a = grads.get(&a).unwrap();
13400 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13401 // The final gradient for `a` is an Add combining the two
13402 // upstream-times-other-input contributions.
13403 assert!(
13404 matches!(node.op, Op::Add),
13405 "expected accumulated gradient to be an Add node, got {:?}",
13406 node.op,
13407 );
13408 }
13409
13410 #[test]
13411 fn backward_of_matmul_emits_transpose_and_matmul_nodes() {
13412 // Forward: Y = A @ B, A:[2,3], B:[3,4], Y:[2,4].
13413 // Backward: dA = dY @ B^T (shape [2,3]), dB = A^T @ dY (shape [3,4]).
13414 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13415 let b = a
13416 .const_f32_like(vec![1.0; 12], Shape::from_dims(&[3, 4]))
13417 .unwrap();
13418 let y = a.matmul(&b);
13419 let grads = y.backward();
13420 let g_a = grads.get(&a).unwrap();
13421 let g_b = grads.get(&b).unwrap();
13422 // Gradient shapes must match the forward shapes.
13423 assert_eq!(g_a.shape().dims(), &[2, 3]);
13424 assert_eq!(g_b.shape().dims(), &[3, 4]);
13425 // Both should be MatMul nodes (the outermost op of each gradient).
13426 let node_a = g_a.graph().read().unwrap().node(g_a.id()).clone();
13427 let node_b = g_b.graph().read().unwrap().node(g_b.id()).clone();
13428 assert!(matches!(node_a.op, Op::MatMul));
13429 assert!(matches!(node_b.op, Op::MatMul));
13430 }
13431
13432 // ----- new builder validation -----
13433
13434 #[test]
13435 fn cast_tags_node_with_target_dtype() {
13436 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13437 let b = a.cast(DType::F64);
13438 assert_eq!(b.dtype(), DType::F64);
13439 assert_eq!(b.shape().dims(), &[2]);
13440 let node = b.graph().read().unwrap().node(b.id()).clone();
13441 assert!(matches!(node.op, Op::Cast(DType::F64)));
13442 }
13443
13444 #[test]
13445 fn broadcast_to_accepts_right_aligned_expansion() {
13446 // [3] broadcasts to [2, 3]: pad with leading 1, expand.
13447 let a =
13448 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13449 let b = a.broadcast_to(Shape::from_dims(&[2, 3]));
13450 assert_eq!(b.shape().dims(), &[2, 3]);
13451 }
13452
13453 #[test]
13454 fn broadcast_to_accepts_size_one_expansion() {
13455 // [3, 1] broadcasts to [3, 4]: size-1 dim expands.
13456 let a = NodeHandle::from_f32(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3, 1]), cpu_dev())
13457 .unwrap();
13458 let b = a.broadcast_to(Shape::from_dims(&[3, 4]));
13459 assert_eq!(b.shape().dims(), &[3, 4]);
13460 }
13461
13462 #[test]
13463 #[should_panic(expected = "incompatible")]
13464 fn broadcast_to_rejects_incompatible_dim() {
13465 // [3] cannot broadcast to [2, 4] — the source dim 3 must match 4.
13466 let a =
13467 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13468 let _ = a.broadcast_to(Shape::from_dims(&[2, 4]));
13469 }
13470
13471 #[test]
13472 fn sum_all_produces_rank_zero_output() {
13473 let a =
13474 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13475 let s = a.sum_all();
13476 assert_eq!(s.shape().dims(), &[] as &[usize]);
13477 }
13478
13479 #[test]
13480 fn sum_dim_removes_reduced_dim_from_shape() {
13481 let a =
13482 NodeHandle::from_f32(vec![1.0; 24], Shape::from_dims(&[2, 3, 4]), cpu_dev()).unwrap();
13483 // Reducing dim 1 should give shape [2, 4].
13484 let s = a.sum_dim(1);
13485 assert_eq!(s.shape().dims(), &[2, 4]);
13486 }
13487
13488 #[test]
13489 #[should_panic(expected = "out of bounds")]
13490 fn sum_dim_rejects_bad_dim() {
13491 let a =
13492 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13493 let _ = a.sum_dim(5);
13494 }
13495
13496 #[test]
13497 fn softmax_and_layer_norm_preserve_shape() {
13498 let a = NodeHandle::from_f32(
13499 vec![1.0, 2.0, 3.0, 4.0],
13500 Shape::from_dims(&[2, 2]),
13501 cpu_dev(),
13502 )
13503 .unwrap();
13504 assert_eq!(a.softmax_last_dim().shape().dims(), &[2, 2]);
13505 assert_eq!(a.layer_norm_last_dim(1e-5).shape().dims(), &[2, 2]);
13506 }
13507
13508 #[test]
13509 fn neg_sub_div_sqrt_log_sin_cos_tanh_sigmoid_all_build() {
13510 // Smoke test: every new builder produces a node with the expected
13511 // shape and dtype. Numerical correctness is exercised in exec.rs.
13512 let a =
13513 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13514 let b = a
13515 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
13516 .unwrap();
13517 for tensor in [
13518 a.neg(),
13519 a.sub(&b),
13520 a.div(&b),
13521 a.sqrt(),
13522 a.log(),
13523 a.sin(),
13524 a.cos(),
13525 a.tanh(),
13526 a.sigmoid(),
13527 a.step(),
13528 ] {
13529 assert_eq!(tensor.shape().dims(), &[3]);
13530 assert_eq!(tensor.dtype(), DType::F32);
13531 }
13532 }
13533
13534 // ----- index tensors and indexing ops -----
13535
13536 #[test]
13537 fn from_u32_tags_node_with_u32_dtype() {
13538 let a = NodeHandle::from_u32(vec![1, 2, 3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13539 assert_eq!(a.dtype(), DType::U32);
13540 let node = a.graph().read().unwrap().node(a.id()).clone();
13541 // Phase 7.5 G2: slot-rooted Const, dtype validated via slot.
13542 assert!(matches!(node.op, Op::Const));
13543 let slot = a.graph().read().unwrap().storage_for(a.id()).unwrap();
13544 assert_eq!(slot.read().unwrap().dtype(), DType::U32);
13545 }
13546
13547 #[test]
13548 fn index_select_produces_shape_with_dim_replaced() {
13549 let data =
13550 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13551 let idx = data
13552 .const_u32_like(vec![0, 2, 1, 0, 2], Shape::from_dims(&[5]))
13553 .unwrap();
13554 let out = data.index_select(0, &idx);
13555 assert_eq!(out.shape().dims(), &[5, 4]);
13556 assert_eq!(out.dtype(), DType::F32);
13557 }
13558
13559 #[test]
13560 #[should_panic(expected = "must be U32")]
13561 fn index_select_rejects_float_index() {
13562 let data =
13563 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13564 let bad = data
13565 .const_f32_like(vec![0.0, 1.0], Shape::from_dims(&[2]))
13566 .unwrap();
13567 let _ = data.index_select(0, &bad);
13568 }
13569
13570 #[test]
13571 #[should_panic(expected = "must be rank 1")]
13572 fn index_select_rejects_multi_dim_index() {
13573 let data =
13574 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13575 let idx = data
13576 .const_u32_like(vec![0, 1, 0, 1], Shape::from_dims(&[2, 2]))
13577 .unwrap();
13578 let _ = data.index_select(0, &idx);
13579 }
13580
13581 #[test]
13582 fn gather_output_shape_matches_index_shape() {
13583 let data =
13584 NodeHandle::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), cpu_dev()).unwrap();
13585 // Index shape [2, 5] — same rank as data (rank 2).
13586 let idx = data
13587 .const_u32_like(vec![0; 10], Shape::from_dims(&[2, 5]))
13588 .unwrap();
13589 let out = data.gather(1, &idx);
13590 assert_eq!(out.shape().dims(), &[2, 5]);
13591 }
13592
13593 #[test]
13594 #[should_panic(expected = "same rank")]
13595 fn gather_rejects_rank_mismatch() {
13596 let data =
13597 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13598 // Rank-1 index for rank-2 data → error.
13599 let idx = data
13600 .const_u32_like(vec![0, 1, 0], Shape::from_dims(&[3]))
13601 .unwrap();
13602 let _ = data.gather(1, &idx);
13603 }
13604
13605 #[test]
13606 fn backward_of_relu_emits_step_node() {
13607 // Before: this used to panic. After adding Step + Relu backward,
13608 // it should successfully emit a backward graph rooted in a Mul
13609 // whose second input is a Step node.
13610 let a =
13611 NodeHandle::from_f32(vec![-1.0, 2.0, -3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13612 let y = a.relu();
13613 let grads = y.backward();
13614 let g_a = grads.get(&a).unwrap();
13615 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13616 assert!(matches!(node.op, Op::Mul));
13617 // Find a Step node somewhere in the node's inputs.
13618 let any_step = node
13619 .inputs
13620 .iter()
13621 .any(|&id| matches!(g_a.graph().read().unwrap().node(id).op, Op::Step,));
13622 assert!(any_step, "Relu backward must reference a Step node");
13623 }
13624
13625 #[test]
13626 fn recip_and_abs_builders_produce_unary_nodes() {
13627 // Smoke test: NodeHandle::recip()/abs() build single-input nodes
13628 // with the expected op variant and shape passthrough.
13629 let a =
13630 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13631 let r = a.recip();
13632 let b = a.abs();
13633 assert_eq!(r.shape().dims(), &[3]);
13634 assert_eq!(b.shape().dims(), &[3]);
13635 let r_node = r.graph().read().unwrap().node(r.id()).clone();
13636 let b_node = b.graph().read().unwrap().node(b.id()).clone();
13637 assert!(matches!(r_node.op, Op::Recip));
13638 assert!(matches!(b_node.op, Op::Abs));
13639 assert_eq!(r_node.inputs, vec![a.id()]);
13640 assert_eq!(b_node.inputs, vec![a.id()]);
13641 }
13642
13643 #[test]
13644 fn backward_of_recip_is_neg_of_upstream_times_y_squared() {
13645 // y = 1/x ⇒ dy/dx = -y². The backward graph should be a Neg
13646 // wrapping a Mul whose inputs include a Sqr node — and the Sqr
13647 // should reference the forward Recip output, not a fresh recompute.
13648 let a = NodeHandle::from_f32(vec![2.0, 4.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13649 let y = a.recip();
13650 let y_id = y.id();
13651 let grads = y.backward();
13652 let g_a = grads.get(&a).unwrap();
13653 let g = g_a.graph().read().unwrap();
13654 let neg_node = g.node(g_a.id()).clone();
13655 assert!(
13656 matches!(neg_node.op, Op::Neg),
13657 "outermost backward op must be Neg"
13658 );
13659 let mul_id = neg_node.inputs[0];
13660 let mul_node = g.node(mul_id).clone();
13661 assert!(matches!(mul_node.op, Op::Mul));
13662 // One of the Mul's inputs is a Sqr node fed by the forward Recip.
13663 let sqr_id = mul_node
13664 .inputs
13665 .iter()
13666 .copied()
13667 .find(|&id| matches!(g.node(id).op, Op::Sqr))
13668 .expect("backward chain must contain a Sqr node");
13669 let sqr_node = g.node(sqr_id).clone();
13670 assert_eq!(
13671 sqr_node.inputs,
13672 vec![y_id],
13673 "Sqr's input must be the forward Recip output, not a recompute"
13674 );
13675 }
13676
13677 #[test]
13678 fn backward_of_abs_emits_sign_mul() {
13679 // y = |x|, dy/dx = sign(x). After PR B2 landed Op::Sign, the
13680 // backward chain shrinks from 5 nodes (step+neg+step+sub+mul)
13681 // to 2 (sign+mul): grad_x = upstream * sign(x), where Sign is
13682 // a single primitive that returns -1/0/1 directly.
13683 let a = NodeHandle::from_f32(vec![-2.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13684 let y = a.abs();
13685 let grads = y.backward();
13686 let g_a = grads.get(&a).unwrap();
13687 let g = g_a.graph().read().unwrap();
13688 let mul_node = g.node(g_a.id()).clone();
13689 assert!(matches!(mul_node.op, Op::Mul));
13690 // Exactly one input of the Mul is a Sign node (the other is
13691 // the upstream gradient — a Const-rooted ones-tensor here).
13692 let sign_count = mul_node
13693 .inputs
13694 .iter()
13695 .filter(|&&id| matches!(g.node(id).op, Op::Sign))
13696 .count();
13697 assert_eq!(
13698 sign_count, 1,
13699 "Abs backward must reference exactly 1 Sign node, got {sign_count}"
13700 );
13701 // The Sign node should feed off the original input `a`.
13702 let sign_id = mul_node
13703 .inputs
13704 .iter()
13705 .copied()
13706 .find(|&id| matches!(g.node(id).op, Op::Sign))
13707 .unwrap();
13708 assert_eq!(
13709 g.node(sign_id).inputs,
13710 vec![a.id()],
13711 "Sign's input must be the forward input `a`"
13712 );
13713 }
13714
13715 #[test]
13716 fn eq_builder_produces_bool_output_with_input_shape() {
13717 // GAP-168(c): NodeHandle::eq builds a binary node whose dtype is Bool
13718 // regardless of input dtype (CireSnave's ruling — "Fuel uses Bool
13719 // where possible"), with shape == lhs.shape() (and == rhs.shape()).
13720 let a =
13721 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13722 let b = a
13723 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13724 .unwrap();
13725 let m = a.eq(&b);
13726 assert_eq!(m.shape().dims(), &[3]);
13727 assert_eq!(m.dtype(), DType::Bool, "eq output must be Bool");
13728 let m_node = m.graph().read().unwrap().node(m.id()).clone();
13729 assert!(matches!(m_node.op, Op::Equal));
13730 assert_eq!(m_node.inputs, vec![a.id(), b.id()]);
13731 }
13732
13733 #[test]
13734 fn all_six_comparisons_produce_bool() {
13735 // GAP-168(c): eq/ne/lt/le/gt/ge every one returns DType::Bool, not the
13736 // legacy U8 mask. Shape is preserved (== lhs == rhs). One assertion per
13737 // operator so a regression names the operator that drifted.
13738 let a =
13739 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13740 let b = a
13741 .const_f32_like(vec![1.0, 5.0, 3.0], Shape::from_dims(&[3]))
13742 .unwrap();
13743 for (name, m) in [
13744 ("eq", a.eq(&b)),
13745 ("ne", a.ne(&b)),
13746 ("lt", a.lt(&b)),
13747 ("le", a.le(&b)),
13748 ("gt", a.gt(&b)),
13749 ("ge", a.ge(&b)),
13750 ] {
13751 assert_eq!(m.dtype(), DType::Bool, "{name} output must be Bool");
13752 assert_eq!(m.shape().dims(), &[3], "{name} preserves input shape");
13753 }
13754 }
13755
13756 #[test]
13757 fn try_unsqueeze_returns_err_on_dim_above_rank() {
13758 // try_unsqueeze surfaces bad dim as Err; unsqueeze panics
13759 // on the same input. Both share the validation message.
13760 let a =
13761 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13762 let err = a.try_unsqueeze(5).expect_err("dim above rank must error");
13763 assert!(
13764 format!("{err:?}").contains("out of bounds"),
13765 "error must mention bounds, got: {err:?}"
13766 );
13767 // Happy path still works.
13768 let ok = a.try_unsqueeze(0).expect("dim=0 valid for any rank");
13769 assert_eq!(ok.shape().dims(), &[1, 3]);
13770 }
13771
13772 #[test]
13773 fn try_reshape_returns_err_on_count_mismatch() {
13774 let a = NodeHandle::from_f32(vec![1.0, 2.0, 3.0, 4.0], Shape::from_dims(&[4]), cpu_dev())
13775 .unwrap();
13776 let err = a
13777 .try_reshape(Shape::from_dims(&[3]))
13778 .expect_err("count mismatch must error");
13779 assert!(
13780 format!("{err:?}").contains("element count mismatch"),
13781 "error must mention count mismatch, got: {err:?}"
13782 );
13783 let ok = a
13784 .try_reshape(Shape::from_dims(&[2, 2]))
13785 .expect("matching count is ok");
13786 assert_eq!(ok.shape().dims(), &[2, 2]);
13787 }
13788
13789 #[test]
13790 fn try_broadcast_to_returns_err_on_incompatible_shape() {
13791 let a =
13792 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13793 let err = a
13794 .try_broadcast_to(Shape::from_dims(&[2, 4]))
13795 .expect_err("source dim 3 cannot broadcast to dim 4");
13796 assert!(
13797 format!("{err:?}").contains("incompatible"),
13798 "error must mention incompatibility, got: {err:?}"
13799 );
13800 let ok = a
13801 .try_broadcast_to(Shape::from_dims(&[2, 3]))
13802 .expect("dim 3 broadcasts to dim 3");
13803 assert_eq!(ok.shape().dims(), &[2, 3]);
13804 }
13805
13806 #[test]
13807 fn try_transpose_returns_err_on_rank_below_2() {
13808 let a =
13809 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13810 let err = a
13811 .try_transpose()
13812 .expect_err("rank-1 input cannot transpose");
13813 assert!(
13814 format!("{err:?}").contains("rank ≥ 2"),
13815 "error must mention rank requirement, got: {err:?}"
13816 );
13817 let m = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13818 let mt = m.try_transpose().expect("rank-2 transposes ok");
13819 assert_eq!(mt.shape().dims(), &[3, 2]);
13820 }
13821
13822 #[test]
13823 fn try_permute_returns_err_on_bad_axes() {
13824 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13825 // Wrong axes length:
13826 let err = a.try_permute(&[0]).expect_err("axes length mismatch");
13827 assert!(
13828 format!("{err:?}").contains("must equal tensor rank"),
13829 "error must mention length, got: {err:?}"
13830 );
13831 // Out-of-bounds axis:
13832 let err = a.try_permute(&[0, 5]).expect_err("axis 5 out of rank 2");
13833 assert!(format!("{err:?}").contains("out of bounds"));
13834 // Duplicate axis:
13835 let err = a.try_permute(&[0, 0]).expect_err("duplicate axis");
13836 assert!(format!("{err:?}").contains("duplicate"));
13837 // Happy path:
13838 let ok = a.try_permute(&[1, 0]).expect("valid permutation");
13839 assert_eq!(ok.shape().dims(), &[3, 2]);
13840 }
13841
13842 #[test]
13843 fn squeeze_drops_size_one_dim_metadata_only() {
13844 // Build [2, 1, 3] → squeeze(1) → [2, 3]. Op::Squeeze, view-op,
13845 // shape pruned, dtype preserved, single input slot.
13846 let a =
13847 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13848 let s = a.squeeze(1).expect("squeeze on size-1 dim");
13849 assert_eq!(s.shape().dims(), &[2, 3]);
13850 assert_eq!(s.dtype(), DType::F32);
13851 let node = s.graph().read().unwrap().node(s.id()).clone();
13852 assert!(matches!(node.op, Op::Squeeze { dim: 1 }));
13853 assert_eq!(node.inputs, vec![a.id()]);
13854 // Squeeze joins the view-op set so the Layout side-table is
13855 // populated automatically.
13856 assert!(
13857 node.op.is_view_op(),
13858 "Op::Squeeze must register as a view op"
13859 );
13860 }
13861
13862 #[test]
13863 fn squeeze_rejects_non_size_one_dim() {
13864 // Result-returning: bad dim surfaces as Err, not panic.
13865 let a = NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
13866 let err = a
13867 .squeeze(1)
13868 .expect_err("squeezing a non-size-1 dim must error");
13869 assert!(
13870 format!("{err:?}").contains("expected 1"),
13871 "error message should mention the size-1 expectation, got: {err:?}"
13872 );
13873 }
13874
13875 #[test]
13876 fn squeeze_rejects_dim_above_rank() {
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.squeeze(5).expect_err("dim above rank must error");
13880 assert!(
13881 format!("{err:?}").contains("out of bounds"),
13882 "error message should mention bounds, got: {err:?}"
13883 );
13884 }
13885
13886 #[test]
13887 fn backward_through_squeeze_emits_unsqueeze() {
13888 // y = squeeze(x, 1). Backward: re-insert dim 1 via Unsqueeze.
13889 // Gradient shape must equal x.shape exactly.
13890 let a =
13891 NodeHandle::from_f32(vec![1.0; 6], Shape::from_dims(&[2, 1, 3]), cpu_dev()).unwrap();
13892 let y = a.squeeze(1).expect("squeeze on size-1 dim");
13893 let grads = y.backward();
13894 let g_a = grads.get(&a).expect("gradient for a");
13895 assert_eq!(
13896 g_a.shape().dims(),
13897 &[2, 1, 3],
13898 "Squeeze backward gradient must restore the original shape"
13899 );
13900 // The chain is: ones-seed (post-squeeze, shape [2,3])
13901 // → Unsqueeze(dim=1) → shape [2, 1, 3].
13902 let g_node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13903 assert!(
13904 matches!(g_node.op, Op::Unsqueeze { dim: 1 }),
13905 "Squeeze backward must be Unsqueeze at the same dim"
13906 );
13907 }
13908
13909 #[test]
13910 fn floor_builder_produces_unary_node_same_dtype() {
13911 // NodeHandle::floor builds a unary node preserving shape + dtype.
13912 let a =
13913 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13914 let f = a.floor();
13915 assert_eq!(f.shape().dims(), &[3]);
13916 assert_eq!(f.dtype(), DType::F32);
13917 let node = f.graph().read().unwrap().node(f.id()).clone();
13918 assert!(matches!(node.op, Op::Floor));
13919 assert_eq!(node.inputs, vec![a.id()]);
13920 }
13921
13922 #[test]
13923 fn backward_through_floor_drops_gradient_silently() {
13924 // Op::Floor has zero gradient almost everywhere; the inline
13925 // backward arm is a no-op. backward() must succeed and the
13926 // input gets no gradient (the input's upstream is never
13927 // populated through the Floor node).
13928 let a =
13929 NodeHandle::from_f32(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13930 let y = a.floor();
13931 let grads = y.backward();
13932 // a's gradient is dropped — no entry in the GradMap.
13933 assert!(
13934 grads.get(&a).is_none(),
13935 "Floor must not propagate gradient to its input"
13936 );
13937 }
13938
13939 #[test]
13940 fn where_cond_builder_produces_ternary_with_a_dtype() {
13941 // self is a Bool cond (GAP-168(c)); a/b are F32. Output dtype = F32
13942 // (= a's dtype), shape = self.shape() (= a.shape() = b.shape()).
13943 // Op::Where node carries 3 inputs in order (cond, a, b).
13944 let a =
13945 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
13946 let b = a
13947 .const_f32_like(vec![10.0, 20.0, 30.0], Shape::from_dims(&[3]))
13948 .unwrap();
13949 let eq_a_b = a.eq(&b); // Bool mask
13950 let picked = eq_a_b.where_cond(&a, &b);
13951 assert_eq!(picked.shape().dims(), &[3]);
13952 assert_eq!(picked.dtype(), DType::F32, "Where output dtype = a/b dtype");
13953 let node = picked.graph().read().unwrap().node(picked.id()).clone();
13954 assert!(matches!(node.op, Op::Where));
13955 assert_eq!(node.inputs.len(), 3);
13956 assert_eq!(
13957 node.inputs,
13958 vec![eq_a_b.id(), a.id(), b.id()],
13959 "Where input order: (cond, a, b)"
13960 );
13961 }
13962
13963 #[test]
13964 fn backward_reuses_exp_forward_output() {
13965 // Exp's backward rule uses the forward output directly. The
13966 // gradient for x should be a Mul whose inputs include the
13967 // forward Exp node (not a new Exp node).
13968 let a = NodeHandle::from_f32(vec![0.0, 1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
13969 let e = a.exp();
13970 let exp_forward_id = e.id();
13971 let grads = e.backward();
13972 let g_a = grads.get(&a).unwrap();
13973 let node = g_a.graph().read().unwrap().node(g_a.id()).clone();
13974 assert!(matches!(node.op, Op::Mul));
13975 // One of the Mul's inputs should be the original forward Exp node.
13976 assert!(
13977 node.inputs.contains(&exp_forward_id),
13978 "Exp backward should reference the forward output ({exp_forward_id:?}), \
13979 got inputs {:?}",
13980 node.inputs,
13981 );
13982 }
13983
13984 // ---- Op::WriteSlice (Phase E.3.2) ---------------------------------------
13985
13986 #[test]
13987 fn write_slice_destructive_input_is_zero() {
13988 let op = Op::WriteSlice {
13989 ranges: vec![(0, 1), (0, 32), (0, 128)],
13990 dyn_offset: None,
13991 };
13992 assert_eq!(op.destructive_input(), Some(0));
13993 }
13994
13995 #[test]
13996 fn write_slice_short_name() {
13997 let op = Op::WriteSlice {
13998 ranges: vec![(0, 1)],
13999 dyn_offset: None,
14000 };
14001 assert_eq!(op.short_name(), "WriteSlice");
14002 }
14003
14004 #[test]
14005 fn write_slice_emits_op_writeslice_node() {
14006 // dest shape [4, 3]; source shape [1, 3]; write at row 2.
14007 let dest =
14008 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14009 let src = dest
14010 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14011 .unwrap();
14012 let out = dest
14013 .write_slice(&src, vec![(2, 3), (0, 3)])
14014 .expect("write_slice should accept matching shapes");
14015 let g = out.graph().read().unwrap();
14016 match &g.node(out.id()).op {
14017 Op::WriteSlice { ranges, dyn_offset } => {
14018 assert_eq!(ranges, &vec![(2, 3), (0, 3)]);
14019 assert_eq!(dyn_offset, &None);
14020 }
14021 other => panic!("expected Op::WriteSlice, got {other:?}"),
14022 }
14023 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14024 // Output shape == destination shape; bytes are post-write same buffer.
14025 assert_eq!(g.node(out.id()).shape.dims(), &[4, 3]);
14026 }
14027
14028 #[test]
14029 fn write_slice_dyn_records_dynamic_offset() {
14030 use fuel_ir::{DynScalar, SymId};
14031 // dest capacity [8, 3]; source [1, 3]; dynamic start on axis 0.
14032 let dest =
14033 NodeHandle::from_f32(vec![0.0_f32; 24], Shape::from_dims(&[8, 3]), cpu_dev()).unwrap();
14034 let src = dest
14035 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14036 .unwrap();
14037 let sym = SymId(0);
14038 // ranges[0].0 is ignored (start is dynamic); width = 1 - 0 = 1
14039 // matches source dim 0. Axis 1 is static, full width.
14040 let out = dest
14041 .write_slice_dyn(&src, vec![(0, 1), (0, 3)], 0, DynScalar::Sym(sym))
14042 .expect("write_slice_dyn should accept matching widths");
14043 let g = out.graph().read().unwrap();
14044 match &g.node(out.id()).op {
14045 Op::WriteSlice { ranges, dyn_offset } => {
14046 assert_eq!(ranges, &vec![(0, 1), (0, 3)]);
14047 assert_eq!(dyn_offset, &Some((0, DynScalar::Sym(sym))));
14048 }
14049 other => panic!("expected Op::WriteSlice, got {other:?}"),
14050 }
14051 assert_eq!(g.node(out.id()).inputs, vec![dest.id(), src.id()]);
14052 assert_eq!(g.node(out.id()).shape.dims(), &[8, 3]);
14053 }
14054
14055 #[test]
14056 fn write_slice_dyn_rejects_slab_wider_than_capacity() {
14057 use fuel_ir::{DynScalar, SymId};
14058 // dest capacity on axis 0 is 2, but the dynamic-axis slab is
14059 // width 4 — can never fit regardless of the runtime offset.
14060 let dest =
14061 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14062 let src = dest
14063 .const_f32_like(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]))
14064 .unwrap();
14065 let err = dest.write_slice_dyn(&src, vec![(0, 4), (0, 3)], 0, DynScalar::Sym(SymId(0)));
14066 assert!(
14067 err.is_err(),
14068 "dynamic-axis slab wider than capacity must error at build"
14069 );
14070 }
14071
14072 #[test]
14073 fn write_slice_dyn_rejects_axis_out_of_bounds() {
14074 use fuel_ir::{DynScalar, SymId};
14075 let dest =
14076 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
14077 let src = dest
14078 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14079 .unwrap();
14080 let err = dest.write_slice_dyn(&src, vec![(0, 1), (0, 3)], 5, DynScalar::Sym(SymId(0)));
14081 assert!(err.is_err(), "dyn_axis past rank must error");
14082 }
14083
14084 #[test]
14085 fn flash_attn_dyn_records_runtime_k_len() {
14086 use fuel_ir::{DynScalar, SymId};
14087 // q [1, 2, 3, 4]; K/V capacity [1, 1, 8, 4] (GQA Hq=2, Hkv=1).
14088 let q = NodeHandle::from_f32(
14089 vec![0.0_f32; 2 * 3 * 4],
14090 Shape::from_dims(&[1, 2, 3, 4]),
14091 cpu_dev(),
14092 )
14093 .unwrap();
14094 let k = q
14095 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14096 .unwrap();
14097 let v = q
14098 .const_f32_like(vec![0.0_f32; 8 * 4], Shape::from_dims(&[1, 1, 8, 4]))
14099 .unwrap();
14100 let sym = SymId(0);
14101 let out = q.flash_attn_dyn(
14102 &k,
14103 &v,
14104 None,
14105 /*scale*/ 0.5,
14106 /*causal*/ true,
14107 None,
14108 None,
14109 None,
14110 DynScalar::Sym(sym),
14111 );
14112 // Output adopts q's shape, not the capacity.
14113 assert_eq!(out.shape().dims(), &[1, 2, 3, 4]);
14114 let g = out.graph().read().unwrap();
14115 match &g.node(out.id()).op {
14116 Op::Fused(fid, crate::registry::FusedOpParams::FlashAttn { causal, k_len, .. })
14117 if *fid == crate::registry::FusedOps::FLASH_ATTN =>
14118 {
14119 assert!(*causal);
14120 assert_eq!(k_len, &Some(DynScalar::Sym(sym)));
14121 }
14122 other => panic!("expected Op::Fused(FLASH_ATTN, FlashAttn), got {other:?}"),
14123 }
14124 assert_eq!(g.node(out.id()).inputs, vec![q.id(), k.id(), v.id()]);
14125 }
14126
14127 #[test]
14128 #[should_panic(expected = "k_len")]
14129 fn flash_attn_dyn_concrete_k_len_exceeding_capacity_panics() {
14130 use fuel_ir::DynScalar;
14131 let q = NodeHandle::from_f32(
14132 vec![0.0_f32; 2 * 4],
14133 Shape::from_dims(&[1, 1, 2, 4]),
14134 cpu_dev(),
14135 )
14136 .unwrap();
14137 let k = q
14138 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14139 .unwrap();
14140 let v = q
14141 .const_f32_like(vec![0.0_f32; 4 * 4], Shape::from_dims(&[1, 1, 4, 4]))
14142 .unwrap();
14143 // Concrete k_len=5 > capacity 4 → build-time panic.
14144 let _ = q.flash_attn_dyn(
14145 &k,
14146 &v,
14147 None,
14148 1.0,
14149 true,
14150 None,
14151 None,
14152 None,
14153 DynScalar::Concrete(5),
14154 );
14155 }
14156
14157 #[test]
14158 fn write_slice_rejects_rank_mismatch() {
14159 let dest =
14160 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14161 let src = dest
14162 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]))
14163 .unwrap();
14164 // ranges has rank 2 (matches dest) but source has rank 1.
14165 let err = dest.write_slice(&src, vec![(0, 1), (0, 3)]);
14166 assert!(err.is_err(), "rank mismatch must error");
14167 }
14168
14169 // ---- cross-graph operands must fail at BUILD time, never hang -----------
14170 //
14171 // Node ids are indices into ONE graph's arena, so an operand built on a
14172 // DIFFERENT graph records an id that indexes an unrelated node (or none),
14173 // producing a malformed dependency graph. The failure surfaces as neither
14174 // a panic nor an error: the executor **HANGS at realize**, waiting on a
14175 // dependency that can never resolve — low CPU, no stack, no message. That
14176 // is strictly worse than a panic, and it violates two rules at once:
14177 // "validate at graph-build time" and never-hang.
14178 //
14179 // `matmul`, `qmatmul`, `conv2d`, `paged_attn`, and everything routed via
14180 // `binary_op` already assert this. These builders did not — a real cost: a
14181 // peer session spent a long bisect localizing exactly this on `write_slice`.
14182 //
14183 // These tests only BUILD, never realize, so before the fix they fail fast
14184 // instead of hanging the suite.
14185
14186 #[test]
14187 fn write_slice_rejects_cross_graph_source() {
14188 let dest =
14189 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14190 // A SECOND `from_*` mints a second graph — the easy mistake to make,
14191 // and currently the un-diagnosable one.
14192 let foreign =
14193 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]), cpu_dev())
14194 .unwrap();
14195 assert_ne!(
14196 dest.graph_id(),
14197 foreign.graph_id(),
14198 "fixture must be cross-graph"
14199 );
14200
14201 let err = dest.write_slice(&foreign, vec![(2, 3), (0, 3)]);
14202 assert!(
14203 err.is_err(),
14204 "cross-graph source must be a build-time Err, not a realize-time hang",
14205 );
14206 let msg = format!("{}", err.unwrap_err());
14207 assert!(
14208 msg.contains("same graph"),
14209 "error should say the operands must share a graph, got: {msg}",
14210 );
14211 }
14212
14213 #[test]
14214 fn masked_fill_rejects_cross_graph_mask() {
14215 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14216 let foreign_mask =
14217 NodeHandle::from_f32(vec![1.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14218 assert_ne!(
14219 x.graph_id(),
14220 foreign_mask.graph_id(),
14221 "fixture must be cross-graph"
14222 );
14223
14224 let err = x.masked_fill(&foreign_mask, Scalar::F32(0.0));
14225 assert!(
14226 err.is_err(),
14227 "cross-graph mask must be a build-time Err, not a realize-time hang",
14228 );
14229 // MUST assert the reason, not just is_err(): this fixture also has a
14230 // dtype mismatch, so a bare `is_err()` passes for the WRONG reason and
14231 // would stay green even with no graph check at all.
14232 let msg = format!("{}", err.unwrap_err());
14233 assert!(
14234 msg.contains("same graph"),
14235 "must fail on GRAPH affinity, not incidentally on dtype, got: {msg}",
14236 );
14237 }
14238
14239 #[test]
14240 fn masked_fill_rejects_scale_dtype_at_build() {
14241 // F8E8M0 is a block-scale dtype: it HAS a scalar value (so the
14242 // value-dtype check passes) but no zero, so the MaskedFill backward
14243 // cannot produce a gradient. Reject at build time — and this must fail
14244 // on the dtype guard specifically: graph / shape / mask-Bool / value-dtype
14245 // are all satisfied, so a bare `is_err()` can only be the guard firing.
14246 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14247 let scale = x.cast(DType::F8E8M0);
14248 let mask = x.cast(DType::Bool);
14249 let value = Scalar::one(DType::F8E8M0).unwrap();
14250
14251 let err = scale.masked_fill(&mask, value);
14252 assert!(
14253 err.is_err(),
14254 "masked_fill on a scale dtype must be a build-time Err"
14255 );
14256 let msg = format!("{}", err.unwrap_err());
14257 assert!(
14258 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14259 "must fail on the packed/scale dtype guard, got: {msg}",
14260 );
14261 }
14262
14263 /// GAP-075 fix B: pin the REJECT verdict for every unfillable dtype
14264 /// individually (not a bucket count). The guard is semantic — packed
14265 /// formats (F4/F6*) have no representable fill value; block-scales
14266 /// (F8E8M0/F8E6M2) have no zero for the zero-filling backward — so each must
14267 /// be a build-time Err on the dtype GUARD specifically (its message names
14268 /// the op). Per-dtype pinning protects the classification: a future dtype
14269 /// misfiled into the allow arm can't hide behind a passing tally, and a new
14270 /// dtype with no verdict is caught by the compiler (the match is exhaustive,
14271 /// no wildcard). Paired with the allow test below (opposite assertion), the
14272 /// two are mutually non-vacuous.
14273 #[test]
14274 fn masked_fill_rejects_every_unfillable_dtype() {
14275 for dt in [
14276 DType::F4,
14277 DType::F6E2M3,
14278 DType::F6E3M2,
14279 DType::F8E8M0,
14280 DType::F8E6M2,
14281 ] {
14282 let x =
14283 NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14284 let t = x.cast(dt);
14285 let mask = x.cast(DType::Bool);
14286 // The dtype guard fires before the value-dtype check, so a dummy
14287 // value is fine; the message assertion proves it was the guard.
14288 let err = t.masked_fill(&mask, Scalar::F32(0.0));
14289 assert!(err.is_err(), "masked_fill must reject {dt:?} at build time");
14290 let msg = format!("{}", err.unwrap_err());
14291 assert!(
14292 msg.contains("unsupported dtype") && msg.contains("masked_fill"),
14293 "{dt:?} must fail on the semantic dtype guard, got: {msg}",
14294 );
14295 }
14296 }
14297
14298 /// GAP-075 fix B: the allow arm is a graph-build PERMISSION (masked_fill is
14299 /// semantically well-defined — a fill value + a zero), NOT a claim a backend
14300 /// can allocate/run the dtype. F32 is the live consumer path (attention
14301 /// masking); I32 is an allowed verdict no consumer currently exercises —
14302 /// locking it preserves today's answer without asserting integer masked_fill
14303 /// is known to compute correctly (a backend lacking I32 storage still
14304 /// declines loudly at allocation, downstream of this permission).
14305 #[test]
14306 fn masked_fill_permits_fillable_dtypes_as_permission_not_capability() {
14307 let x = NodeHandle::from_f32(vec![0.0_f32; 4], Shape::from_dims(&[4]), cpu_dev()).unwrap();
14308 let mask = x.cast(DType::Bool);
14309 assert!(
14310 x.masked_fill(&mask, Scalar::F32(0.0)).is_ok(),
14311 "F32 masked_fill must build (the live consumer path)",
14312 );
14313 let xi = x.cast(DType::I32);
14314 assert!(
14315 xi.masked_fill(&mask, Scalar::one(DType::I32).unwrap())
14316 .is_ok(),
14317 "I32 masked_fill must build — permission preserved, not a correctness claim",
14318 );
14319 }
14320
14321 #[test]
14322 #[should_panic(expected = "same graph")]
14323 fn rope_with_tables_panics_on_cross_graph_tables() {
14324 // Returns `NodeHandle`, so it follows the convention of the already-checked
14325 // builders (`matmul`, `paged_attn`) and asserts. A panic names the
14326 // problem at the build site; the status quo hangs later saying nothing.
14327 let x = NodeHandle::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[1, 1, 2, 4]), cpu_dev())
14328 .unwrap();
14329 let cos =
14330 NodeHandle::from_f32(vec![1.0_f32; 8], Shape::from_dims(&[2, 4]), cpu_dev()).unwrap();
14331 let sin = x
14332 .const_f32_like(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]))
14333 .unwrap();
14334 let _ = x.rope_with_tables(&cos, &sin);
14335 }
14336
14337 #[test]
14338 fn write_slice_rejects_slab_width_mismatch() {
14339 let dest =
14340 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14341 // Source has 2 elements along axis 0, but slab is width 1.
14342 let src = dest
14343 .const_f32_like(vec![1.0_f32; 6], Shape::from_dims(&[2, 3]))
14344 .unwrap();
14345 let err = dest.write_slice(&src, vec![(2, 3), (0, 3)]);
14346 assert!(err.is_err(), "slab-width mismatch must error");
14347 }
14348
14349 #[test]
14350 fn write_slice_rejects_range_past_dest_extent() {
14351 let dest =
14352 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14353 let src = dest
14354 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14355 .unwrap();
14356 // axis 0: dest extent is 4; range [4, 5) is out of bounds.
14357 let err = dest.write_slice(&src, vec![(4, 5), (0, 3)]);
14358 assert!(err.is_err(), "range past dest extent must error");
14359 }
14360
14361 #[test]
14362 fn write_slice_derives_ordering_after_other_readers() {
14363 // Graph:
14364 // dest = ...; src = ...
14365 // ro = dest.relu() (non-destructive reader of dest)
14366 // w = dest.write_slice(&src, [(0,1),(0,3)]) (destructive on dest)
14367 // Expected ordering: w must run after ro.
14368 let dest =
14369 NodeHandle::from_f32(vec![0.0_f32; 12], Shape::from_dims(&[4, 3]), cpu_dev()).unwrap();
14370 let src = dest
14371 .const_f32_like(vec![1.0, 2.0, 3.0], Shape::from_dims(&[1, 3]))
14372 .unwrap();
14373 let ro = dest.relu();
14374 let w = dest.write_slice(&src, vec![(0, 1), (0, 3)]).unwrap();
14375 let ord = crate::opt::derive_ordering(&dest.graph().read().unwrap(), &[ro.id(), w.id()]);
14376 let deps = ord.deps_of(w.id());
14377 assert_eq!(
14378 deps.len(),
14379 1,
14380 "write_slice should have one ordering dep (the relu)"
14381 );
14382 assert_eq!(
14383 deps[0],
14384 ro.id(),
14385 "write_slice must run after the non-destructive reader"
14386 );
14387 }
14388
14389 // ---- In-place ops Phase 1 -----------------------------------------------
14390 //
14391 // Smoke tests for the 5 new in-place unary variants
14392 // (`Op::ReluInplace`, `Op::SiluInplace`, `Op::GeluTanhInplace`,
14393 // `Op::TanhInplace`, `Op::SigmoidInplace`) and `FusedOps::INPLACE_AFFINE`.
14394 // Phase 1 only ships the structural plumbing (Op IR + destructive_input +
14395 // short_name + scheduler integration); dispatch + autograd land in Phases
14396 // 3 + 4. See `docs/session-prompts/in-place-ops-infrastructure.md`.
14397
14398 #[test]
14399 fn inplace_unary_destructive_input_is_zero() {
14400 for op in [
14401 Op::ReluInplace,
14402 Op::SiluInplace,
14403 Op::GeluTanhInplace,
14404 Op::TanhInplace,
14405 Op::SigmoidInplace,
14406 Op::NegInplace,
14407 Op::AbsInplace,
14408 Op::SqrInplace,
14409 Op::SqrtInplace,
14410 Op::RsqrtInplace,
14411 Op::RecipInplace,
14412 Op::ExpInplace,
14413 Op::LogInplace,
14414 Op::SinInplace,
14415 Op::CosInplace,
14416 Op::SignInplace,
14417 Op::FloorInplace,
14418 Op::CeilInplace,
14419 Op::RoundInplace,
14420 Op::ErfInplace,
14421 Op::GeluInplace,
14422 ] {
14423 assert_eq!(
14424 op.destructive_input(),
14425 Some(0),
14426 "in-place unary {op:?} must declare input 0 destructive",
14427 );
14428 }
14429 }
14430
14431 #[test]
14432 fn inplace_unary_short_names_round_trip() {
14433 assert_eq!(Op::ReluInplace.short_name(), "ReluInplace");
14434 assert_eq!(Op::SiluInplace.short_name(), "SiluInplace");
14435 assert_eq!(Op::GeluTanhInplace.short_name(), "GeluTanhInplace");
14436 assert_eq!(Op::TanhInplace.short_name(), "TanhInplace");
14437 assert_eq!(Op::SigmoidInplace.short_name(), "SigmoidInplace");
14438 assert_eq!(Op::NegInplace.short_name(), "NegInplace");
14439 assert_eq!(Op::AbsInplace.short_name(), "AbsInplace");
14440 assert_eq!(Op::SqrInplace.short_name(), "SqrInplace");
14441 assert_eq!(Op::SqrtInplace.short_name(), "SqrtInplace");
14442 assert_eq!(Op::RsqrtInplace.short_name(), "RsqrtInplace");
14443 assert_eq!(Op::RecipInplace.short_name(), "RecipInplace");
14444 assert_eq!(Op::ExpInplace.short_name(), "ExpInplace");
14445 assert_eq!(Op::LogInplace.short_name(), "LogInplace");
14446 assert_eq!(Op::SinInplace.short_name(), "SinInplace");
14447 assert_eq!(Op::CosInplace.short_name(), "CosInplace");
14448 assert_eq!(Op::SignInplace.short_name(), "SignInplace");
14449 assert_eq!(Op::FloorInplace.short_name(), "FloorInplace");
14450 assert_eq!(Op::CeilInplace.short_name(), "CeilInplace");
14451 assert_eq!(Op::RoundInplace.short_name(), "RoundInplace");
14452 assert_eq!(Op::ErfInplace.short_name(), "ErfInplace");
14453 assert_eq!(Op::GeluInplace.short_name(), "GeluInplace");
14454 assert_eq!(
14455 Op::ClampInplace { min: 0.0, max: 1.0 }.short_name(),
14456 "ClampInplace"
14457 );
14458 assert_eq!(Op::PowIInplace(3).short_name(), "PowIInplace");
14459 }
14460
14461 #[test]
14462 fn inplace_affine_fused_op_destructive_input_is_zero() {
14463 let op = Op::Fused(
14464 crate::registry::FusedOps::INPLACE_AFFINE,
14465 crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 },
14466 );
14467 assert_eq!(op.destructive_input(), Some(0));
14468 }
14469
14470 #[test]
14471 fn destructive_input_for_fused_is_registry_declared() {
14472 // GAP-076: a fused op's destructiveness is a MANDATORY declared field on
14473 // its registry entry, and `Op::destructive_input` reads that field via
14474 // `default_registry()` rather than a hardcoded id match that could drift
14475 // out of sync. This locks BOTH directions of the declaration plus the
14476 // routing that reads it. Regression lock, not a born-red: no op was
14477 // misclassified before the fix — its value is that a future wrong
14478 // declaration (or a reverted routing) reddens HERE instead of surfacing
14479 // as an intermittent scheduler data race that points nowhere near this
14480 // code. The exhaustive match in `Op::destructive_input` and the
14481 // mandatory struct field are the compile-time seams; this is the belt.
14482 use crate::registry::{FusedOps, default_registry};
14483 let reg = default_registry();
14484 assert_eq!(
14485 reg.entry(FusedOps::INPLACE_AFFINE)
14486 .expect("INPLACE_AFFINE is registered")
14487 .destructive_input,
14488 Some(0),
14489 "InplaceAffine must declare itself destructive on input 0",
14490 );
14491 assert_eq!(
14492 reg.entry(FusedOps::SOFTMAX_LAST_DIM)
14493 .expect("SOFTMAX_LAST_DIM is registered")
14494 .destructive_input,
14495 None,
14496 "a functional fused op must declare itself non-destructive",
14497 );
14498 // Routing reads the declared field (not a hardcoded id match).
14499 let op = Op::Fused(
14500 FusedOps::INPLACE_AFFINE,
14501 crate::registry::FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 },
14502 );
14503 assert_eq!(op.destructive_input(), Some(0));
14504 }
14505
14506 #[test]
14507 fn inplace_affine_params_key_dedupe_on_same_mul_add() {
14508 // Two `InplaceAffine` params with identical (mul, add) hash to the
14509 // same key; differing values produce distinct keys. Lets CSE / the
14510 // existing op_key infrastructure collapse identical in-place affines
14511 // (when callers wire them through the equivalent graph machinery).
14512 let a = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14513 let b = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 1.0 };
14514 let c = crate::registry::FusedOpParams::InplaceAffine { mul: 2.0, add: 0.5 };
14515 assert_eq!(a.key(), b.key(), "identical mul/add must dedupe");
14516 assert_ne!(a.key(), c.key(), "different add must produce distinct key");
14517 }
14518
14519 // ---- Phase 4 — autograd through in-place ops ----
14520 //
14521 // The view-aware `derive_ordering` (Phase 4a) ensures backward
14522 // grad nodes that read forward inputs run BEFORE any in-place
14523 // mutation of those inputs. The backward arms in
14524 // `NodeHandle::backward` (Phase 4b) emit the same gradient graph as
14525 // the non-inplace cousins. These tests prove that calling
14526 // `.backward()` through an in-place node:
14527 // (1) does NOT panic (was previously guarded by the Phase 1
14528 // defensive panic);
14529 // (2) emits the same gradient-node structure as the non-inplace
14530 // cousin (matching node counts + op types as a structural
14531 // proxy for numerical equivalence — the actual numerics are
14532 // exercised by the live oracle tests in fuel-storage).
14533
14534 #[test]
14535 fn backward_through_relu_inplace_does_not_panic() {
14536 // y = x.relu_inplace(); loss = y.sum_all(); loss.backward()
14537 // Phase 1's defensive panic is removed; backward emits
14538 // Op::Step(x) + Op::Mul(upstream, step) — same as Op::Relu.
14539 let x =
14540 NodeHandle::from_f32(vec![1.0, -2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14541 let y = x.relu_inplace();
14542 let loss = y.sum_all();
14543 let grads = loss.backward();
14544 let g_x = grads.get(&x).expect("gradient for x should be present");
14545 // Same structural form as Op::Relu's backward: gradient node
14546 // is an Op::Mul (upstream × step(x)).
14547 let g_node = g_x.graph().read().unwrap().node(g_x.id()).clone();
14548 assert!(
14549 matches!(g_node.op, Op::Mul),
14550 "relu backward grad is Mul; got {:?}",
14551 g_node.op
14552 );
14553 }
14554
14555 #[test]
14556 fn backward_through_sigmoid_inplace_does_not_panic() {
14557 let x = NodeHandle::from_f32(vec![0.5, -0.5], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14558 let y = x.sigmoid_inplace();
14559 let loss = y.sum_all();
14560 let grads = loss.backward();
14561 let g_x = grads.get(&x);
14562 assert!(g_x.is_some());
14563 }
14564
14565 #[test]
14566 fn backward_through_tanh_inplace_does_not_panic() {
14567 let x =
14568 NodeHandle::from_f32(vec![0.1, 0.2, 0.3], Shape::from_dims(&[3]), cpu_dev()).unwrap();
14569 let y = x.tanh_inplace();
14570 let loss = y.sum_all();
14571 let grads = loss.backward();
14572 let g_x = grads.get(&x);
14573 assert!(g_x.is_some());
14574 }
14575
14576 #[test]
14577 fn backward_through_silu_inplace_does_not_panic() {
14578 let x = NodeHandle::from_f32(vec![0.1, 0.2], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14579 let y = x.silu_inplace();
14580 let loss = y.sum_all();
14581 let grads = loss.backward();
14582 let g_x = grads.get(&x);
14583 assert!(g_x.is_some());
14584 }
14585
14586 #[test]
14587 fn backward_through_gelu_inplace_panics_matching_op_gelu() {
14588 // GeluTanhInplace mirrors Op::GeluTanh's "currently inference-only"
14589 // panic — both rely on the same not-yet-implemented gradient.
14590 // SiluInplace is the recommended differentiable alternative.
14591 let x = NodeHandle::from_f32(vec![0.1], Shape::from_dims(&[1]), cpu_dev()).unwrap();
14592 let y = x.gelu_tanh_inplace();
14593 let loss = y.sum_all();
14594 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| loss.backward()));
14595 assert!(
14596 result.is_err(),
14597 "GeluTanhInplace backward should panic (mirrors Op::GeluTanh)"
14598 );
14599 }
14600
14601 #[test]
14602 fn backward_through_relu_inplace_emits_same_graph_shape_as_functional() {
14603 // Structural parity: relu_inplace backward emits the same node
14604 // count + same op variants as relu backward, since the
14605 // gradient formula is identical.
14606 let x_inp =
14607 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14608 let y_inp = x_inp.relu_inplace();
14609 let loss_inp = y_inp.sum_all();
14610 let nodes_before_inp = loss_inp.graph().read().unwrap().len();
14611 let _ = loss_inp.backward();
14612 let added_inp = loss_inp.graph().read().unwrap().len() - nodes_before_inp;
14613
14614 let x_fn =
14615 NodeHandle::from_f32(vec![1.0, -1.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
14616 let y_fn = x_fn.relu();
14617 let loss_fn = y_fn.sum_all();
14618 let nodes_before_fn = loss_fn.graph().read().unwrap().len();
14619 let _ = loss_fn.backward();
14620 let added_fn = loss_fn.graph().read().unwrap().len() - nodes_before_fn;
14621
14622 assert_eq!(
14623 added_inp, added_fn,
14624 "ReluInplace backward should add the same number of nodes as Relu backward ({added_fn}), got {added_inp}",
14625 );
14626 }
14627
14628 #[test]
14629 fn relu_inplace_builder_emits_op_reluinplace() {
14630 let x = NodeHandle::from_f32(
14631 vec![1.0_f32, -1.0, 2.0, -2.0],
14632 Shape::from_dims(&[4]),
14633 cpu_dev(),
14634 )
14635 .unwrap();
14636 let y = x.relu_inplace();
14637 let g = y.graph().read().unwrap();
14638 let node = g.node(y.id());
14639 assert!(matches!(node.op, Op::ReluInplace));
14640 assert_eq!(node.inputs, vec![x.id()]);
14641 assert_eq!(node.shape.dims(), &[4]);
14642 assert_eq!(node.dtype, DType::F32);
14643 }
14644
14645 #[test]
14646 fn affine_inplace_builder_emits_fused_inplace_affine() {
14647 let x = NodeHandle::from_f32(
14648 vec![1.0_f32, 2.0, 3.0, 4.0],
14649 Shape::from_dims(&[4]),
14650 cpu_dev(),
14651 )
14652 .unwrap();
14653 let y = x.affine_inplace(2.0, 0.5);
14654 let g = y.graph().read().unwrap();
14655 let node = g.node(y.id());
14656 match &node.op {
14657 Op::Fused(id, crate::registry::FusedOpParams::InplaceAffine { mul, add }) => {
14658 assert_eq!(*id, crate::registry::FusedOps::INPLACE_AFFINE);
14659 assert_eq!(*mul, 2.0);
14660 assert_eq!(*add, 0.5);
14661 }
14662 other => panic!("expected Op::Fused(INPLACE_AFFINE, InplaceAffine), got {other:?}"),
14663 }
14664 assert_eq!(node.inputs, vec![x.id()]);
14665 assert_eq!(node.shape.dims(), &[4]);
14666 }
14667
14668 #[test]
14669 fn all_inplace_unary_builders_round_trip_through_op_variants() {
14670 // One smoke per variant — each builder emits exactly the
14671 // matching `Op::*Inplace` variant, single input, shape +
14672 // dtype unchanged.
14673 let x = NodeHandle::from_f32(vec![0.5_f32; 8], Shape::from_dims(&[8]), cpu_dev()).unwrap();
14674 fn check(y: NodeHandle, x_id: NodeId, expect: fn(&Op) -> bool) {
14675 let g = y.graph().read().unwrap();
14676 let node = g.node(y.id());
14677 assert!(expect(&node.op), "wrong Op variant: {:?}", node.op);
14678 assert_eq!(node.inputs, vec![x_id]);
14679 assert_eq!(node.shape.dims(), &[8]);
14680 assert_eq!(node.dtype, DType::F32);
14681 }
14682 check(x.relu_inplace(), x.id(), |o| matches!(o, Op::ReluInplace));
14683 check(x.silu_inplace(), x.id(), |o| matches!(o, Op::SiluInplace));
14684 check(x.gelu_tanh_inplace(), x.id(), |o| {
14685 matches!(o, Op::GeluTanhInplace)
14686 });
14687 check(x.tanh_inplace(), x.id(), |o| matches!(o, Op::TanhInplace));
14688 check(x.sigmoid_inplace(), x.id(), |o| {
14689 matches!(o, Op::SigmoidInplace)
14690 });
14691 check(x.neg_inplace(), x.id(), |o| matches!(o, Op::NegInplace));
14692 check(x.abs_inplace(), x.id(), |o| matches!(o, Op::AbsInplace));
14693 check(x.sqr_inplace(), x.id(), |o| matches!(o, Op::SqrInplace));
14694 check(x.sqrt_inplace(), x.id(), |o| matches!(o, Op::SqrtInplace));
14695 check(x.rsqrt_inplace(), x.id(), |o| matches!(o, Op::RsqrtInplace));
14696 check(x.recip_inplace(), x.id(), |o| matches!(o, Op::RecipInplace));
14697 check(x.exp_inplace(), x.id(), |o| matches!(o, Op::ExpInplace));
14698 check(x.log_inplace(), x.id(), |o| matches!(o, Op::LogInplace));
14699 check(x.sin_inplace(), x.id(), |o| matches!(o, Op::SinInplace));
14700 check(x.cos_inplace(), x.id(), |o| matches!(o, Op::CosInplace));
14701 check(x.sign_inplace(), x.id(), |o| matches!(o, Op::SignInplace));
14702 check(x.floor_inplace(), x.id(), |o| matches!(o, Op::FloorInplace));
14703 check(x.ceil_inplace(), x.id(), |o| matches!(o, Op::CeilInplace));
14704 check(x.round_inplace(), x.id(), |o| matches!(o, Op::RoundInplace));
14705 check(x.erf_inplace(), x.id(), |o| matches!(o, Op::ErfInplace));
14706 check(x.gelu_inplace(), x.id(), |o| matches!(o, Op::GeluInplace));
14707 check(x.clamp_inplace(-1.0, 1.0), x.id(), |o| {
14708 matches!(o, Op::ClampInplace { .. })
14709 });
14710 check(x.powi_inplace(3), x.id(), |o| {
14711 matches!(o, Op::PowIInplace(3))
14712 });
14713 }
14714
14715 /// Backward smoke for the expanded in-place op family — each variant
14716 /// (except zero-grad ones) must produce a gradient node for x without
14717 /// panicking. Zero-grad variants (Sign/Floor/Ceil/Round) drop the
14718 /// gradient entirely (no entry in the GradMap), mirroring their
14719 /// non-inplace cousins.
14720 #[test]
14721 fn backward_through_expanded_inplace_unary_emits_grad() {
14722 fn check_emits_grad(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14723 let x =
14724 NodeHandle::from_f32(vec![0.5_f32, 1.5, 2.5], Shape::from_dims(&[3]), cpu_dev())
14725 .unwrap();
14726 let y = make(&x);
14727 let loss = y.sum_all();
14728 let grads = loss.backward();
14729 assert!(grads.get(&x).is_some(), "backward must emit gradient for x");
14730 }
14731 check_emits_grad(|x| x.neg_inplace());
14732 check_emits_grad(|x| x.abs_inplace());
14733 check_emits_grad(|x| x.sqr_inplace());
14734 check_emits_grad(|x| x.sqrt_inplace());
14735 check_emits_grad(|x| x.rsqrt_inplace());
14736 check_emits_grad(|x| x.recip_inplace());
14737 check_emits_grad(|x| x.exp_inplace());
14738 check_emits_grad(|x| x.log_inplace());
14739 check_emits_grad(|x| x.sin_inplace());
14740 check_emits_grad(|x| x.cos_inplace());
14741 check_emits_grad(|x| x.erf_inplace());
14742 check_emits_grad(|x| x.gelu_inplace());
14743 check_emits_grad(|x| x.clamp_inplace(-1.0, 2.0));
14744 check_emits_grad(|x| x.powi_inplace(3));
14745 }
14746
14747 #[test]
14748 fn backward_through_zero_grad_inplace_drops_gradient() {
14749 fn check_drops(make: impl FnOnce(&NodeHandle) -> NodeHandle) {
14750 let x =
14751 NodeHandle::from_f32(vec![1.5_f32, 2.5, -3.5], Shape::from_dims(&[3]), cpu_dev())
14752 .unwrap();
14753 let y = make(&x);
14754 let loss = y.sum_all();
14755 let grads = loss.backward();
14756 assert!(
14757 grads.get(&x).is_none(),
14758 "zero-grad in-place op must not emit gradient"
14759 );
14760 }
14761 check_drops(|x| x.sign_inplace());
14762 check_drops(|x| x.floor_inplace());
14763 check_drops(|x| x.ceil_inplace());
14764 check_drops(|x| x.round_inplace());
14765 }
14766
14767 #[test]
14768 fn inplace_unary_derives_ordering_after_non_destructive_readers() {
14769 // Graph:
14770 // x = const f32 [4]
14771 // y_a = x.relu() (non-destructive reader of x)
14772 // y_b = manually-pushed Op::ReluInplace on x (destructive)
14773 // Expected: y_b must run after y_a.
14774 let x = NodeHandle::from_f32(
14775 vec![1.0_f32, -1.0, 2.0, -2.0],
14776 Shape::from_dims(&[4]),
14777 cpu_dev(),
14778 )
14779 .unwrap();
14780 let y_a = x.relu();
14781 let y_b_id = x.graph().write().unwrap().push(Node {
14782 op: Op::ReluInplace,
14783 inputs: vec![x.id()],
14784 shape: Shape::from_dims(&[4]),
14785 dtype: DType::F32,
14786 });
14787 let ord = crate::opt::derive_ordering(&x.graph().read().unwrap(), &[y_a.id(), y_b_id]);
14788 let deps = ord.deps_of(y_b_id);
14789 assert_eq!(deps.len(), 1, "in-place unary should have one ordering dep");
14790 assert_eq!(
14791 deps[0],
14792 y_a.id(),
14793 "in-place unary must run after the non-destructive reader"
14794 );
14795 }
14796
14797 // ------------------------------------------------------------------
14798 // Multi-output nodes (Option C, Session 1)
14799 // ------------------------------------------------------------------
14800
14801 use fuel_backend_contract::storage::Storage as CoreStorage;
14802 use fuel_ir::storage::OutputView;
14803
14804 /// Build a real CPU `Storage` of `n` F32 zeros so `Storage`-level
14805 /// tests can attach + read bundle metadata against a live backend
14806 /// allocator. The dtype is fixed at F32 because every existing
14807 /// `OutputView` test below uses F32 for slot 0; bundle dtype is
14808 /// validated at `with_bundle` time against this primary dtype.
14809 fn cpu_f32_storage(n: usize) -> CoreStorage {
14810 let dev = cpu_dev();
14811 let buf = fuel_ir::HostBuffer::F32(vec![0.0_f32; n]);
14812 let inner = dev
14813 .storage_from_host_buffer_owned_dyn(buf)
14814 .expect("test fixture: F32 storage_from_host_buffer_owned_dyn failed");
14815 CoreStorage::from_dyn(inner)
14816 }
14817
14818 /// Build a 2-slot bundle: slot 0 `[2, 3]` F32 `y`-shape, slot 1
14819 /// `[2, 4]` F32 `last_state`-shape. Returns the views and the
14820 /// total element count (used to size the backing CPU buffer so
14821 /// slot 1's byte range stays inside the bundle's bytes).
14822 fn two_slot_views() -> (Vec<OutputView>, usize) {
14823 let s0 = Shape::from_dims(&[2, 3]);
14824 let s1 = Shape::from_dims(&[2, 4]);
14825 let v0 = OutputView {
14826 byte_offset: 0,
14827 len_elements: s0.elem_count(),
14828 dtype: DType::F32,
14829 shape: s0.clone(),
14830 layout: Layout::contiguous(s0),
14831 name: Some("y"),
14832 };
14833 let v1 = OutputView {
14834 byte_offset: v0.len_bytes(),
14835 len_elements: s1.elem_count(),
14836 dtype: DType::F32,
14837 shape: s1.clone(),
14838 layout: Layout::contiguous(s1),
14839 name: Some("last_state"),
14840 };
14841 let total = v0.len_elements + v1.len_elements;
14842 (vec![v0, v1], total)
14843 }
14844
14845 /// `Storage::is_bundled` is false by default; `slot_count` is 1;
14846 /// `bundle` / `bundle_arc` / `slot_view` / `slot_dtype` all return
14847 /// `None` for the non-multi-output case.
14848 #[test]
14849 fn storage_single_output_defaults() {
14850 let s = cpu_f32_storage(8);
14851 assert!(!s.is_bundled());
14852 assert_eq!(s.slot_count(), 1);
14853 assert!(s.bundle().is_none());
14854 assert!(s.bundle_arc().is_none());
14855 assert!(s.slot_view(0).is_none());
14856 assert_eq!(s.slot_dtype(0), None);
14857 assert_eq!(s.primary_dtype(), DType::F32);
14858 assert_eq!(s.dtype(), DType::F32);
14859 }
14860
14861 /// `Storage::with_bundle` attaches the side-table and per-slot
14862 /// lookups report the declared shape/dtype.
14863 #[test]
14864 fn storage_with_bundle_attaches_views() {
14865 let (views, total) = two_slot_views();
14866 let s = cpu_f32_storage(total)
14867 .with_bundle(views.clone().into())
14868 .expect("with_bundle should accept matching slot-0 dtype");
14869 assert!(s.is_bundled());
14870 assert_eq!(s.slot_count(), 2);
14871 let slot0 = s.slot_view(0).unwrap();
14872 assert_eq!(slot0.shape, Shape::from_dims(&[2, 3]));
14873 assert_eq!(slot0.dtype, DType::F32);
14874 assert_eq!(slot0.byte_offset, 0);
14875 assert_eq!(slot0.name, Some("y"));
14876 let slot1 = s.slot_view(1).unwrap();
14877 assert_eq!(slot1.shape, Shape::from_dims(&[2, 4]));
14878 assert_eq!(slot1.byte_offset, 24); // 6 F32s = 24 bytes
14879 assert_eq!(slot1.name, Some("last_state"));
14880 // Out-of-range slot reads `None`, doesn't panic.
14881 assert!(s.slot_view(2).is_none());
14882 assert_eq!(s.slot_dtype(2), None);
14883 }
14884
14885 /// `Storage::with_bundle` rejects an empty bundle slice (a
14886 /// zero-slot bundle is a contract bug — use a single-output
14887 /// Storage if there's nothing to project).
14888 #[test]
14889 fn storage_with_bundle_rejects_empty() {
14890 let s = cpu_f32_storage(1);
14891 let empty: Arc<[OutputView]> = Arc::from(Vec::<OutputView>::new().into_boxed_slice());
14892 let err = s
14893 .with_bundle(empty)
14894 .expect_err("empty bundle slice must error");
14895 let msg = format!("{err}");
14896 assert!(msg.contains("non-empty"), "error message: {msg}");
14897 }
14898
14899 /// `Storage::with_bundle` rejects slot 0 dtype that disagrees with
14900 /// the inner backend dtype — the bundle invariant "slot 0 dtype ==
14901 /// primary_dtype()" must hold.
14902 #[test]
14903 fn storage_with_bundle_rejects_dtype_mismatch() {
14904 let s = cpu_f32_storage(8);
14905 let bad = OutputView {
14906 byte_offset: 0,
14907 len_elements: 4,
14908 dtype: DType::F64,
14909 shape: Shape::from_dims(&[2, 2]),
14910 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
14911 name: None,
14912 };
14913 let err = s
14914 .with_bundle(Arc::from(vec![bad].into_boxed_slice()))
14915 .expect_err("slot 0 dtype mismatch must error");
14916 let msg = format!("{err}");
14917 assert!(msg.contains("dtype"), "error message: {msg}");
14918 }
14919
14920 /// `Graph::output_views` is `None` for ordinary single-output
14921 /// nodes; `multi_output_count` is 0.
14922 #[test]
14923 fn graph_output_views_defaults() {
14924 let mut g = Graph::new();
14925 let id = g.push(Node {
14926 op: Op::Const,
14927 inputs: vec![],
14928 shape: Shape::from_dims(&[2, 3]),
14929 dtype: DType::F32,
14930 });
14931 assert!(g.output_views(id).is_none());
14932 assert!(!g.is_multi_output(id));
14933 assert_eq!(g.multi_output_count(), 0);
14934 }
14935
14936 /// `Graph::set_output_views` round-trips: read returns what was
14937 /// written; `is_multi_output` flips.
14938 #[test]
14939 fn graph_set_output_views_roundtrip() {
14940 let mut g = Graph::new();
14941 let id = g.push(Node {
14942 op: Op::Const,
14943 inputs: vec![],
14944 shape: Shape::from_dims(&[2, 3]),
14945 dtype: DType::F32,
14946 });
14947 let (views, _) = two_slot_views();
14948 g.set_output_views(id, views.clone().into())
14949 .expect("valid 2-slot specs");
14950 assert!(g.is_multi_output(id));
14951 assert_eq!(g.multi_output_count(), 1);
14952 let read = g.output_views(id).expect("entry present");
14953 assert_eq!(read.len(), 2);
14954 assert_eq!(read[1].shape, Shape::from_dims(&[2, 4]));
14955 }
14956
14957 /// `Graph::set_output_views` rejects slot 0 dtype/shape that
14958 /// disagree with the producer node's primary shape/dtype.
14959 #[test]
14960 fn graph_set_output_views_validates_primary() {
14961 let mut g = Graph::new();
14962 let id = g.push(Node {
14963 op: Op::Const,
14964 inputs: vec![],
14965 shape: Shape::from_dims(&[2, 3]),
14966 dtype: DType::F32,
14967 });
14968 // dtype mismatch on slot 0
14969 let bad_dtype = OutputView {
14970 byte_offset: 0,
14971 len_elements: 6,
14972 dtype: DType::F64,
14973 shape: Shape::from_dims(&[2, 3]),
14974 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
14975 name: None,
14976 };
14977 let err = g
14978 .set_output_views(id, vec![bad_dtype].into())
14979 .expect_err("primary dtype mismatch must error");
14980 let msg = format!("{err}");
14981 assert!(msg.contains("dtype"), "error message: {msg}");
14982 // shape mismatch on slot 0
14983 let bad_shape = OutputView {
14984 byte_offset: 0,
14985 len_elements: 4,
14986 dtype: DType::F32,
14987 shape: Shape::from_dims(&[2, 2]),
14988 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
14989 name: None,
14990 };
14991 let err = g
14992 .set_output_views(id, vec![bad_shape].into())
14993 .expect_err("primary shape mismatch must error");
14994 let msg = format!("{err}");
14995 assert!(msg.contains("shape"), "error message: {msg}");
14996 }
14997
14998 /// `NodeHandle::view(slot)` against a producer that hasn't been
14999 /// declared multi-output returns Err — fails fast at build time.
15000 #[test]
15001 fn tensor_view_on_non_multi_output_errors() {
15002 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15003 let id = graph.write().unwrap().push(Node {
15004 op: Op::Const,
15005 inputs: vec![],
15006 shape: Shape::from_dims(&[2, 3]),
15007 dtype: DType::F32,
15008 });
15009 let producer = NodeHandle::from_existing(Arc::clone(&graph), id);
15010 let err = producer
15011 .view(0)
15012 .expect_err("view on non-multi-output producer must error");
15013 let msg = format!("{err}");
15014 assert!(msg.contains("multi-output"), "error message: {msg}");
15015 }
15016
15017 /// `NodeHandle::view(slot)` with slot OOB returns Err.
15018 #[test]
15019 fn tensor_view_oob_slot_errors() {
15020 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15021 let producer_id = {
15022 let mut g = graph.write().unwrap();
15023 let id = g.push(Node {
15024 op: Op::Const,
15025 inputs: vec![],
15026 shape: Shape::from_dims(&[2, 3]),
15027 dtype: DType::F32,
15028 });
15029 let (views, _) = two_slot_views();
15030 g.set_output_views(id, views.into())
15031 .expect("valid 2-slot specs");
15032 id
15033 };
15034 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15035 let err = producer
15036 .view(2)
15037 .expect_err("slot 2 of a 2-slot producer must error");
15038 let msg = format!("{err}");
15039 assert!(msg.contains("out of range"), "error message: {msg}");
15040 }
15041
15042 /// `NodeHandle::view(slot)` produces a tensor whose shape/dtype match
15043 /// the slot spec; producer's primary shape stays as slot 0's. The
15044 /// View node holds the producer in `inputs[0]`.
15045 #[test]
15046 fn tensor_view_shape_dtype_from_slot() {
15047 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15048 let producer_id = {
15049 let mut g = graph.write().unwrap();
15050 let id = g.push(Node {
15051 op: Op::Const,
15052 inputs: vec![],
15053 shape: Shape::from_dims(&[2, 3]),
15054 dtype: DType::F32,
15055 });
15056 let (views, _) = two_slot_views();
15057 g.set_output_views(id, views.into())
15058 .expect("valid 2-slot specs");
15059 id
15060 };
15061 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15062 let v0 = producer.view(0).expect("slot 0 view");
15063 assert_eq!(v0.shape(), Shape::from_dims(&[2, 3]));
15064 assert_eq!(v0.dtype(), DType::F32);
15065 let v1 = producer.view(1).expect("slot 1 view");
15066 assert_eq!(v1.shape(), Shape::from_dims(&[2, 4]));
15067 assert_eq!(v1.dtype(), DType::F32);
15068 // View node carries the producer in inputs[0] and the slot
15069 // index in the Op variant — verify the Graph state directly.
15070 let g = graph.read().unwrap();
15071 let v1_node = g.node(v1.id());
15072 assert_eq!(v1_node.inputs, vec![producer_id]);
15073 assert!(matches!(v1_node.op, Op::View { slot: 1 }));
15074 // Slot 0 starts at byte_offset 0 + contiguous → layout
15075 // matches Layout::contiguous(slot0.shape) → no side-table
15076 // entry (the contiguous fallback covers it).
15077 assert!(!g.has_explicit_layout(v0.id()));
15078 // Slot 1 starts at byte_offset 24 (= 6 F32 elements past
15079 // slot 0). Session 4 bakes that into the layout's
15080 // start_offset so a downstream kernel reading the producer's
15081 // bytes as F32 elements lands on slot 1's first byte. Side-
15082 // table entry is mandatory.
15083 assert!(g.has_explicit_layout(v1.id()));
15084 let l1 = g.layout(v1.id());
15085 assert_eq!(
15086 l1.start_offset(),
15087 6,
15088 "slot 1 byte_offset 24 / 4 = 6 F32 elements"
15089 );
15090 assert_eq!(l1.shape(), &Shape::from_dims(&[2, 4]));
15091 }
15092
15093 /// `NodeHandle::view(slot)` over a slot whose layout is non-contiguous
15094 /// (strided) populates the Graph's layout side-table with the
15095 /// slot's layout — so downstream consumers see the strided view.
15096 #[test]
15097 fn tensor_view_propagates_non_contiguous_slot_layout() {
15098 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15099 let strided_shape = Shape::from_dims(&[2, 3]);
15100 let strided_layout = Layout::contiguous(strided_shape.clone())
15101 .transpose(0, 1)
15102 .expect("transpose [2,3] -> [3,2]");
15103 // Slot 0 = primary (contiguous, matches producer's Node shape).
15104 let s0 = OutputView {
15105 byte_offset: 0,
15106 len_elements: strided_shape.elem_count(),
15107 dtype: DType::F32,
15108 shape: strided_shape.clone(),
15109 layout: Layout::contiguous(strided_shape.clone()),
15110 name: Some("primary"),
15111 };
15112 // Slot 1 = strided projection. Same byte range as slot 0; the
15113 // shape after transpose is [3, 2]; layout's start offset stays
15114 // within the slot.
15115 let s1 = OutputView {
15116 byte_offset: 0,
15117 len_elements: strided_shape.elem_count(),
15118 dtype: DType::F32,
15119 shape: Shape::from_dims(&[3, 2]),
15120 layout: strided_layout.clone(),
15121 name: Some("strided_view"),
15122 };
15123 let producer_id = {
15124 let mut g = graph.write().unwrap();
15125 let id = g.push(Node {
15126 op: Op::Const,
15127 inputs: vec![],
15128 shape: strided_shape.clone(),
15129 dtype: DType::F32,
15130 });
15131 g.set_output_views(id, vec![s0, s1].into())
15132 .expect("valid 2-slot strided spec");
15133 id
15134 };
15135 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15136 let v1 = producer.view(1).expect("strided slot view");
15137 let g = graph.read().unwrap();
15138 assert!(
15139 g.has_explicit_layout(v1.id()),
15140 "strided slot must populate Graph::layouts side-table",
15141 );
15142 let read_layout = g.layout(v1.id());
15143 assert_eq!(read_layout.shape(), strided_layout.shape());
15144 assert_eq!(read_layout.stride(), strided_layout.stride());
15145 }
15146
15147 /// `NodeHandle::view_owned(slot)` produces the same shape/dtype as
15148 /// `NodeHandle::view(slot)` but its output layout is ALWAYS contiguous
15149 /// — the forward memcpy produces a fresh standalone buffer, so
15150 /// the slot's (possibly strided) layout is not propagated.
15151 #[test]
15152 fn tensor_view_owned_layout_is_contiguous() {
15153 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15154 let strided_shape = Shape::from_dims(&[2, 3]);
15155 let strided_layout = Layout::contiguous(strided_shape.clone())
15156 .transpose(0, 1)
15157 .expect("transpose [2,3] -> [3,2]");
15158 let s0 = OutputView {
15159 byte_offset: 0,
15160 len_elements: strided_shape.elem_count(),
15161 dtype: DType::F32,
15162 shape: strided_shape.clone(),
15163 layout: Layout::contiguous(strided_shape.clone()),
15164 name: None,
15165 };
15166 let s1 = OutputView {
15167 byte_offset: 0,
15168 len_elements: strided_shape.elem_count(),
15169 dtype: DType::F32,
15170 shape: Shape::from_dims(&[3, 2]),
15171 layout: strided_layout,
15172 name: None,
15173 };
15174 let producer_id = {
15175 let mut g = graph.write().unwrap();
15176 let id = g.push(Node {
15177 op: Op::Const,
15178 inputs: vec![],
15179 shape: strided_shape,
15180 dtype: DType::F32,
15181 });
15182 g.set_output_views(id, vec![s0, s1].into())
15183 .expect("valid 2-slot specs");
15184 id
15185 };
15186 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15187 let v1 = producer.view_owned(1).expect("ViewOwned slot 1");
15188 assert_eq!(v1.shape(), Shape::from_dims(&[3, 2]));
15189 assert_eq!(v1.dtype(), DType::F32);
15190 let g = graph.read().unwrap();
15191 // ViewOwned is a fresh allocation — no explicit layout entry,
15192 // contiguous layout falls through.
15193 assert!(!g.has_explicit_layout(v1.id()));
15194 let owned_node = g.node(v1.id());
15195 assert!(matches!(owned_node.op, Op::ViewOwned { slot: 1 }));
15196 }
15197
15198 // ------------------------------------------------------------------
15199 // Session 2: bundled allocator + FusedOpEntry::output_views +
15200 // View-vs-ViewOwned planner pass. The tests use the bundled
15201 // storage allocator and a synthetic 2-output FusedOp entry — no
15202 // real fused-op author migrates in Session 2; the
15203 // selective-scan-ssd-chunk-multi-output-followup session lights
15204 // up the first real consumer.
15205 // ------------------------------------------------------------------
15206
15207 use fuel_backend_contract::storage::allocate_bundled_storage;
15208 use fuel_ir::storage::OutputViewSpec;
15209
15210 /// `allocate_bundled_storage` allocates one Storage on the device,
15211 /// attaches the bundle, and slot lookups report the spec-derived
15212 /// byte_offsets.
15213 #[test]
15214 fn allocate_bundled_storage_two_slot_roundtrip() {
15215 let dev = cpu_dev();
15216 let specs = vec![
15217 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15218 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15219 ];
15220 let s =
15221 allocate_bundled_storage(dev.as_ref(), &specs).expect("two-slot F32 alloc succeeds");
15222 assert!(s.is_bundled());
15223 assert_eq!(s.slot_count(), 2);
15224 assert_eq!(s.primary_dtype(), DType::F32);
15225 let v0 = s.slot_view(0).unwrap();
15226 let v1 = s.slot_view(1).unwrap();
15227 assert_eq!(v0.byte_offset, 0);
15228 assert_eq!(v0.shape, Shape::from_dims(&[2, 3]));
15229 assert_eq!(v1.byte_offset, 24);
15230 assert_eq!(v1.shape, Shape::from_dims(&[2, 4]));
15231 }
15232
15233 /// `allocate_bundled_storage` handles mixed F32 + F64 slots — slot
15234 /// 0 is primary (F32), slot 1's bytes are aligned to its F64
15235 /// boundary, and the underlying allocation has enough flat F32
15236 /// elements to cover the total bundle bytes.
15237 #[test]
15238 fn allocate_bundled_storage_mixed_dtype() {
15239 let dev = cpu_dev();
15240 let specs = vec![
15241 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[6])),
15242 OutputViewSpec::contiguous(DType::F64, Shape::from_dims(&[3])),
15243 ];
15244 let s = allocate_bundled_storage(dev.as_ref(), &specs).expect("mixed-dtype alloc succeeds");
15245 assert_eq!(s.primary_dtype(), DType::F32);
15246 let v0 = s.slot_view(0).unwrap();
15247 let v1 = s.slot_view(1).unwrap();
15248 assert_eq!(v0.dtype, DType::F32);
15249 assert_eq!(v1.dtype, DType::F64);
15250 assert_eq!(v0.byte_offset, 0);
15251 // F32[6] = 24 bytes; 24 is already multiple of 8, so v1
15252 // starts at 24 without further padding.
15253 assert_eq!(v1.byte_offset, 24);
15254 }
15255
15256 /// `allocate_bundled_storage` propagates compose_bundle errors —
15257 /// an empty spec list errors out before touching the device.
15258 #[test]
15259 fn allocate_bundled_storage_rejects_empty() {
15260 let dev = cpu_dev();
15261 let err = allocate_bundled_storage(dev.as_ref(), &[]).expect_err("empty specs error");
15262 assert!(format!("{err}").contains("non-empty"));
15263 }
15264
15265 /// The two SelectiveScan / SsdChunkScan migrations from item 3
15266 /// (2026-06-01) are the first `default_registry` entries to
15267 /// declare `output_views`. Any new multi-output op author should
15268 /// extend the expected set here.
15269 #[test]
15270 fn default_registry_multi_output_entries() {
15271 let reg = crate::registry::default_registry();
15272 let mut multi_out_names: Vec<&'static str> = reg
15273 .entries_iter()
15274 .filter(|e| e.output_views.is_some())
15275 .map(|e| e.name)
15276 .collect();
15277 multi_out_names.sort();
15278 assert_eq!(
15279 multi_out_names,
15280 vec!["SelectiveScan", "SsdChunkScan"],
15281 "the multi-output registry set should match the item-3 \
15282 migrations (SelectiveScan + SsdChunkScan); add new \
15283 multi-output ops to this list as they migrate",
15284 );
15285 }
15286
15287 /// Authoring-contract invariant: for every multi-output entry in
15288 /// the process-wide registry, `shape_rule(inputs)` MUST equal
15289 /// `output_views(inputs)[0].shape` and `dtype_rule(inputs)` MUST
15290 /// equal `output_views(inputs)[0].dtype`. Slot 0 is the primary
15291 /// and the bundled-allocation contract assumes the producer's
15292 /// `Node.shape`/`Node.dtype` reflect it.
15293 #[test]
15294 fn multi_output_entries_slot_0_matches_primary_rules() {
15295 use crate::registry::FusedOpParams;
15296 let reg = crate::registry::default_registry();
15297
15298 // Each multi-output entry needs a representative input batch
15299 // (shapes + dtypes + params) that satisfies its
15300 // shape_rule/dtype_rule preconditions. The check below runs
15301 // once per entry using these fixtures.
15302 struct Fixture {
15303 shapes: Vec<Shape>,
15304 dtypes: Vec<DType>,
15305 params: FusedOpParams,
15306 }
15307 fn selective_scan_fixture() -> Fixture {
15308 Fixture {
15309 shapes: vec![
15310 Shape::from_dims(&[2, 4, 8]), // u: [batch, seqlen, dim]
15311 Shape::from_dims(&[2, 4, 8]), // delta: same
15312 Shape::from_dims(&[8, 16]), // a: [dim, dstate]
15313 Shape::from_dims(&[2, 4, 16]), // b: [batch, seqlen, dstate]
15314 Shape::from_dims(&[2, 4, 16]), // c: same
15315 ],
15316 dtypes: vec![DType::F32; 5],
15317 params: FusedOpParams::SelectiveScan {
15318 delta_softplus: false,
15319 },
15320 }
15321 }
15322 fn ssd_chunk_scan_fixture() -> Fixture {
15323 Fixture {
15324 shapes: vec![
15325 Shape::from_dims(&[2, 4, 3, 8]), // x: [batch, seqlen, heads, head_dim]
15326 Shape::from_dims(&[2, 4, 3]), // dt: [batch, seqlen, heads]
15327 Shape::from_dims(&[3]), // a: [heads]
15328 Shape::from_dims(&[2, 4, 3, 16]), // b: [batch, seqlen, heads, state_dim]
15329 Shape::from_dims(&[2, 4, 3, 16]), // c: same
15330 ],
15331 dtypes: vec![DType::F32; 5],
15332 params: FusedOpParams::SsdChunkScan { chunk_size: 4 },
15333 }
15334 }
15335
15336 for entry in reg.entries_iter().filter(|e| e.output_views.is_some()) {
15337 let fx = match entry.name {
15338 "SelectiveScan" => selective_scan_fixture(),
15339 "SsdChunkScan" => ssd_chunk_scan_fixture(),
15340 other => panic!(
15341 "multi_output_entries_slot_0_matches_primary_rules: \
15342 no fixture for new multi-output entry {other:?}. \
15343 Add one to this test as you register a new op.",
15344 ),
15345 };
15346 let primary_shape = (entry.shape_rule)(&fx.shapes, &fx.params);
15347 let primary_dtype = (entry.dtype_rule)(&fx.dtypes, &fx.params);
15348 let specs = entry.output_views.unwrap()(&fx.shapes, &fx.dtypes, &fx.params);
15349 assert!(
15350 !specs.is_empty(),
15351 "{}: output_views returned empty Vec (multi-output ops \
15352 must have ≥ 1 slot)",
15353 entry.name,
15354 );
15355 assert_eq!(
15356 specs[0].shape, primary_shape,
15357 "{}: output_views[0].shape {:?} must equal shape_rule \
15358 {:?} (slot 0 is the primary; Node::shape reflects it)",
15359 entry.name, specs[0].shape, primary_shape,
15360 );
15361 assert_eq!(
15362 specs[0].dtype, primary_dtype,
15363 "{}: output_views[0].dtype {:?} must equal dtype_rule \
15364 {:?} (slot 0 is the primary; Node::dtype reflects it)",
15365 entry.name, specs[0].dtype, primary_dtype,
15366 );
15367 // Layout-shape coherence: each slot's layout shape must
15368 // equal its declared shape (the same invariant
15369 // set_output_views enforces at graph-build time).
15370 for (i, spec) in specs.iter().enumerate() {
15371 assert_eq!(
15372 spec.layout.shape(),
15373 &spec.shape,
15374 "{}: slot {i} layout.shape() {:?} disagrees with \
15375 declared spec.shape {:?}",
15376 entry.name,
15377 spec.layout.shape(),
15378 spec.shape,
15379 );
15380 }
15381 }
15382 }
15383
15384 /// Build a synthetic multi-output `FusedOpEntry` to exercise the
15385 /// authoring contract end-to-end without polluting the production
15386 /// registry. The output_views fn returns a 2-slot spec list whose
15387 /// slot 0 matches shape_rule / dtype_rule (the primary).
15388 fn synthetic_two_output_entry() -> crate::registry::FusedOpEntry {
15389 fn shape(_: &[Shape], _: &crate::registry::FusedOpParams) -> Shape {
15390 Shape::from_dims(&[2, 3])
15391 }
15392 fn dtype(_: &[DType], _: &crate::registry::FusedOpParams) -> DType {
15393 DType::F32
15394 }
15395 fn ovs(
15396 _: &[Shape],
15397 _: &[DType],
15398 _: &crate::registry::FusedOpParams,
15399 ) -> Vec<OutputViewSpec> {
15400 vec![
15401 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 3])),
15402 OutputViewSpec::contiguous(DType::F32, Shape::from_dims(&[2, 4])),
15403 ]
15404 }
15405 crate::registry::FusedOpEntry {
15406 destructive_input: None,
15407 id: crate::registry::FusedOps::SOFTMAX_LAST_DIM, // any id; not registered
15408 name: "<synthetic-2-output>",
15409 family: crate::registry::FusedOpFamily::Forward,
15410 pattern: crate::registry::SubgraphPattern::Callable(|_g, _id| None),
15411 decompose: |_g, id, _p| id,
15412 backward: crate::registry::BackwardKind::NotDifferentiable,
15413 shape_rule: shape,
15414 dtype_rule: dtype,
15415 output_views: Some(ovs),
15416 }
15417 }
15418
15419 /// The synthetic entry's `output_views` matches the
15420 /// `shape_rule`/`dtype_rule` contract on slot 0.
15421 #[test]
15422 fn synthetic_entry_output_views_matches_primary_contract() {
15423 let entry = synthetic_two_output_entry();
15424 let ovs_fn = entry.output_views.expect("synthetic entry is multi-output");
15425 let specs = ovs_fn(&[], &[], &crate::registry::FusedOpParams::SoftmaxLastDim);
15426 assert_eq!(specs.len(), 2);
15427 assert_eq!(
15428 specs[0].dtype,
15429 (entry.dtype_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15430 );
15431 assert_eq!(
15432 specs[0].shape,
15433 (entry.shape_rule)(&[], &crate::registry::FusedOpParams::SoftmaxLastDim)
15434 );
15435 }
15436
15437 /// Build a producer Const node and declare it multi-output via
15438 /// `Graph::set_output_views`. Returns the producer's NodeId and a
15439 /// SharedGraph handle.
15440 fn multi_output_producer(slots: Vec<OutputView>) -> (SharedGraph, NodeId) {
15441 let graph: SharedGraph = Arc::new(RwLock::new(Graph::new()));
15442 let id = {
15443 let mut g = graph.write().unwrap();
15444 let id = g.push(Node {
15445 op: Op::Const,
15446 inputs: vec![],
15447 shape: slots[0].shape.clone(),
15448 dtype: slots[0].dtype,
15449 });
15450 g.set_output_views(id, slots.into())
15451 .expect("valid synthetic specs");
15452 id
15453 };
15454 (graph, id)
15455 }
15456
15457 /// Two slots, both consumed at the same topo depth → planner does
15458 /// nothing (symmetric lifetimes, bundle drops naturally).
15459 #[test]
15460 fn promote_views_symmetric_lifetimes_is_noop() {
15461 let slot_specs = vec![
15462 OutputView {
15463 byte_offset: 0,
15464 len_elements: 6,
15465 dtype: DType::F32,
15466 shape: Shape::from_dims(&[2, 3]),
15467 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15468 name: Some("y"),
15469 },
15470 OutputView {
15471 byte_offset: 24,
15472 len_elements: 8,
15473 dtype: DType::F32,
15474 shape: Shape::from_dims(&[2, 4]),
15475 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15476 name: Some("state"),
15477 },
15478 ];
15479 let (graph, producer_id) = multi_output_producer(slot_specs);
15480 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15481 // Each slot has exactly one View, consumed at the same depth
15482 // (a no-op Relu downstream of each).
15483 let v0 = producer.view(0).expect("slot 0 view");
15484 let v1 = producer.view(1).expect("slot 1 view");
15485 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15486 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15487 let roots = {
15488 let mut g = graph.write().unwrap();
15489 let r0 = g.push(Node {
15490 op: Op::Relu,
15491 inputs: vec![v0_id],
15492 shape: v0_shape,
15493 dtype: v0_dtype,
15494 });
15495 let r1 = g.push(Node {
15496 op: Op::Relu,
15497 inputs: vec![v1_id],
15498 shape: v1_shape,
15499 dtype: v1_dtype,
15500 });
15501 vec![r0, r1]
15502 };
15503 let promotions = {
15504 let mut g = graph.write().unwrap();
15505 crate::opt::promote_views_for_liveness(&mut g, &roots)
15506 };
15507 assert_eq!(
15508 promotions, 0,
15509 "symmetric lifetimes shouldn't promote anything"
15510 );
15511 }
15512
15513 /// Asymmetric lifetimes: slot 0 consumed early, slot 1 consumed
15514 /// late → planner promotes slot 1's View to ViewOwned.
15515 #[test]
15516 fn promote_views_asymmetric_promotes_long_lived_slot() {
15517 let slot_specs = vec![
15518 OutputView {
15519 byte_offset: 0,
15520 len_elements: 6,
15521 dtype: DType::F32,
15522 shape: Shape::from_dims(&[2, 3]),
15523 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15524 name: Some("y"),
15525 },
15526 OutputView {
15527 byte_offset: 24,
15528 len_elements: 6,
15529 dtype: DType::F32,
15530 shape: Shape::from_dims(&[2, 3]),
15531 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15532 name: Some("state"),
15533 },
15534 ];
15535 let (graph, producer_id) = multi_output_producer(slot_specs);
15536 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15537 let v_y = producer.view(0).expect("slot 0 view");
15538 let v_state = producer.view(1).expect("slot 1 view");
15539 // Slot 0 ("y") consumed at depth 1 (single Relu).
15540 // Slot 1 ("state") consumed at a much deeper chain — Relu →
15541 // Relu → Relu. Topo positions push state's last-use later
15542 // than y's, triggering promotion of state's View.
15543 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15544 let (v_state_id, v_state_shape, v_state_dtype) =
15545 (v_state.id(), v_state.shape(), v_state.dtype());
15546 let roots = {
15547 let mut g = graph.write().unwrap();
15548 let y_relu = g.push(Node {
15549 op: Op::Relu,
15550 inputs: vec![v_y_id],
15551 shape: v_y_shape,
15552 dtype: v_y_dtype,
15553 });
15554 let s1 = g.push(Node {
15555 op: Op::Relu,
15556 inputs: vec![v_state_id],
15557 shape: v_state_shape.clone(),
15558 dtype: v_state_dtype,
15559 });
15560 let s2 = g.push(Node {
15561 op: Op::Relu,
15562 inputs: vec![s1],
15563 shape: v_state_shape.clone(),
15564 dtype: v_state_dtype,
15565 });
15566 let s3 = g.push(Node {
15567 op: Op::Relu,
15568 inputs: vec![s2],
15569 shape: v_state_shape,
15570 dtype: v_state_dtype,
15571 });
15572 vec![y_relu, s3]
15573 };
15574 let promotions = {
15575 let mut g = graph.write().unwrap();
15576 crate::opt::promote_views_for_liveness(&mut g, &roots)
15577 };
15578 assert_eq!(
15579 promotions, 1,
15580 "exactly the long-lived slot 1 View should promote"
15581 );
15582 // Slot 1's consumer (the first Relu in the long chain) now
15583 // reads a fresh Op::ViewOwned node, not the old Op::View.
15584 let g = graph.read().unwrap();
15585 // Find the new ViewOwned node — it was pushed AFTER the
15586 // existing nodes, so it's the last node in the arena. Its op
15587 // must be Op::ViewOwned { slot: 1 } and its input must be the
15588 // producer.
15589 let last_id = NodeId(g.len() - 1);
15590 let last_node = g.node(last_id);
15591 assert!(matches!(last_node.op, Op::ViewOwned { slot: 1 }));
15592 assert_eq!(last_node.inputs, vec![producer_id]);
15593 // The slot 0 View is untouched — still Op::View.
15594 let v_y_node = g.node(v_y_id);
15595 assert!(matches!(v_y_node.op, Op::View { slot: 0 }));
15596 // The old slot 1 View stays in the arena (orphaned). No
15597 // consumer points at it anymore.
15598 let v_state_node = g.node(v_state_id);
15599 assert!(matches!(v_state_node.op, Op::View { slot: 1 }));
15600 }
15601
15602 /// Running the pass twice on the same graph promotes nothing on
15603 /// the second call — `Op::ViewOwned` is a fixpoint (skipped by
15604 /// the planner because `is_owned` is true).
15605 #[test]
15606 fn promote_views_idempotent() {
15607 let slot_specs = vec![
15608 OutputView {
15609 byte_offset: 0,
15610 len_elements: 4,
15611 dtype: DType::F32,
15612 shape: Shape::from_dims(&[2, 2]),
15613 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15614 name: None,
15615 },
15616 OutputView {
15617 byte_offset: 16,
15618 len_elements: 4,
15619 dtype: DType::F32,
15620 shape: Shape::from_dims(&[2, 2]),
15621 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15622 name: None,
15623 },
15624 ];
15625 let (graph, producer_id) = multi_output_producer(slot_specs);
15626 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15627 let v_y = producer.view(0).expect("slot 0 view");
15628 let v_state = producer.view(1).expect("slot 1 view");
15629 let (v_y_id, v_y_shape, v_y_dtype) = (v_y.id(), v_y.shape(), v_y.dtype());
15630 let (v_state_id, v_state_shape, v_state_dtype) =
15631 (v_state.id(), v_state.shape(), v_state.dtype());
15632 let roots = {
15633 let mut g = graph.write().unwrap();
15634 let y_r = g.push(Node {
15635 op: Op::Relu,
15636 inputs: vec![v_y_id],
15637 shape: v_y_shape,
15638 dtype: v_y_dtype,
15639 });
15640 let s1 = g.push(Node {
15641 op: Op::Relu,
15642 inputs: vec![v_state_id],
15643 shape: v_state_shape.clone(),
15644 dtype: v_state_dtype,
15645 });
15646 let s2 = g.push(Node {
15647 op: Op::Relu,
15648 inputs: vec![s1],
15649 shape: v_state_shape,
15650 dtype: v_state_dtype,
15651 });
15652 vec![y_r, s2]
15653 };
15654 let first = {
15655 let mut g = graph.write().unwrap();
15656 crate::opt::promote_views_for_liveness(&mut g, &roots)
15657 };
15658 let second = {
15659 let mut g = graph.write().unwrap();
15660 crate::opt::promote_views_for_liveness(&mut g, &roots)
15661 };
15662 assert_eq!(first, 1, "first call promotes the long-lived slot");
15663 assert_eq!(
15664 second, 0,
15665 "second call is idempotent — no further promotions"
15666 );
15667 }
15668
15669 /// Graph with no multi-output producers: pass returns 0 and
15670 /// touches nothing.
15671 #[test]
15672 fn promote_views_noop_on_graph_without_multi_output() {
15673 let mut g = Graph::new();
15674 let a = g.push(Node {
15675 op: Op::Const,
15676 inputs: vec![],
15677 shape: Shape::from_dims(&[2, 3]),
15678 dtype: DType::F32,
15679 });
15680 let r = g.push(Node {
15681 op: Op::Relu,
15682 inputs: vec![a],
15683 shape: Shape::from_dims(&[2, 3]),
15684 dtype: DType::F32,
15685 });
15686 let n_before = g.len();
15687 let promotions = crate::opt::promote_views_for_liveness(&mut g, &[r]);
15688 assert_eq!(promotions, 0);
15689 assert_eq!(g.len(), n_before, "no node should have been added");
15690 }
15691
15692 // ------------------------------------------------------------------
15693 // Session 3: scheduler / destructive-cleanup integration —
15694 // bundle-aware liveness. A destructive op on a multi-output
15695 // producer (or any of its Views) must run after every reader of
15696 // every other View, because all Views share the bundle's storage
15697 // Arc. Op::ViewOwned is excluded — it forks a fresh standalone
15698 // Storage at execute time.
15699 // ------------------------------------------------------------------
15700
15701 /// Helper: build two contiguous slot specs for a producer of
15702 /// `Node::shape = [2, 3] F32`. Slot 0 is the primary (matches the
15703 /// producer's Node::shape/dtype, required by set_output_views);
15704 /// slot 1 carries a sibling shape that doesn't collide with the
15705 /// primary.
15706 fn two_slot_views_2x3_and_2x4() -> Vec<OutputView> {
15707 vec![
15708 OutputView {
15709 byte_offset: 0,
15710 len_elements: 6,
15711 dtype: DType::F32,
15712 shape: Shape::from_dims(&[2, 3]),
15713 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15714 name: Some("y"),
15715 },
15716 OutputView {
15717 byte_offset: 24,
15718 len_elements: 8,
15719 dtype: DType::F32,
15720 shape: Shape::from_dims(&[2, 4]),
15721 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15722 name: Some("state"),
15723 },
15724 ]
15725 }
15726
15727 /// Op::Release targeting a multi-output producer pins after every
15728 /// consumer of any View of that producer. Without bundle-aware
15729 /// aliasing the Views' downstream Relu nodes would be missed and
15730 /// could race the Release.
15731 #[test]
15732 fn derive_ordering_release_of_bundled_producer_pins_after_view_consumers() {
15733 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15734 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15735 let v0 = producer.view(0).expect("slot 0 view");
15736 let v1 = producer.view(1).expect("slot 1 view");
15737 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15738 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15739 let (r0, r1, release_id) = {
15740 let mut g = graph.write().unwrap();
15741 let r0 = g.push(Node {
15742 op: Op::Relu,
15743 inputs: vec![v0_id],
15744 shape: v0_shape,
15745 dtype: v0_dtype,
15746 });
15747 let r1 = g.push(Node {
15748 op: Op::Relu,
15749 inputs: vec![v1_id],
15750 shape: v1_shape,
15751 dtype: v1_dtype,
15752 });
15753 let release = g.push(Node {
15754 op: Op::Release,
15755 inputs: vec![producer_id],
15756 shape: Shape::from_dims(&[0]),
15757 dtype: DType::F32,
15758 });
15759 (r0, r1, release)
15760 };
15761 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r0, r1, release_id]);
15762 let deps = ord.deps_of(release_id);
15763 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15764 assert!(
15765 dep_set.contains(&r0),
15766 "Release must run after the slot-0 View's consumer (r0)",
15767 );
15768 assert!(
15769 dep_set.contains(&r1),
15770 "Release must run after the slot-1 View's consumer (r1) — \
15771 both Views share the bundle Arc",
15772 );
15773 }
15774
15775 /// Destructive op targeting one of a bundle's Op::View nodes
15776 /// pins after every sibling View's consumers too — every View
15777 /// of the producer shares the bundle's Arc, so writing through
15778 /// one of them clobbers the bytes the others read.
15779 #[test]
15780 fn derive_ordering_destructive_on_view_pins_sibling_view_consumers() {
15781 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15782 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15783 let v0 = producer.view(0).expect("slot 0 view");
15784 let v1 = producer.view(1).expect("slot 1 view");
15785 let (v0_id, _v0_shape, _v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15786 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15787 // Destructive op (Release) targets v0 directly — its
15788 // alias set must reach v1's consumer via the producer-sibling
15789 // hop in collect_alias_set.
15790 let (r1, release_id) = {
15791 let mut g = graph.write().unwrap();
15792 let r1 = g.push(Node {
15793 op: Op::Relu,
15794 inputs: vec![v1_id],
15795 shape: v1_shape,
15796 dtype: v1_dtype,
15797 });
15798 let release = g.push(Node {
15799 op: Op::Release,
15800 inputs: vec![v0_id],
15801 shape: Shape::from_dims(&[0]),
15802 dtype: DType::F32,
15803 });
15804 (r1, release)
15805 };
15806 let ord = crate::opt::derive_ordering(&graph.read().unwrap(), &[r1, release_id]);
15807 let deps = ord.deps_of(release_id);
15808 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15809 assert!(
15810 dep_set.contains(&r1),
15811 "Release targeting slot-0 View must pin after sibling slot-1 \
15812 View's consumer (r1) — both share the bundle's storage Arc",
15813 );
15814 }
15815
15816 /// Op::ViewOwned does NOT extend the alias set: its forward
15817 /// memcpy produces an independent Storage. derive_ordering must
15818 /// still pin Release after the ViewOwned itself (via the standard
15819 /// data-dependency: ViewOwned consumes the producer), but
15820 /// downstream consumers of the ViewOwned are NOT in the alias
15821 /// set's reader sweep — they read independent bytes and may run
15822 /// freely after the Release.
15823 #[test]
15824 fn derive_ordering_view_owned_is_not_alias_extending() {
15825 let (graph, producer_id) = multi_output_producer(two_slot_views_2x3_and_2x4());
15826 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15827 // Slot 0 → View (shared Arc); slot 1 → ViewOwned (independent).
15828 let v_view = producer.view(0).expect("slot 0 view");
15829 let v_owned = producer.view_owned(1).expect("slot 1 viewowned");
15830 let (v_view_id, _, _) = (v_view.id(), v_view.shape(), v_view.dtype());
15831 let (v_owned_id, v_owned_shape, v_owned_dtype) =
15832 (v_owned.id(), v_owned.shape(), v_owned.dtype());
15833 let (consumer_of_owned, release_id) = {
15834 let mut g = graph.write().unwrap();
15835 let consumer = g.push(Node {
15836 op: Op::Relu,
15837 inputs: vec![v_owned_id],
15838 shape: v_owned_shape,
15839 dtype: v_owned_dtype,
15840 });
15841 let release = g.push(Node {
15842 op: Op::Release,
15843 inputs: vec![producer_id],
15844 shape: Shape::from_dims(&[0]),
15845 dtype: DType::F32,
15846 });
15847 (consumer, release)
15848 };
15849 let ord =
15850 crate::opt::derive_ordering(&graph.read().unwrap(), &[consumer_of_owned, release_id]);
15851 let deps = ord.deps_of(release_id);
15852 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15853 // Release MUST wait for ViewOwned to run (ViewOwned reads
15854 // the producer's bytes during its memcpy).
15855 assert!(
15856 dep_set.contains(&v_owned_id),
15857 "Release must pin after ViewOwned — ViewOwned reads the \
15858 producer's bundle during its memcpy phase",
15859 );
15860 // Release must NOT depend on the ViewOwned's downstream
15861 // consumer — that consumer reads ViewOwned's independent
15862 // bytes, not the producer's bundle.
15863 assert!(
15864 !dep_set.contains(&consumer_of_owned),
15865 "Release must NOT pin after consumers of ViewOwned — \
15866 ViewOwned forks a fresh Storage; its consumers don't \
15867 read the producer's bundle",
15868 );
15869 // Op::View's consumers stay reached via the alias chain; here
15870 // there are none (v_view has no consumer), so v_view itself
15871 // is the only alias-set entry beyond the producer.
15872 let _ = v_view_id;
15873 }
15874
15875 /// Long-tail bundle-aware schedule: a producer with three Views,
15876 /// each consumed by a chain of different depth, and a destructive
15877 /// Release on the producer. The Release must end up after every
15878 /// terminal consumer of every chain — bundle-as-single-eviction-
15879 /// unit semantics fall out of derive_ordering's alias-set walk
15880 /// reaching each chain's leaf via the producer-then-View hop.
15881 #[test]
15882 fn derive_ordering_bundle_release_pins_after_all_chains() {
15883 // Build a 3-slot bundle. Slot 0 primary [2,3] F32 satisfies
15884 // the producer's Node::shape/dtype constraint; slots 1 + 2
15885 // add sibling shapes.
15886 let slot_specs = vec![
15887 OutputView {
15888 byte_offset: 0,
15889 len_elements: 6,
15890 dtype: DType::F32,
15891 shape: Shape::from_dims(&[2, 3]),
15892 layout: Layout::contiguous(Shape::from_dims(&[2, 3])),
15893 name: Some("a"),
15894 },
15895 OutputView {
15896 byte_offset: 24,
15897 len_elements: 4,
15898 dtype: DType::F32,
15899 shape: Shape::from_dims(&[2, 2]),
15900 layout: Layout::contiguous(Shape::from_dims(&[2, 2])),
15901 name: Some("b"),
15902 },
15903 OutputView {
15904 byte_offset: 40,
15905 len_elements: 8,
15906 dtype: DType::F32,
15907 shape: Shape::from_dims(&[2, 4]),
15908 layout: Layout::contiguous(Shape::from_dims(&[2, 4])),
15909 name: Some("c"),
15910 },
15911 ];
15912 let (graph, producer_id) = multi_output_producer(slot_specs);
15913 let producer = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
15914 let v0 = producer.view(0).unwrap();
15915 let v1 = producer.view(1).unwrap();
15916 let v2 = producer.view(2).unwrap();
15917 let (v0_id, v0_shape, v0_dtype) = (v0.id(), v0.shape(), v0.dtype());
15918 let (v1_id, v1_shape, v1_dtype) = (v1.id(), v1.shape(), v1.dtype());
15919 let (v2_id, v2_shape, v2_dtype) = (v2.id(), v2.shape(), v2.dtype());
15920 let (leaf_a, leaf_b, leaf_c, release_id) = {
15921 let mut g = graph.write().unwrap();
15922 let leaf_a = g.push(Node {
15923 op: Op::Relu,
15924 inputs: vec![v0_id],
15925 shape: v0_shape,
15926 dtype: v0_dtype,
15927 });
15928 let b1 = g.push(Node {
15929 op: Op::Relu,
15930 inputs: vec![v1_id],
15931 shape: v1_shape.clone(),
15932 dtype: v1_dtype,
15933 });
15934 let leaf_b = g.push(Node {
15935 op: Op::Relu,
15936 inputs: vec![b1],
15937 shape: v1_shape,
15938 dtype: v1_dtype,
15939 });
15940 let c1 = g.push(Node {
15941 op: Op::Relu,
15942 inputs: vec![v2_id],
15943 shape: v2_shape.clone(),
15944 dtype: v2_dtype,
15945 });
15946 let c2 = g.push(Node {
15947 op: Op::Relu,
15948 inputs: vec![c1],
15949 shape: v2_shape.clone(),
15950 dtype: v2_dtype,
15951 });
15952 let leaf_c = g.push(Node {
15953 op: Op::Relu,
15954 inputs: vec![c2],
15955 shape: v2_shape,
15956 dtype: v2_dtype,
15957 });
15958 let release = g.push(Node {
15959 op: Op::Release,
15960 inputs: vec![producer_id],
15961 shape: Shape::from_dims(&[0]),
15962 dtype: DType::F32,
15963 });
15964 (leaf_a, leaf_b, leaf_c, release)
15965 };
15966 let ord = crate::opt::derive_ordering(
15967 &graph.read().unwrap(),
15968 &[leaf_a, leaf_b, leaf_c, release_id],
15969 );
15970 let deps = ord.deps_of(release_id);
15971 let dep_set: std::collections::HashSet<NodeId> = deps.iter().copied().collect();
15972 // The direct readers of any View are the FIRST relu in each
15973 // chain — those are the nodes that read the bundle's bytes.
15974 // Every consumer further down reads its predecessor's
15975 // standalone output Storage, so they aren't in the alias-set
15976 // reader sweep. Verify the Release pins on the direct
15977 // readers — sufficient for bundle-single-eviction safety
15978 // because the chains are themselves data-dep ordered after
15979 // their direct readers.
15980 assert!(
15981 dep_set.contains(&leaf_a),
15982 "single-Relu chain a: leaf is the direct reader",
15983 );
15984 // For the b/c chains, the direct readers are the first Relus
15985 // (b1 / c1), not the leaves. The Release must include those.
15986 // Find them by walking inputs from leaves.
15987 let g = graph.read().unwrap();
15988 let b1 = g.node(leaf_b).inputs[0];
15989 let (c2, c1) = {
15990 let c2 = g.node(leaf_c).inputs[0];
15991 let c1 = g.node(c2).inputs[0];
15992 (c2, c1)
15993 };
15994 let _ = c2;
15995 assert!(
15996 dep_set.contains(&b1),
15997 "two-Relu chain b: first Relu is the direct bundle reader",
15998 );
15999 assert!(
16000 dep_set.contains(&c1),
16001 "three-Relu chain c: first Relu is the direct bundle reader",
16002 );
16003 }
16004
16005 // ------------------------------------------------------------------
16006 // Item 4 — Op::View / Op::ViewOwned autograd emits Op::ScatterIntoSlot
16007 // ------------------------------------------------------------------
16008
16009 /// The View's backward arm pushes an `Op::ScatterIntoSlot { slot }`
16010 /// node into the gradient graph as the producer's input gradient.
16011 /// Synthetic test: build a 2-slot producer + Op::View(slot 1) +
16012 /// a Relu downstream + invoke NodeHandle::backward + walk the produced
16013 /// gradient graph and assert a ScatterIntoSlot was emitted.
16014 #[test]
16015 fn op_view_backward_emits_scatter_into_slot() {
16016 let producer_t =
16017 NodeHandle::from_f32(vec![0.0_f32; 6], Shape::from_dims(&[2, 3]), cpu_dev()).unwrap();
16018 let graph: SharedGraph = Arc::clone(producer_t.graph());
16019 let producer_id = producer_t.id();
16020 let view_id = {
16021 let mut g = graph.write().unwrap();
16022 let specs = two_slot_views_2x3_and_2x4();
16023 g.set_output_views(producer_id, specs.into())
16024 .expect("output_views");
16025 drop(g);
16026 let v1 = producer_t.view(1).expect("slot 1 view");
16027 v1.id()
16028 };
16029 // Build a tiny tape-tracked loss = sum(relu(v1)).
16030 let v1_tensor = NodeHandle::from_existing(Arc::clone(&graph), view_id);
16031 let relu_t = v1_tensor.relu();
16032 let loss_t = relu_t.sum_all();
16033
16034 // Take backward — exercises the View's backward arm.
16035 let grads = loss_t.backward();
16036
16037 // The producer's input gradient should be reachable via a
16038 // chain that includes an Op::ScatterIntoSlot { slot: 1 } node.
16039 let producer_tensor = NodeHandle::from_existing(Arc::clone(&graph), producer_id);
16040 let grad_for_producer = grads
16041 .get(&producer_tensor)
16042 .expect("producer has an accumulated gradient");
16043 let grad_id = grad_for_producer.id();
16044 let g = graph.read().unwrap();
16045 let scatter_present = matches!(g.node(grad_id).op, Op::ScatterIntoSlot { slot: 1 }) || {
16046 // Walk one hop back through `Op::Add` accumulations
16047 // if any.
16048 let n = g.node(grad_id);
16049 n.inputs
16050 .iter()
16051 .any(|inp| matches!(g.node(*inp).op, Op::ScatterIntoSlot { slot: 1 }))
16052 };
16053 assert!(
16054 scatter_present,
16055 "View(slot=1) backward must emit an Op::ScatterIntoSlot {{ slot: 1 }} \
16056 into the gradient graph; got grad node op = {:?}",
16057 g.node(grad_id).op,
16058 );
16059 }
16060
16061 // ----- Op::Branch inert scaffold (Phase A PR-A0 of the
16062 // "plan IS the graph" rebuild) -----
16063
16064 /// Back-compat by construction: a graph with ZERO `Op::Branch`
16065 /// nodes builds with exactly the arena it had before the variant
16066 /// existed. The locked design guarantees "a graph with zero
16067 /// Op::Branch nodes is exactly today's single-route graph" — this
16068 /// test pins that: the same builder calls produce the same node
16069 /// count, the same topo order, and not a single `Op::Branch` node.
16070 /// GAP-003 STEP 1: the panic IS reachable from the public API today.
16071 ///
16072 /// `NodeHandle::from_f32` returns `Self`, so a length/shape mismatch has
16073 /// nowhere to go but `assert_eq!` inside `from_host_buffer_on`. This test
16074 /// PASSES today and is deleted by the fix -- it exists to prove the defect
16075 /// is live from a caller's seat, not merely present in the source.
16076 /// GAP-003: a length/shape mismatch DECLINES instead of panicking.
16077 ///
16078 /// ⚠️ This started life as a `#[should_panic]` probe proving the defect was
16079 /// reachable from the public API. The bulk `.unwrap()` pass then appended
16080 /// `.unwrap()` to it, and it KEPT PASSING -- for the wrong reason: unwrapping
16081 /// an `Err` panics, and the `Err` message contains the expected substring, so
16082 /// the assertion could no longer tell "the API panics" from "I unwrapped a
16083 /// Result". A vacuous green produced by the very edit that fixed the defect.
16084 ///
16085 /// It now asserts the `Err` DIRECTLY, with no `unwrap`, and matches on the
16086 /// LENGTH-MISMATCH message specifically -- not merely on `is_err()`. That
16087 /// distinction is load-bearing: `from_host_buffer_on` has a second failure
16088 /// path (`storage_from_host_buffer_owned_dyn`), so a bare `is_err()` could
16089 /// not tell this decline from that one.
16090 #[test]
16091 fn gap003_from_f32_declines_a_length_mismatch() {
16092 // 2 elements declared as a 3-element shape.
16093 let err = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[3]), cpu_dev())
16094 .expect_err("a length/shape mismatch must DECLINE, not construct");
16095 let msg = err.to_string();
16096 assert!(
16097 msg.contains("does not match shape element count"),
16098 "the decline must name the LENGTH MISMATCH specifically, got: {msg}"
16099 );
16100 assert!(
16101 msg.contains('2') && msg.contains('3'),
16102 "and both operands: {msg}"
16103 );
16104
16105 // CONTROL: a MATCHING length still constructs, so the guard is not
16106 // "this constructor always fails".
16107 assert!(
16108 NodeHandle::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), cpu_dev()).is_ok()
16109 );
16110 }
16111
16112 #[test]
16113 fn zero_branch_graph_builds_unchanged() {
16114 // Build: c = (a + b) * a — the same DAG the topo-order tests
16115 // use, exercised here purely to prove the arena is untouched by
16116 // the new variant.
16117 let a = NodeHandle::from_f32(vec![1.0, 2.0], Shape::from_dims(&[2]), cpu_dev()).unwrap();
16118 let b = a
16119 .const_f32_like(vec![3.0, 4.0], Shape::from_dims(&[2]))
16120 .unwrap();
16121 let sum = a.add(&b);
16122 let c = sum.mul(&a);
16123
16124 let g = c.graph();
16125 let guard = g.read().unwrap();
16126
16127 // Exactly four nodes (a, b, sum, c) — no implicit Branch
16128 // anywhere.
16129 assert_eq!(
16130 guard.len(),
16131 4,
16132 "zero-Branch graph must have the same node count as before"
16133 );
16134
16135 // Topo order is unchanged and contains zero Branch nodes.
16136 let order = topo_order(&guard, c.id());
16137 assert_eq!(order.len(), 4);
16138 let branch_count = order
16139 .iter()
16140 .filter(|&&id| matches!(guard.node(id).op, Op::Branch { .. }))
16141 .count();
16142 assert_eq!(branch_count, 0, "no builder constructs Op::Branch in PR-A0");
16143
16144 // The ops are exactly the ones the builders emitted (no
16145 // structural rewrite slipped in a merge node).
16146 assert!(matches!(guard.node(a.id()).op, Op::Const));
16147 assert!(matches!(guard.node(b.id()).op, Op::Const));
16148 assert!(matches!(guard.node(sum.id()).op, Op::Add));
16149 assert!(matches!(guard.node(c.id()).op, Op::Mul));
16150 }
16151
16152 /// The variant exists and its infallible accessor behaves: a
16153 /// hand-constructed `Op::Branch` reports `short_name() == "Branch"`,
16154 /// and the multi-path encoding (arms = `inputs`, explicit
16155 /// `reconverge_at`) round-trips through the arena. This is the only
16156 /// place in PR-A0 that constructs the variant — the production
16157 /// builders land in PR-A1.
16158 #[test]
16159 fn branch_variant_exists_and_short_name_works() {
16160 // short_name / the Op::short_name() facade both return the
16161 // stable "Branch" constant.
16162 let reconverge = NodeId(7);
16163 let branch_op = Op::Branch {
16164 reconverge_at: reconverge,
16165 };
16166 assert_eq!(branch_op.short_name(), "Branch");
16167 assert_eq!(op_short_name(&branch_op), "Branch");
16168
16169 // Structural nodes carry no destructive input (matches the
16170 // other structural ops: Const / View / ScatterIntoSlot).
16171 assert_eq!(branch_op.destructive_input(), None);
16172
16173 // Encode a 2-arm merge directly on the arena: two route exits
16174 // as `inputs`, the reconvergence node named explicitly. Prove
16175 // the encoding survives a push + read-back unchanged.
16176 let mut g = Graph::new();
16177 let arm0 = g.push(Node {
16178 op: Op::Const,
16179 inputs: vec![],
16180 shape: Shape::from_dims(&[2]),
16181 dtype: DType::F32,
16182 });
16183 let arm1 = g.push(Node {
16184 op: Op::Const,
16185 inputs: vec![],
16186 shape: Shape::from_dims(&[2]),
16187 dtype: DType::F32,
16188 });
16189 let merged = g.push(Node {
16190 op: Op::Const,
16191 inputs: vec![],
16192 shape: Shape::from_dims(&[2]),
16193 dtype: DType::F32,
16194 });
16195 let branch = g.push(Node {
16196 op: Op::Branch {
16197 reconverge_at: merged,
16198 },
16199 inputs: vec![arm0, arm1],
16200 shape: Shape::from_dims(&[2]),
16201 dtype: DType::F32,
16202 });
16203
16204 let node = g.node(branch);
16205 assert_eq!(node.op.short_name(), "Branch");
16206 // Arms are the node's inputs (each input = one route's exit).
16207 assert_eq!(node.inputs, vec![arm0, arm1]);
16208 // The explicit reconvergence node is carried on the op.
16209 match node.op {
16210 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, merged),
16211 ref other => panic!("expected Op::Branch, got {other:?}"),
16212 }
16213 }
16214
16215 // ----- Op::Branch builders + build-time validation
16216 // (Phase A PR-A1 of the "plan IS the graph" rebuild) -----
16217
16218 /// Hand-build a 2-arm diamond directly on the arena and return the
16219 /// pieces the branch builders will stitch together:
16220 /// `diverge` → {`arm0`, `arm1`} → `reconverge`. The reconverge node
16221 /// already reads arm0 as input 0, which is exactly the runnability
16222 /// invariant the builders must preserve (a finalized-but-unpicked
16223 /// branch still realizes on arm 0). Every node is `[2] f32` so the
16224 /// cast-to-uniform check has agreeing shape/dtype across arms.
16225 fn diamond_2arm() -> (Graph, NodeId, NodeId, NodeId, NodeId) {
16226 let mut g = Graph::new();
16227 let diverge = g.push(Node {
16228 op: Op::Const,
16229 inputs: vec![],
16230 shape: Shape::from_dims(&[2]),
16231 dtype: DType::F32,
16232 });
16233 // arm0 = relu(diverge), arm1 = silu(diverge): two interior nodes,
16234 // each reachable only through its own arm from the diverge point.
16235 let arm0 = g.push(Node {
16236 op: Op::Relu,
16237 inputs: vec![diverge],
16238 shape: Shape::from_dims(&[2]),
16239 dtype: DType::F32,
16240 });
16241 let arm1 = g.push(Node {
16242 op: Op::Silu,
16243 inputs: vec![diverge],
16244 shape: Shape::from_dims(&[2]),
16245 dtype: DType::F32,
16246 });
16247 // reconverge reads arm0 (runnability: arm 0 is always input 0).
16248 let reconverge = g.push(Node {
16249 op: Op::Relu,
16250 inputs: vec![arm0],
16251 shape: Shape::from_dims(&[2]),
16252 dtype: DType::F32,
16253 });
16254 (g, diverge, arm0, arm1, reconverge)
16255 }
16256
16257 /// (a) A 2-arm diamond round-trips through
16258 /// `open_branch`/`add_arm`/`finalize_branches`: it produces exactly
16259 /// one valid `Op::Branch` node whose `inputs` are the arm exits in
16260 /// order and whose `reconverge_at` is the named merge node.
16261 #[test]
16262 fn two_arm_diamond_round_trips_to_branch_node() {
16263 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16264 let before = g.len();
16265
16266 let mut b = g.open_branch(diverge);
16267 b.add_arm(arm0);
16268 b.add_arm(arm1);
16269 let branch = b
16270 .finalize_branches(&mut g, reconverge)
16271 .expect("well-formed 2-arm branch must finalize")
16272 .expect("2 arms survive — not collapsed to a single arm");
16273
16274 // Exactly one node was appended (the Branch); no orphan debris.
16275 assert_eq!(g.len(), before + 1);
16276
16277 let node = g.node(branch);
16278 assert!(matches!(node.op, Op::Branch { .. }));
16279 // Arms are the node's inputs, in add order: arm0 first.
16280 assert_eq!(node.inputs, vec![arm0, arm1]);
16281 match node.op {
16282 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, reconverge),
16283 ref other => panic!("expected Op::Branch, got {other:?}"),
16284 }
16285 // The merge node still carries arm0's shape/dtype (cast-to-uniform
16286 // validated, not rewritten).
16287 assert_eq!(node.shape, g.node(arm0).shape);
16288 assert_eq!(node.dtype, g.node(arm0).dtype);
16289 }
16290
16291 /// (b) A `reconverge_at` that is NOT a descendant of the diverge
16292 /// point returns `Error::InvalidBranch` — never a panic.
16293 #[test]
16294 fn reconverge_not_descendant_of_diverge_is_typed_err() {
16295 let (mut g, diverge, arm0, arm1, _reconverge) = diamond_2arm();
16296 // A sibling node that does NOT descend from `diverge`.
16297 let unrelated = g.push(Node {
16298 op: Op::Const,
16299 inputs: vec![],
16300 shape: Shape::from_dims(&[2]),
16301 dtype: DType::F32,
16302 });
16303
16304 let mut b = g.open_branch(diverge);
16305 b.add_arm(arm0);
16306 b.add_arm(arm1);
16307 let err = b
16308 .finalize_branches(&mut g, unrelated)
16309 .expect_err("reconverge that doesn't descend from diverge must be rejected");
16310 assert!(
16311 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16312 "expected InvalidBranch, got {err:?}",
16313 );
16314 }
16315
16316 /// (c) A non-disjoint arm — an arm interior node reachable from
16317 /// outside that arm (shared with the rest of the graph) — returns
16318 /// `Error::InvalidBranch`.
16319 #[test]
16320 fn non_disjoint_arm_is_typed_err() {
16321 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16322 // Add a reader OUTSIDE the branch that consumes arm0's interior.
16323 // arm0 is now reachable from a node that isn't part of the merge,
16324 // so the arm is not internally disjoint.
16325 let _external_reader = g.push(Node {
16326 op: Op::Relu,
16327 inputs: vec![arm0],
16328 shape: Shape::from_dims(&[2]),
16329 dtype: DType::F32,
16330 });
16331
16332 let mut b = g.open_branch(diverge);
16333 b.add_arm(arm0);
16334 b.add_arm(arm1);
16335 let err = b
16336 .finalize_branches(&mut g, reconverge)
16337 .expect_err("an arm interior read from outside the branch must be rejected");
16338 assert!(
16339 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16340 "expected InvalidBranch, got {err:?}",
16341 );
16342 }
16343
16344 /// (c') Arms that disagree on shape/dtype at their exits violate
16345 /// cast-to-uniform and return `Error::InvalidBranch` (validate-and-Err
16346 /// — no implicit Cast insertion in PR-A1).
16347 #[test]
16348 fn arms_disagreeing_on_dtype_is_typed_err() {
16349 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16350 // A second arm with a DIFFERENT dtype than arm0.
16351 let arm1_f16 = g.push(Node {
16352 op: Op::Silu,
16353 inputs: vec![diverge],
16354 shape: Shape::from_dims(&[2]),
16355 dtype: DType::F16,
16356 });
16357
16358 let mut b = g.open_branch(diverge);
16359 b.add_arm(arm0);
16360 b.add_arm(arm1_f16);
16361 let err = b
16362 .finalize_branches(&mut g, reconverge)
16363 .expect_err("arms with mismatched dtype must be rejected (cast-to-uniform)");
16364 assert!(
16365 matches!(err, fuel_ir::Error::InvalidBranch { .. }),
16366 "expected InvalidBranch, got {err:?}",
16367 );
16368 }
16369
16370 /// (d) `finalize_branches` drops a single-arm branch: with only one
16371 /// surviving arm there is no real decision point, so no `Op::Branch`
16372 /// node is emitted (`Ok(None)`), the arena is left untouched, and the
16373 /// graph collapses back to that arm.
16374 #[test]
16375 fn single_arm_branch_is_dropped() {
16376 let (mut g, diverge, arm0, _arm1, reconverge) = diamond_2arm();
16377 let before = g.len();
16378
16379 let mut b = g.open_branch(diverge);
16380 b.add_arm(arm0);
16381 let result = b
16382 .finalize_branches(&mut g, reconverge)
16383 .expect("a single-arm branch is valid — it just collapses");
16384 assert!(
16385 result.is_none(),
16386 "single-arm branch must NOT emit an Op::Branch"
16387 );
16388 // No node appended: the lone arm is the graph, unchanged.
16389 assert_eq!(
16390 g.len(),
16391 before,
16392 "dropping a single-arm branch leaves the arena untouched"
16393 );
16394 let branch_count = (0..g.len())
16395 .filter(|&i| matches!(g.node(NodeId(i)).op, Op::Branch { .. }))
16396 .count();
16397 assert_eq!(branch_count, 0);
16398 }
16399
16400 /// (e) The runnability invariant: the emitted `Op::Branch`'s inputs
16401 /// always include arm-0's exit as input 0, so a finalized-but-not-yet-
16402 /// route-picked graph still realizes on arm 0 (a graph with a
16403 /// finalized branch must still be executable). The named reconverge
16404 /// node reads arm-0's exit, so realizing on arm 0 alone produces a
16405 /// defined value at the merge.
16406 #[test]
16407 fn finalized_branch_preserves_arm0_runnability() {
16408 let (mut g, diverge, arm0, arm1, reconverge) = diamond_2arm();
16409
16410 let mut b = g.open_branch(diverge);
16411 b.add_arm(arm0);
16412 b.add_arm(arm1);
16413 let branch = b
16414 .finalize_branches(&mut g, reconverge)
16415 .expect("well-formed branch finalizes")
16416 .expect("2 arms survive");
16417
16418 // arm 0 is input 0 of the Branch — the always-realizable route.
16419 assert_eq!(g.node(branch).inputs.first().copied(), Some(arm0));
16420 // And the named reconverge node reads arm0, so realizing on
16421 // arm 0 alone produces a defined value at the merge.
16422 assert!(
16423 g.node(reconverge).inputs.contains(&arm0),
16424 "reconverge must read arm-0's exit so the unpicked graph runs on arm 0",
16425 );
16426 }
16427
16428 // ===================================================================
16429 // PR-B4: required compaction of the append-only arena.
16430 // ===================================================================
16431
16432 use crate::run::{extract_runs, lower_runs_arm0};
16433
16434 /// Build the same 2-arm diamond the run.rs tests use, finalized into a
16435 /// real `Op::Branch`. Returns `(g, diverge, arm0, arm1, reconverge,
16436 /// branch, post)`. `post` reads `reconverge`, so the post-merge region
16437 /// is a non-empty run and `post` is a stable root.
16438 fn diamond_with_branch_b4() -> (Graph, NodeId, NodeId, NodeId, NodeId, NodeId, NodeId) {
16439 let mk = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
16440 g.push(Node {
16441 op,
16442 inputs,
16443 shape: Shape::from_dims(&[2]),
16444 dtype: DType::F32,
16445 })
16446 };
16447 let mut g = Graph::new();
16448 let pre = mk(&mut g, Op::Const, vec![]);
16449 let diverge = mk(&mut g, Op::Relu, vec![pre]);
16450 let arm0 = mk(&mut g, Op::Silu, vec![diverge]);
16451 let arm1 = mk(&mut g, Op::GeluTanh, vec![diverge]);
16452 let reconverge = mk(&mut g, Op::Relu, vec![arm0]);
16453 let mut b = g.open_branch(diverge);
16454 b.add_arm(arm0);
16455 b.add_arm(arm1);
16456 let branch = b
16457 .finalize_branches(&mut g, reconverge)
16458 .expect("well-formed 2-arm branch finalizes")
16459 .expect("2 arms survive");
16460 let post = mk(&mut g, Op::Tanh, vec![reconverge]);
16461 (g, diverge, arm0, arm1, reconverge, branch, post)
16462 }
16463
16464 /// PR-D1 storage-class substrate: the op-inferred class is correct
16465 /// (`Op::Const` → Shared, `Op::WriteSlice` → SessionState, other →
16466 /// Transient), an explicit override beats the inferred default (a
16467 /// KV-cache placeholder `Op::Const` marked SessionState), and `compact`
16468 /// carries the override to the node's new id while inferred defaults
16469 /// still hold. Born-red: fails if classification, override precedence,
16470 /// or the compaction remap is wrong.
16471 #[test]
16472 fn storage_class_inference_override_and_compaction() {
16473 let mut g = Graph::new();
16474 // A shared weight Const, a session-state KV placeholder Const, a
16475 // transient activation, and an in-place cache-write target.
16476 let weight = g.push(Node {
16477 op: Op::Const,
16478 inputs: vec![],
16479 shape: Shape::from_dims(&[2]),
16480 dtype: DType::F32,
16481 });
16482 let kv = g.push(Node {
16483 op: Op::Const,
16484 inputs: vec![],
16485 shape: Shape::from_dims(&[2]),
16486 dtype: DType::F32,
16487 });
16488 let act = g.push(Node {
16489 op: Op::Relu,
16490 inputs: vec![weight],
16491 shape: Shape::from_dims(&[2]),
16492 dtype: DType::F32,
16493 });
16494 let write = g.push(Node {
16495 op: Op::WriteSlice {
16496 ranges: vec![(0, 2)],
16497 dyn_offset: None,
16498 },
16499 inputs: vec![kv, act],
16500 shape: Shape::from_dims(&[2]),
16501 dtype: DType::F32,
16502 });
16503
16504 // Op-inferred defaults.
16505 assert_eq!(
16506 g.storage_class(weight),
16507 StorageClass::Shared,
16508 "Const → Shared"
16509 );
16510 assert_eq!(
16511 g.storage_class(act),
16512 StorageClass::Transient,
16513 "activation → Transient"
16514 );
16515 assert_eq!(
16516 g.storage_class(write),
16517 StorageClass::SessionState,
16518 "WriteSlice → SessionState"
16519 );
16520 // No overrides set yet.
16521 assert_eq!(
16522 g.storage_class(kv),
16523 StorageClass::Shared,
16524 "KV placeholder Const infers Shared before override"
16525 );
16526 assert!(!g.has_storage_class_override(kv));
16527 assert_eq!(g.storage_class_override_count(), 0);
16528
16529 // Explicit override: the KV placeholder is session state, not a
16530 // shared weight.
16531 g.set_storage_class(kv, StorageClass::SessionState);
16532 assert_eq!(
16533 g.storage_class(kv),
16534 StorageClass::SessionState,
16535 "override beats inferred default"
16536 );
16537 assert!(g.has_storage_class_override(kv));
16538 assert_eq!(g.storage_class_override_count(), 1);
16539
16540 // Compaction carries the override to the new id; inferred defaults
16541 // (no side-table entry) still resolve from the op.
16542 let remap = compact(&mut g, &[write]);
16543 let n_kv = remap.get(kv).expect("kv survives (input of write)");
16544 let n_weight = remap
16545 .get(weight)
16546 .expect("weight survives (transitively under act)");
16547 let n_write = remap.get(write).expect("write is the root");
16548 assert_eq!(
16549 g.storage_class(n_kv),
16550 StorageClass::SessionState,
16551 "override remapped by compact"
16552 );
16553 assert!(g.has_storage_class_override(n_kv));
16554 assert_eq!(
16555 g.storage_class_override_count(),
16556 1,
16557 "exactly the one override survives"
16558 );
16559 assert_eq!(
16560 g.storage_class(n_weight),
16561 StorageClass::Shared,
16562 "inferred Shared still holds post-compact"
16563 );
16564 assert_eq!(
16565 g.storage_class(n_write),
16566 StorageClass::SessionState,
16567 "inferred SessionState still holds post-compact"
16568 );
16569 assert!(g.verify_no_dangling().is_ok());
16570 }
16571
16572 /// (a) A deliberately-orphaned node (pushed, referenced by nothing) is
16573 /// dropped by `compact`; the node count shrinks by exactly the orphan
16574 /// count, and every still-reachable node survives.
16575 #[test]
16576 fn compact_drops_orphan_debris() {
16577 let mut g = Graph::new();
16578 let a = g.push(Node {
16579 op: Op::Const,
16580 inputs: vec![],
16581 shape: Shape::from_dims(&[2]),
16582 dtype: DType::F32,
16583 });
16584 let b = g.push(Node {
16585 op: Op::Relu,
16586 inputs: vec![a],
16587 shape: Shape::from_dims(&[2]),
16588 dtype: DType::F32,
16589 });
16590 let c = g.push(Node {
16591 op: Op::Silu,
16592 inputs: vec![b],
16593 shape: Shape::from_dims(&[2]),
16594 dtype: DType::F32,
16595 });
16596 // Two pieces of exploration debris: reachable from nothing in the
16597 // live structure (no root, no side-effect, no branch references them).
16598 let _orphan0 = g.push(Node {
16599 op: Op::Const,
16600 inputs: vec![],
16601 shape: Shape::from_dims(&[2]),
16602 dtype: DType::F32,
16603 });
16604 let _orphan1 = g.push(Node {
16605 op: Op::Tanh,
16606 inputs: vec![_orphan0],
16607 shape: Shape::from_dims(&[2]),
16608 dtype: DType::F32,
16609 });
16610
16611 let before = g.len();
16612 let remap = compact(&mut g, &[c]);
16613
16614 assert_eq!(
16615 g.len(),
16616 before - 2,
16617 "compaction drops exactly the two orphan-debris nodes",
16618 );
16619 // The three reachable nodes all survived (have new ids).
16620 assert!(remap.get(a).is_some());
16621 assert!(remap.get(b).is_some());
16622 assert!(remap.get(c).is_some());
16623 // The orphans are gone.
16624 assert!(remap.get(_orphan0).is_none());
16625 assert!(remap.get(_orphan1).is_none());
16626 // The surviving chain still resolves: c' reads b' reads a'.
16627 let (na, nb, nc) = (
16628 remap.get(a).unwrap(),
16629 remap.get(b).unwrap(),
16630 remap.get(c).unwrap(),
16631 );
16632 assert_eq!(g.node(nc).inputs, vec![nb]);
16633 assert_eq!(g.node(nb).inputs, vec![na]);
16634 assert_eq!(g.node(na).inputs, Vec::<NodeId>::new());
16635 assert_no_dangling(&g);
16636 }
16637
16638 /// (b) Branches preserved: a graph with a finalized `Op::Branch` keeps
16639 /// every arm + `reconverge_at` after compaction (remapped), and the
16640 /// arm-0 lowering yields the same logical route.
16641 #[test]
16642 fn compact_preserves_branch_arms_and_reconverge() {
16643 let (mut g, _diverge, arm0, arm1, reconverge, branch, post) = diamond_with_branch_b4();
16644
16645 // Inject orphan debris so compaction has something to drop and the
16646 // surviving-branch claim is non-trivial.
16647 let _debris = g.push(Node {
16648 op: Op::Const,
16649 inputs: vec![],
16650 shape: Shape::from_dims(&[2]),
16651 dtype: DType::F32,
16652 });
16653
16654 // Baseline arm-0 route over old ids, mapped to the op sequence.
16655 let before_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16656 .iter()
16657 .map(|&id| g.node(id).op.short_name())
16658 .collect();
16659
16660 let remap = compact(&mut g, &[post]);
16661
16662 // Every branch participant survived.
16663 let narm0 = remap.get(arm0).expect("arm0 survives");
16664 let narm1 = remap
16665 .get(arm1)
16666 .expect("arm1 (the non-fallback arm) survives");
16667 let nrecon = remap.get(reconverge).expect("reconverge survives");
16668 let nbranch = remap.get(branch).expect("the Branch node itself survives");
16669 let npost = remap.get(post).expect("post survives");
16670
16671 // The Branch's inputs are the remapped arm exits (arm0 first), and
16672 // its reconverge_at is the remapped reconverge — it still resolves.
16673 let bn = g.node(nbranch);
16674 assert!(matches!(bn.op, Op::Branch { .. }));
16675 assert_eq!(
16676 bn.inputs,
16677 vec![narm0, narm1],
16678 "arm exits remapped, arm0 first"
16679 );
16680 match bn.op {
16681 Op::Branch { reconverge_at } => assert_eq!(reconverge_at, nrecon),
16682 ref other => panic!("expected Op::Branch, got {other:?}"),
16683 }
16684 // reconverge still reads arm0 (runnability preserved through remap).
16685 assert!(g.node(nrecon).inputs.contains(&narm0));
16686 // The arm-0 route is logically identical (same op sequence).
16687 let after_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16688 .iter()
16689 .map(|&id| g.node(id).op.short_name())
16690 .collect();
16691 assert_eq!(before_ops, after_ops, "arm-0 route is logically unchanged");
16692 assert_no_dangling(&g);
16693 }
16694
16695 /// (c) Base map preserved: a branchless, fully-reachable graph compacts
16696 /// to itself — no node dropped; ids may renumber but the structure is
16697 /// identical.
16698 #[test]
16699 fn compact_branchless_reachable_is_identity_in_structure() {
16700 let mut g = Graph::new();
16701 let a = g.push(Node {
16702 op: Op::Const,
16703 inputs: vec![],
16704 shape: Shape::from_dims(&[2]),
16705 dtype: DType::F32,
16706 });
16707 let b = g.push(Node {
16708 op: Op::Relu,
16709 inputs: vec![a],
16710 shape: Shape::from_dims(&[2]),
16711 dtype: DType::F32,
16712 });
16713 let c = g.push(Node {
16714 op: Op::Silu,
16715 inputs: vec![b],
16716 shape: Shape::from_dims(&[2]),
16717 dtype: DType::F32,
16718 });
16719 let d = g.push(Node {
16720 op: Op::Tanh,
16721 inputs: vec![c],
16722 shape: Shape::from_dims(&[2]),
16723 dtype: DType::F32,
16724 });
16725
16726 let before_ops: Vec<&'static str> = extract_runs(&g, d)
16727 .iter()
16728 .flat_map(|r| {
16729 r.members
16730 .iter()
16731 .map(|&id| g.node(id).op.short_name())
16732 .collect::<Vec<_>>()
16733 })
16734 .collect();
16735 let before_len = g.len();
16736
16737 let remap = compact(&mut g, &[d]);
16738
16739 assert_eq!(g.len(), before_len, "a fully-reachable graph drops nothing");
16740 for n in [a, b, c, d] {
16741 assert!(remap.get(n).is_some(), "every node survives");
16742 }
16743 // Structure identical: same op sequence over the compacted graph.
16744 let nd = remap.get(d).unwrap();
16745 let after_ops: Vec<&'static str> = extract_runs(&g, nd)
16746 .iter()
16747 .flat_map(|r| {
16748 r.members
16749 .iter()
16750 .map(|&id| g.node(id).op.short_name())
16751 .collect::<Vec<_>>()
16752 })
16753 .collect();
16754 assert_eq!(before_ops, after_ops);
16755 assert_no_dangling(&g);
16756 }
16757
16758 /// (d) No dangling + round-trip: after `compact`, NO NodeId reference
16759 /// (node inputs, op-carried `reconverge_at`, or any side-table) points
16760 /// outside the new arena, AND `extract_runs` / arm-0 lowering on the
16761 /// compacted graph yields the identical logical result, including for
16762 /// graphs carrying every side-table (placements, target_backends,
16763 /// layouts, storage_map, node_output_views, side_effect_roots).
16764 #[test]
16765 fn compact_no_dangling_and_round_trip_with_side_tables() {
16766 let (mut g, diverge, arm0, _arm1, reconverge, _branch, post) = diamond_with_branch_b4();
16767
16768 // Populate side-tables on surviving nodes so the remap must carry
16769 // them. (target_backend on a couple nodes; placement on one.)
16770 g.set_target_backend(arm0, BackendId::Cpu);
16771 g.set_target_backend(reconverge, BackendId::Cpu);
16772 g.set_placement(diverge, DeviceLocation::Cpu);
16773 // A side-effect root that is itself orphan-from-roots: a Release-like
16774 // op the executor must keep even though no output reads it.
16775 let se = g.push(Node {
16776 op: Op::Const,
16777 inputs: vec![post],
16778 shape: Shape::from_dims(&[2]),
16779 dtype: DType::F32,
16780 });
16781 g.add_side_effect_root(se);
16782
16783 // Orphan debris (referenced by nothing live) to force a real drop.
16784 let _debris = g.push(Node {
16785 op: Op::Const,
16786 inputs: vec![],
16787 shape: Shape::from_dims(&[2]),
16788 dtype: DType::F32,
16789 });
16790
16791 let before_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[post])
16792 .iter()
16793 .map(|&id| g.node(id).op.short_name())
16794 .collect();
16795
16796 let remap = compact(&mut g, &[post]);
16797
16798 // No dangling references anywhere.
16799 assert_no_dangling(&g);
16800
16801 // The side-effect root survived (a side-effect-only node is a
16802 // reachability seed) and its side-table entry was remapped.
16803 let nse = remap.get(se).expect("side-effect root survives compaction");
16804 assert!(
16805 g.side_effect_roots().contains(&nse),
16806 "the remapped side-effect root is registered post-compaction",
16807 );
16808 // The surviving target_backend side-table is keyed by the new ids.
16809 assert_eq!(
16810 g.target_backend(remap.get(arm0).unwrap()),
16811 Some(BackendId::Cpu)
16812 );
16813 assert_eq!(
16814 g.target_backend(remap.get(reconverge).unwrap()),
16815 Some(BackendId::Cpu)
16816 );
16817 assert_eq!(
16818 g.placement(remap.get(diverge).unwrap()),
16819 Some(DeviceLocation::Cpu)
16820 );
16821
16822 // Round-trip: the arm-0 route is logically identical.
16823 let npost = remap.get(post).unwrap();
16824 let after_run_ops: Vec<&'static str> = lower_runs_arm0(&g, &[npost])
16825 .iter()
16826 .map(|&id| g.node(id).op.short_name())
16827 .collect();
16828 assert_eq!(
16829 before_run_ops, after_run_ops,
16830 "compaction preserves the realized arm-0 route exactly",
16831 );
16832 }
16833
16834 /// Helper: assert NO NodeId reference in the graph points outside the
16835 /// arena. Covers node `inputs`, the op-carried `Op::Branch.reconverge_at`,
16836 /// every NodeId-keyed side-table, and the `side_effect_roots` vec — the
16837 /// exhaustive no-dangling safety net for a missed remap.
16838 fn assert_no_dangling(g: &Graph) {
16839 let n = g.len();
16840 let ok = |id: NodeId| id.0 < n;
16841 for i in 0..n {
16842 let node = g.node(NodeId(i));
16843 for &inp in &node.inputs {
16844 assert!(ok(inp), "Node#{i} input {:?} dangles (len={n})", inp);
16845 }
16846 if let Op::Branch { reconverge_at } = node.op {
16847 assert!(
16848 ok(reconverge_at),
16849 "Node#{i} Branch.reconverge_at {:?} dangles (len={n})",
16850 reconverge_at
16851 );
16852 }
16853 }
16854 for &r in g.side_effect_roots() {
16855 assert!(ok(r), "side_effect_root {:?} dangles (len={n})", r);
16856 }
16857 // Use the graph's own verification entry point as the load-bearing
16858 // assert (it covers every side-table by reading the private fields).
16859 assert!(
16860 g.verify_no_dangling().is_ok(),
16861 "Graph::verify_no_dangling found a dangling reference: {:?}",
16862 g.verify_no_dangling().err(),
16863 );
16864 }
16865
16866 #[test]
16867 fn scan_variants_construct_and_name() {
16868 use crate::{Graph, Node, Op, ScanEmit, ScanPredicate, ScanRole};
16869 use fuel_ir::{DType, Shape};
16870 let mut g = Graph::new();
16871 let s = Shape::from_dims(&[1, 1, 1]);
16872 let carry = g.push(Node {
16873 op: Op::Const,
16874 inputs: vec![],
16875 shape: s.clone(),
16876 dtype: DType::F32,
16877 });
16878 // A ScanPlaceholder leaf (the per-step carry hole).
16879 let hole = g.push(Node {
16880 op: Op::ScanPlaceholder {
16881 role: ScanRole::Carry,
16882 index: 0,
16883 },
16884 inputs: vec![],
16885 shape: s.clone(),
16886 dtype: DType::F32,
16887 });
16888 // A trivial body: new_carry = hole (identity); body_y = hole.
16889 // Op::Scan node: inputs = [init_carry, <no xs>, <no consts>, body_new_carry, body_y].
16890 let scan = g.push(Node {
16891 op: Op::Scan {
16892 n_carries: 1,
16893 n_xs: 0,
16894 bound: 1,
16895 emit: ScanEmit::All,
16896 early_exit: None,
16897 },
16898 inputs: vec![carry, hole, hole],
16899 shape: s.clone(),
16900 dtype: DType::F32,
16901 });
16902 assert_eq!(g.node(scan).op.short_name(), "Scan");
16903 assert_eq!(g.node(hole).op.short_name(), "ScanPlaceholder");
16904 // early_exit is constructible (guarded elsewhere) but never Some on a live path.
16905 let _guarded = Op::Scan {
16906 n_carries: 1,
16907 n_xs: 0,
16908 bound: 1,
16909 emit: ScanEmit::Final,
16910 early_exit: Some(ScanPredicate),
16911 };
16912 // derive_view_output_layout: Scan is NOT a view op -> Err (handled by the catch-all).
16913 let lay = fuel_ir::Layout::contiguous(s.clone());
16914 let derived = crate::derive_view_output_layout(
16915 &Op::Scan {
16916 n_carries: 1,
16917 n_xs: 0,
16918 bound: 1,
16919 emit: ScanEmit::All,
16920 early_exit: None,
16921 },
16922 &lay,
16923 );
16924 assert!(
16925 derived.is_err(),
16926 "Op::Scan must not be treated as a view op"
16927 );
16928 let _ = scan;
16929 }
16930
16931 #[test]
16932 fn scan_builder_all_and_final_shapes() {
16933 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
16934 use fuel_ir::{DType, Shape};
16935 use std::sync::{Arc, RwLock};
16936 let graph = Arc::new(RwLock::new(Graph::new()));
16937 let cs = Shape::from_dims(&[2]); // carry shape
16938 let ys = Shape::from_dims(&[2]); // per-step y shape
16939 let (carry, hole, new_carry, body_y) = {
16940 let mut g = graph.write().unwrap();
16941 let carry = g.push(Node {
16942 op: Op::Const,
16943 inputs: vec![],
16944 shape: cs.clone(),
16945 dtype: DType::F32,
16946 });
16947 let hole = g.push(Node {
16948 op: Op::ScanPlaceholder {
16949 role: ScanRole::Carry,
16950 index: 0,
16951 },
16952 inputs: vec![],
16953 shape: cs.clone(),
16954 dtype: DType::F32,
16955 });
16956 let new_carry = g.push(Node {
16957 op: Op::MulScalar(2.0),
16958 inputs: vec![hole],
16959 shape: cs.clone(),
16960 dtype: DType::F32,
16961 });
16962 let body_y = g.push(Node {
16963 op: Op::AddScalar(1.0),
16964 inputs: vec![new_carry],
16965 shape: ys.clone(),
16966 dtype: DType::F32,
16967 });
16968 (carry, hole, new_carry, body_y)
16969 };
16970 let t = |id| NodeHandle {
16971 graph: graph.clone(),
16972 id,
16973 }; // same-crate access to private fields
16974 let init = t(carry);
16975 let (nc, by) = (t(new_carry), t(body_y));
16976 let bound = 4usize;
16977
16978 let all = init
16979 .scan(&[], &[], &nc, &by, bound, ScanEmit::All)
16980 .expect("scan All");
16981 assert_eq!(
16982 all.shape().dims(),
16983 &[bound, 2],
16984 "emit=All -> [bound] ++ body_y"
16985 );
16986
16987 // Structural guard (Task-2 review finding): the Op::Scan node's
16988 // inputs MUST end with [.., body_new_carry, body_y] in that
16989 // order — base_map_hash recurses into the last two inputs to
16990 // hash the body, so a reordering would silently hash the wrong
16991 // subgraph. `all` is a View(0) over the producer; its own
16992 // single input is the producer NodeId.
16993 {
16994 let g = graph.read().unwrap();
16995 let producer_id = g.node(all.id()).inputs[0];
16996 let producer_inputs = &g.node(producer_id).inputs;
16997 assert_eq!(
16998 producer_inputs[producer_inputs.len() - 2],
16999 nc.id(),
17000 "Op::Scan inputs[len-2] must be body_new_carry",
17001 );
17002 assert_eq!(
17003 producer_inputs[producer_inputs.len() - 1],
17004 by.id(),
17005 "Op::Scan inputs[len-1] must be body_y",
17006 );
17007 }
17008
17009 let fin = init
17010 .scan(&[], &[], &nc, &by, bound, ScanEmit::Final)
17011 .expect("scan Final");
17012 assert_eq!(fin.shape().dims(), &[2], "emit=Final -> carry shape");
17013 let _ = hole;
17014 }
17015
17016 #[test]
17017 fn scan_builder_rejects_zero_bound() {
17018 use crate::{Graph, Node, NodeHandle, Op, ScanEmit, ScanRole};
17019 use fuel_ir::{DType, Shape};
17020 use std::sync::{Arc, RwLock};
17021 let graph = Arc::new(RwLock::new(Graph::new()));
17022 let cs = Shape::from_dims(&[1]);
17023 let (carry, new_carry, body_y) = {
17024 let mut g = graph.write().unwrap();
17025 let carry = g.push(Node {
17026 op: Op::Const,
17027 inputs: vec![],
17028 shape: cs.clone(),
17029 dtype: DType::F32,
17030 });
17031 let hole = g.push(Node {
17032 op: Op::ScanPlaceholder {
17033 role: ScanRole::Carry,
17034 index: 0,
17035 },
17036 inputs: vec![],
17037 shape: cs.clone(),
17038 dtype: DType::F32,
17039 });
17040 let nc = g.push(Node {
17041 op: Op::MulScalar(2.0),
17042 inputs: vec![hole],
17043 shape: cs.clone(),
17044 dtype: DType::F32,
17045 });
17046 (carry, nc, nc)
17047 };
17048 let t = |id| NodeHandle {
17049 graph: graph.clone(),
17050 id,
17051 };
17052 let r = t(carry).scan(&[], &[], &t(new_carry), &t(body_y), 0, ScanEmit::All);
17053 assert!(r.is_err(), "bound == 0 must be a typed Err, not a panic");
17054 }
17055
17056 /// Task 5 (C6): every "opt-in" classifier/dispatch site over `Op` must
17057 /// treat the new `Op::Scan` / `Op::ScanPlaceholder` variants via its
17058 /// existing safe-conservative wildcard/allow-list — no site should need
17059 /// a bespoke Scan arm in Phase 1. This is a regression LOCK, not a
17060 /// born-red test: every assertion here is expected to pass immediately
17061 /// because the wildcards already exist; a red assertion means that site
17062 /// silently mishandles Scan and needs a conservative arm added.
17063 ///
17064 /// Also confirms reachability: `Op::Scan`'s body lives in its own
17065 /// `inputs` (like `Op::Branch`'s arms), so the ordinary input-closure
17066 /// walk (`topo_order_multi`) sees body nodes for free — no
17067 /// `effective_roots` / `live_set` edit is needed.
17068 #[test]
17069 fn scan_opt_in_sites_are_safe_defaults() {
17070 use crate::{Graph, Node, Op, ScanEmit, ScanRole};
17071 use fuel_ir::{DType, Shape};
17072 let scan = Op::Scan {
17073 n_carries: 1,
17074 n_xs: 0,
17075 bound: 2,
17076 emit: ScanEmit::All,
17077 early_exit: None,
17078 };
17079 let hole = Op::ScanPlaceholder {
17080 role: ScanRole::Carry,
17081 index: 0,
17082 };
17083 // Classifier defaults.
17084 assert_eq!(scan.destructive_input(), None);
17085 assert_eq!(hole.destructive_input(), None);
17086 assert!(!scan.is_view_op());
17087 assert!(!hole.is_view_op());
17088 assert_eq!(
17089 crate::infer_storage_class(&scan),
17090 crate::StorageClass::Transient
17091 );
17092 assert_eq!(crate::jit::op_to_tag(&scan), None);
17093 // Reachability: build a graph with an Op::Scan whose body references a hole;
17094 // the hole (a body node) is reachable from the Scan via inputs, no seeding.
17095 let mut g = Graph::new();
17096 let s = Shape::from_dims(&[1]);
17097 let carry = g.push(Node {
17098 op: Op::Const,
17099 inputs: vec![],
17100 shape: s.clone(),
17101 dtype: DType::F32,
17102 });
17103 let h = g.push(Node {
17104 op: hole.clone(),
17105 inputs: vec![],
17106 shape: s.clone(),
17107 dtype: DType::F32,
17108 });
17109 let nc = g.push(Node {
17110 op: Op::MulScalar(2.0),
17111 inputs: vec![h],
17112 shape: s.clone(),
17113 dtype: DType::F32,
17114 });
17115 let sc = g.push(Node {
17116 op: scan.clone(),
17117 inputs: vec![carry, nc, nc],
17118 shape: Shape::from_dims(&[2, 1]),
17119 dtype: DType::F32,
17120 });
17121 let reachable = crate::topo_order_multi(&g, &[sc]);
17122 assert!(
17123 reachable.contains(&nc) && reachable.contains(&h),
17124 "body nodes must be reachable from Op::Scan via inputs (no effective_roots edit needed)"
17125 );
17126 }
17127}