Skip to main content

fuel_tensor/
lazy.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Phase 6a bridge: a lazy-computation-graph tensor that wraps
3//! [`fuel_graph::NodeHandle`] and presents it through an API compatible
4//! with fuel-core's eager `Tensor`.
5//!
6//! # Purpose
7//!
8//! The Phase 6 architectural pivot moves fuel from eager execution to a
9//! lazy computation graph. End state: `fuel_core::tensor::Tensor` *is* a
10//! `fuel_graph::NodeHandle` and every model in `fuel-transformers` runs
11//! through the lazy backend without per-model porting.
12//!
13//! The bridge is the intermediate stage. [`Tensor`] is a wrapper
14//! around [`fuel_graph::NodeHandle`] that exposes the fuel-core-style
15//! method API (`.add()`, `.mul()`, `.matmul()`, `.relu()`, `.shape()`,
16//! `.to_vec0()`, `.to_vec1()`, ...) so callers can gradually migrate
17//! from eager to lazy one function at a time. Each method appends a
18//! node to the underlying [`fuel_graph::Graph`]; nothing runs until
19//! you call [`Tensor::realize_f32`] or a sibling.
20//!
21//! This is NOT intended as a permanent user-facing type. It's the
22//! scaffolding that makes the final merge incremental: each
23//! `fuel-transformers` model can be converted to `Tensor` in a
24//! separate PR, and once they all compile against the wrapper, the
25//! type alias flips and `fuel_core::tensor::Tensor` becomes the lazy variant.
26//!
27//! # What's here today
28//!
29//! A minimal but real subset: constructors from `Vec<f32>`/`Vec<f64>`
30//! and friends, shape/dtype inspection, the element-wise arithmetic
31//! and unary ops most models use, matmul, softmax, layer_norm,
32//! rms_norm, and realization to a typed `Vec`. Everything routes
33//! through `fuel_graph::NodeHandle` underneath.
34//!
35//! Missing: autograd integration via `fuel_core::Var`, the
36//! `backward()` / `apply_op*` convenience methods, safetensors
37//! loading directly into `Tensor`s, and many of the niche
38//! methods on `fuel_core::tensor::Tensor`. All of these are additive
39//! extensions — they do not require changes to the bridge's
40//! structural design.
41
42use crate::inference_context::InferenceContext;
43use crate::{DType, Device, Shape};
44use fuel_ir::shape::{Dim, Dims};
45use std::sync::Arc;
46
47/// A lazy tensor that builds a `fuel_graph::Graph` as its methods are
48/// called. Cheap to clone — the underlying `fuel_graph::NodeHandle` is a
49/// cheap handle pair `(Rc<RefCell<Graph>>, NodeId)`, so cloning just
50/// bumps the `Rc` and copies the id.
51///
52/// # Tensors are graph-affine — read this before building anything
53///
54/// **Every tensor in one computation must descend from a common root.**
55/// Each `from_*` constructor ([`from_f32`](Self::from_f32),
56/// [`from_bf16`](Self::from_bf16), …) — and [`zeros`](Self::zeros) /
57/// [`full`](Self::full), which delegate to them — **mints a brand-new
58/// graph**. Two independently-constructed tensors therefore live on two
59/// different graphs and **cannot be combined**: every binary op asserts
60/// `"… must live on the same graph"`.
61///
62/// So the obvious shape does *not* work:
63///
64/// ```ignore
65/// let a = Tensor::from_f32(a_data, [2, 3], &device);
66/// let w = Tensor::from_f32(w_data, [3, 2], &device);  // ← a SECOND graph
67/// let y = a.matmul(&w);                                   // ← panics
68/// ```
69///
70/// There are two ways to put a second tensor on an existing graph.
71///
72/// **1. `from_*_on` — pass the graph.** Use this when you have the graph, or
73/// simply want the construction site to say which graph it targets:
74///
75/// ```ignore
76/// let a = Tensor::from_f32(a_data, [2, 3], &device);          // the root
77/// let w = Tensor::from_f32_on(a.graph(), w_data, [3, 2], &device);
78/// let y = a.matmul(&w);                                           // ✓
79/// ```
80///
81/// **2. `const_*_like` — pass an anchor tensor.** Identical effect; use it when
82/// what you have to hand is a sibling tensor rather than the graph:
83///
84/// ```ignore
85/// let a = Tensor::from_f32(a_data, [2, 3], &device);  // the root
86/// let w = a.const_f32_like(w_data, [3, 2].into());        // same graph ✓
87/// let y = a.matmul(&w);                                   // ✓
88/// ```
89///
90/// Every tensor also reports its [`graph_id`](Self::graph_id), so if two do end
91/// up on different graphs the panic names which is which.
92///
93/// In a model this means the **activation tensor is the root and the
94/// weights are `const_*_like` off it**. `const_bf16_like` exists for
95/// precisely the mixed-precision case — f32 activations with bf16 weight
96/// matrices sharing one graph.
97#[derive(Clone, Debug)]
98pub struct Tensor {
99    // `pub(crate)`: the shared decode build path lives in
100    // `crate::persistent_decode` (GAP-029 increment 3) and needs the graph +
101    // NodeId handles to mint Consts and name realize roots. Still private to
102    // the crate — no consumer sees the graph representation.
103    pub(crate) inner: fuel_graph::NodeHandle,
104}
105
106impl Tensor {
107    // ---- constructors ----
108
109    /// Build an `f32` lazy tensor from flat data, a shape, and a device.
110    ///
111    /// `data` takes `impl Into<Arc<[f32]>>` so both `Vec<f32>` and
112    /// `Arc<[f32]>` callers work without conversion. Pass an `Arc`
113    /// when you already have one (e.g. model weights loaded once at
114    /// startup) to avoid any copy.
115    ///
116    /// Phase 7.5 G2: `device` selects where the realized Storage is
117    /// allocated. The graph's storage_map slot for the new node is
118    /// populated and `Op::Const(None)` is emitted — no host-side
119    /// `ConstData` payload rides on the graph node.
120    ///
121    /// # Mints a NEW graph
122    ///
123    /// This starts a **fresh graph**. A tensor built here cannot be combined
124    /// with one built by another `from_*` call — ops assert both operands
125    /// share a graph. To add a second tensor to *this* one's graph, use
126    /// [`const_f32_like`](Self::const_f32_like) (or a sibling
127    /// `const_*_like`). See [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
128    pub fn from_f32(
129        data: impl Into<Arc<[f32]>>,
130        shape: impl Into<Shape>,
131        device: &crate::Device,
132    ) -> fuel_ir::Result<Self> {
133        Ok(Self {
134            inner: fuel_graph::NodeHandle::from_f32(data, shape, device.as_dyn())?,
135        })
136    }
137
138    /// This tensor's graph identity — see [`fuel_graph::GraphId`]. Two tensors
139    /// can be combined **iff** their `graph_id`s match.
140    pub fn graph_id(&self) -> fuel_graph::GraphId {
141        self.inner.graph_id()
142    }
143
144    /// The shared graph this tensor belongs to — hand it to a `from_*_on`
145    /// constructor to build a sibling on the same graph.
146    pub fn graph(&self) -> &fuel_graph::SharedGraph {
147        self.inner.graph()
148    }
149
150    /// Build an `f32` lazy tensor **on the graph you pass in**, not a fresh one.
151    ///
152    /// The non-anchor route for adding a tensor to an existing graph.
153    /// [`from_f32`](Self::from_f32) mints a NEW graph, so two `from_*` tensors
154    /// can never be combined; this puts the new leaf on `graph`.
155    /// [`const_f32_like`](Self::const_f32_like) does the same when what you have
156    /// to hand is a sibling *tensor* rather than the graph itself.
157    ///
158    /// ```ignore
159    /// let a = Tensor::from_f32(a_data, [2, 3], &device);          // root
160    /// let w = Tensor::from_f32_on(a.graph(), w_data, [3, 2], &device);
161    /// let y = a.matmul(&w)?;                                          // ✓
162    /// ```
163    pub fn from_f32_on(
164        graph: &fuel_graph::SharedGraph,
165        data: impl Into<Arc<[f32]>>,
166        shape: impl Into<Shape>,
167        device: &crate::Device,
168    ) -> fuel_ir::Result<Self> {
169        Ok(Self {
170            inner: fuel_graph::NodeHandle::from_f32_on(graph, data, shape, device.as_dyn())?,
171        })
172    }
173
174    /// `f64` sibling of [`from_f32_on`](Self::from_f32_on).
175    pub fn from_f64_on(
176        graph: &fuel_graph::SharedGraph,
177        data: impl Into<Arc<[f64]>>,
178        shape: impl Into<Shape>,
179        device: &crate::Device,
180    ) -> fuel_ir::Result<Self> {
181        Ok(Self {
182            inner: fuel_graph::NodeHandle::from_f64_on(graph, data, shape, device.as_dyn())?,
183        })
184    }
185
186    /// `bf16` sibling of [`from_f32_on`](Self::from_f32_on) — the mixed-precision
187    /// shape (f32 activations, bf16 weights) is this plus
188    /// [`from_f32_on`](Self::from_f32_on) against one shared graph.
189    pub fn from_bf16_on(
190        graph: &fuel_graph::SharedGraph,
191        data: impl Into<Arc<[half::bf16]>>,
192        shape: impl Into<Shape>,
193        device: &crate::Device,
194    ) -> fuel_ir::Result<Self> {
195        Ok(Self {
196            inner: fuel_graph::NodeHandle::from_bf16_on(graph, data, shape, device.as_dyn())?,
197        })
198    }
199
200    /// `f16` sibling of [`from_f32_on`](Self::from_f32_on).
201    pub fn from_f16_on(
202        graph: &fuel_graph::SharedGraph,
203        data: impl Into<Arc<[half::f16]>>,
204        shape: impl Into<Shape>,
205        device: &crate::Device,
206    ) -> fuel_ir::Result<Self> {
207        Ok(Self {
208            inner: fuel_graph::NodeHandle::from_f16_on(graph, data, shape, device.as_dyn())?,
209        })
210    }
211
212    /// `u32` sibling of [`from_f32_on`](Self::from_f32_on) — index tensors built
213    /// straight onto the graph they will be gathered on.
214    pub fn from_u32_on(
215        graph: &fuel_graph::SharedGraph,
216        data: impl Into<Arc<[u32]>>,
217        shape: impl Into<Shape>,
218        device: &crate::Device,
219    ) -> fuel_ir::Result<Self> {
220        Ok(Self {
221            inner: fuel_graph::NodeHandle::from_u32_on(graph, data, shape, device.as_dyn())?,
222        })
223    }
224
225    /// Build an `f64` lazy tensor. `device` selects where the realized
226    /// Storage is allocated.
227    ///
228    /// **Mints a NEW graph** — to build on an existing tensor's graph use
229    /// [`const_f64_like`](Self::const_f64_like). See
230    /// [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
231    pub fn from_f64(
232        data: impl Into<Arc<[f64]>>,
233        shape: impl Into<Shape>,
234        device: &crate::Device,
235    ) -> fuel_ir::Result<Self> {
236        Ok(Self {
237            inner: fuel_graph::NodeHandle::from_f64(data, shape, device.as_dyn())?,
238        })
239    }
240
241    /// Build a `bf16` lazy tensor. `device` selects where the realized
242    /// Storage is allocated.
243    ///
244    /// **Mints a NEW graph.** For the common case — bf16 weights alongside
245    /// f32 activations — build the weights with
246    /// [`const_bf16_like`](Self::const_bf16_like) off the activation tensor
247    /// so both share one graph. See
248    /// [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
249    pub fn from_bf16(
250        data: impl Into<Arc<[half::bf16]>>,
251        shape: impl Into<Shape>,
252        device: &crate::Device,
253    ) -> fuel_ir::Result<Self> {
254        Ok(Self {
255            inner: fuel_graph::NodeHandle::from_bf16(data, shape, device.as_dyn())?,
256        })
257    }
258
259    /// Build an `f16` lazy tensor. `device` selects where the realized
260    /// Storage is allocated.
261    pub fn from_f16(
262        data: impl Into<Arc<[half::f16]>>,
263        shape: impl Into<Shape>,
264        device: &crate::Device,
265    ) -> fuel_ir::Result<Self> {
266        Ok(Self {
267            inner: fuel_graph::NodeHandle::from_f16(data, shape, device.as_dyn())?,
268        })
269    }
270
271    /// Build a `u32` (index) lazy tensor. Used for gather/scatter/
272    /// index_select and similar discrete operations. `device` selects
273    /// where the realized Storage is allocated.
274    pub fn from_u32(
275        data: impl Into<Arc<[u32]>>,
276        shape: impl Into<Shape>,
277        device: &crate::Device,
278    ) -> fuel_ir::Result<Self> {
279        Ok(Self {
280            inner: fuel_graph::NodeHandle::from_u32(data, shape, device.as_dyn())?,
281        })
282    }
283
284    /// Build a const tensor of the same dtype and graph as `self`.
285    /// This is the most convenient way to attach new input data to an
286    /// existing computation.
287    ///
288    /// Phase 7.5 G2: the realized Storage is allocated on the device
289    /// derived from `self`'s graph (any existing slot's device — the
290    /// graph always has at least one slot-bearing leaf by the time
291    /// const_*_like is called). Use [`Self::from_f32`] with an explicit
292    /// `&Device` when you need a const on a different device than
293    /// `self`.
294    pub fn const_f32_like(
295        &self,
296        data: impl Into<Arc<[f32]>>,
297        shape: impl Into<Shape>,
298    ) -> std::result::Result<Self, fuel_ir::Error> {
299        Ok(Self {
300            inner: self.inner.const_f32_like(data, shape)?,
301        })
302    }
303
304    /// Build a const f16 tensor on the same graph as `self`.
305    pub fn const_f16_like(
306        &self,
307        data: impl Into<Arc<[half::f16]>>,
308        shape: impl Into<Shape>,
309    ) -> std::result::Result<Self, fuel_ir::Error> {
310        Ok(Self {
311            inner: self.inner.const_f16_like(data, shape)?,
312        })
313    }
314
315    /// Build a const bf16 tensor on the same graph as `self`. Used for
316    /// bf16-on-device weights in the mixed-precision matmul path —
317    /// activations stay f32, weight matrices live as bf16.
318    pub fn const_bf16_like(
319        &self,
320        data: impl Into<Arc<[half::bf16]>>,
321        shape: impl Into<Shape>,
322    ) -> std::result::Result<Self, fuel_ir::Error> {
323        Ok(Self {
324            inner: self.inner.const_bf16_like(data, shape)?,
325        })
326    }
327
328    /// Build a const tensor on the same graph as `self`, holding
329    /// `data`'s values encoded in `dtype`. Only `F32` (identity copy)
330    /// and `BF16` (host `half::bf16::from_f32` conversion) are
331    /// supported today — the two activation dtypes the BF16-throughout
332    /// decode seam (Phase D increment A: LlamaModel's cached decode
333    /// path) threads through small per-model host constants (norm
334    /// gains, biases, the causal mask) that must track the running
335    /// activation dtype instead of being hardcoded f32. Any other
336    /// dtype is a caller bug (not a data-dependent runtime
337    /// possibility), so it surfaces a typed error rather than silently
338    /// emitting wrong bytes.
339    pub fn const_like_dtype(
340        &self,
341        data: &[f32],
342        shape: impl Into<Shape>,
343        dtype: fuel_ir::DType,
344    ) -> std::result::Result<Self, fuel_ir::Error> {
345        match dtype {
346            fuel_ir::DType::F32 => self.const_f32_like(data.to_vec(), shape),
347            fuel_ir::DType::BF16 => {
348                let converted: Vec<half::bf16> =
349                    data.iter().map(|&v| half::bf16::from_f32(v)).collect();
350                self.const_bf16_like(converted, shape)
351            }
352            other => Err(fuel_ir::Error::Msg(format!(
353                "const_like_dtype: unsupported activation dtype {other:?} \
354                 (expected F32 or BF16)",
355            ))
356            .bt()),
357        }
358    }
359
360    /// Unwrap the underlying `fuel_graph::NodeHandle`. Used by callers that
361    /// need to drop down to the graph layer for operations the bridge
362    /// does not yet expose.
363    pub fn into_graph_tensor(self) -> fuel_graph::NodeHandle {
364        self.inner
365    }
366
367    /// Borrow the underlying `fuel_graph::NodeHandle`.
368    pub fn graph_tensor(&self) -> &fuel_graph::NodeHandle {
369        &self.inner
370    }
371
372    /// Wrap an existing `fuel_graph::NodeHandle` in a `Tensor`. Useful
373    /// when you have code that already builds a graph and want to
374    /// present its outputs through this API.
375    pub fn from_graph_tensor(t: fuel_graph::NodeHandle) -> Self {
376        Self { inner: t }
377    }
378
379    // ---- shape / dtype inspection ----
380
381    /// The tensor's shape.
382    pub fn shape(&self) -> Shape {
383        self.inner.shape()
384    }
385
386    /// The tensor's dtype.
387    pub fn dtype(&self) -> DType {
388        self.inner.dtype()
389    }
390
391    /// This tensor's underlying graph handle. Exposed for call sites
392    /// outside this module that need to drive
393    /// [`InferenceContext`](crate::inference_context::InferenceContext)
394    /// directly — e.g. a persistent cross-graph decode cache implemented
395    /// in a sibling model module (`lazy_deepseek2.rs`'s
396    /// `forward_with_latent_kv_context`). Most callers should prefer
397    /// [`Self::realize_f32`] and friends instead.
398    pub fn graph_handle(&self) -> &fuel_graph::SharedGraph {
399        self.inner.graph()
400    }
401
402    /// This tensor's `NodeId` on its graph. See [`Self::graph_handle`].
403    pub fn node_id(&self) -> fuel_graph::NodeId {
404        self.inner.id()
405    }
406
407    /// The tensor's rank (number of dimensions).
408    pub fn rank(&self) -> usize {
409        self.inner.shape().dims().len()
410    }
411
412    /// Total element count.
413    pub fn elem_count(&self) -> usize {
414        self.inner.shape().elem_count()
415    }
416
417    /// PyTorch-convention alias of [`Self::elem_count`].
418    pub fn numel(&self) -> usize {
419        self.elem_count()
420    }
421
422    /// Size of the tensor along dimension `dim`. Returns a typed error
423    /// rather than panicking on out-of-range — matches eager's
424    /// `crate::Tensor::dim` signature.
425    pub fn dim<D: Dim>(&self, dim: D) -> std::result::Result<usize, fuel_ir::Error> {
426        let shape = self.inner.shape();
427        let dim = dim.to_index(&shape, "dim")?;
428        Ok(shape.dims()[dim])
429    }
430
431    // ---- arithmetic (element-wise, strict shape) ----
432
433    /// Element-wise addition. Shapes and dtypes must match — mismatches
434    /// surface as typed errors at build time.
435    pub fn add(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
436        self.check_strict_binary("add", other)?;
437        Ok(Self {
438            inner: self.inner.add(&other.inner),
439        })
440    }
441
442    /// Element-wise subtraction.
443    pub fn sub(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
444        self.check_strict_binary("sub", other)?;
445        Ok(Self {
446            inner: self.inner.sub(&other.inner),
447        })
448    }
449
450    /// Element-wise multiplication.
451    pub fn mul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
452        self.check_strict_binary("mul", other)?;
453        Ok(Self {
454            inner: self.inner.mul(&other.inner),
455        })
456    }
457
458    /// Element-wise division.
459    pub fn div(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
460        self.check_strict_binary("div", other)?;
461        Ok(Self {
462            inner: self.inner.div(&other.inner),
463        })
464    }
465
466    /// Element-wise maximum.
467    pub fn maximum(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
468        self.check_strict_binary("maximum", other)?;
469        Ok(Self {
470            inner: self.inner.maximum(&other.inner),
471        })
472    }
473
474    /// Element-wise minimum.
475    pub fn minimum(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
476        self.check_strict_binary("minimum", other)?;
477        Ok(Self {
478            inner: self.inner.minimum(&other.inner),
479        })
480    }
481
482    /// IEEE-754 NaN-**suppressing** maximum (`fmax_ieee`, KISS-OPS §6.15-0001) —
483    /// DISTINCT from [`maximum`](Self::maximum) (NaN-propagating). Resolves through
484    /// the spec-pinned §6.13 decomposition; does not substitute `maximum`. GAP-048.
485    pub fn fmax_ieee(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
486        self.check_strict_binary("fmax_ieee", other)?;
487        Ok(Self {
488            inner: self.inner.fmax_ieee(&other.inner),
489        })
490    }
491
492    /// IEEE-754 NaN-**suppressing** minimum (`fmin_ieee`, KISS-OPS §6.15-0001) —
493    /// DISTINCT from [`minimum`](Self::minimum) (NaN-propagating). GAP-048.
494    pub fn fmin_ieee(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
495        self.check_strict_binary("fmin_ieee", other)?;
496        Ok(Self {
497            inner: self.inner.fmin_ieee(&other.inner),
498        })
499    }
500
501    /// Truncated remainder (`rem_trunc`, KISS-OPS §6.15-0003) — sign of the
502    /// DIVIDEND (C99 `fmod`), DISTINCT from [`rem`](Self::rem) (floored, sign of
503    /// the divisor). Resolves through the spec-pinned §6.13 decomposition. GAP-048.
504    pub fn rem_trunc(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
505        self.check_strict_binary("rem_trunc", other)?;
506        Ok(Self {
507            inner: self.inner.rem_trunc(&other.inner),
508        })
509    }
510
511    /// Round toward zero (`trunc`, KISS-OPS §6.3 floor op; GAP-300). Fuel's own
512    /// expansion (`q>=0 ? floor(q) : ceil(q)`), NOT spec-pinned — its ±0/NaN/inf
513    /// correctness is Fuel's liability. Integer dtypes are identity.
514    pub fn trunc(&self) -> Self {
515        Self {
516            inner: self.inner.trunc(),
517        }
518    }
519
520    /// Element-wise equality (`self == other`) producing a `U8` mask:
521    /// `1` where equal, `0` otherwise. Both operands must share dtype
522    /// and shape. NaN follows IEEE-754 (`NaN == NaN` is false). The
523    /// resulting tensor's dtype is `DType::U8`. Non-differentiable.
524    pub fn eq(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
525        self.check_strict_binary("eq", other)?;
526        Ok(Self {
527            inner: self.inner.eq(&other.inner),
528        })
529    }
530
531    /// Element-wise inequality (`self != other`) producing a `U8`
532    /// mask. NaN follows IEEE-754 (`NaN != NaN` is true → `1`).
533    /// Non-differentiable.
534    pub fn ne(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
535        self.check_strict_binary("ne", other)?;
536        Ok(Self {
537            inner: self.inner.ne(&other.inner),
538        })
539    }
540
541    /// Element-wise strictly-less (`self < other`) producing a `U8`
542    /// mask. NaN-on-either-side is `0` (IEEE-754 unordered).
543    /// Non-differentiable.
544    pub fn lt(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
545        self.check_strict_binary("lt", other)?;
546        Ok(Self {
547            inner: self.inner.lt(&other.inner),
548        })
549    }
550
551    /// Element-wise less-or-equal (`self <= other`) producing a `U8`
552    /// mask. NaN-on-either-side is `0`. Non-differentiable.
553    pub fn le(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
554        self.check_strict_binary("le", other)?;
555        Ok(Self {
556            inner: self.inner.le(&other.inner),
557        })
558    }
559
560    /// Element-wise strictly-greater (`self > other`) producing a
561    /// `U8` mask. NaN-on-either-side is `0`. Non-differentiable.
562    pub fn gt(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
563        self.check_strict_binary("gt", other)?;
564        Ok(Self {
565            inner: self.inner.gt(&other.inner),
566        })
567    }
568
569    /// Element-wise greater-or-equal (`self >= other`) producing a
570    /// `U8` mask. NaN-on-either-side is `0`. Non-differentiable.
571    /// Final variant of the comparison family (`eq` / `ne` / `lt` /
572    /// `le` / `gt` / `ge`).
573    pub fn ge(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
574        self.check_strict_binary("ge", other)?;
575        Ok(Self {
576            inner: self.inner.ge(&other.inner),
577        })
578    }
579
580    /// Ternary select (typically used to consume a comparison-op
581    /// mask): `result[i] = if self[i] { a[i] } else { b[i] }`.
582    /// `self` is the cond mask (must be `DType::Bool`, GAP-168(c)); `a` and `b`
583    /// share dtype + shape with `self`. Output dtype matches `a`/`b`,
584    /// shape matches `self`.
585    ///
586    /// Differentiable through `a` and `b` only.
587    pub fn where_cond(&self, a: &Self, b: &Self) -> std::result::Result<Self, fuel_ir::Error> {
588        // GAP-168(c): the cond mask is Bool, matching `masked_fill` and the
589        // `fixed(BOOL)` comparison contracts. The DOC above already said Bool
590        // while this guard still required U8 — prose and check disagreeing, with
591        // the prose right; every comparison feeds `where_cond`, so 22 model tests
592        // failed on it. Cast a numeric mask explicitly (the cast is deliberately
593        // NOT implicit — a silent coercion is what the Bool dtype exists to stop).
594        if self.inner.dtype() != fuel_ir::DType::Bool {
595            return Err(fuel_ir::Error::Msg(format!(
596                "where_cond: cond mask must be Bool, got {:?} — cast a numeric \
597                 mask to Bool explicitly (GAP-168(c))",
598                self.inner.dtype(),
599            ))
600            .bt());
601        }
602        if a.inner.dtype() != b.inner.dtype() {
603            return Err(fuel_ir::Error::Msg(format!(
604                "where_cond: branches must share dtype, got a={:?} b={:?}",
605                a.inner.dtype(),
606                b.inner.dtype(),
607            ))
608            .bt());
609        }
610        let cond_dims = self.inner.shape();
611        let a_dims = a.inner.shape();
612        let b_dims = b.inner.shape();
613        if a_dims.dims() != cond_dims.dims() || b_dims.dims() != cond_dims.dims() {
614            return Err(fuel_ir::Error::Msg(format!(
615                "where_cond: shapes must match cond, got cond={:?} a={:?} b={:?}",
616                cond_dims.dims(),
617                a_dims.dims(),
618                b_dims.dims(),
619            ))
620            .bt());
621        }
622        Ok(Self {
623            inner: self.inner.where_cond(&a.inner, &b.inner),
624        })
625    }
626
627    // ---- broadcast-aware arithmetic ----
628
629    /// Element-wise addition with auto-broadcasting.
630    pub fn broadcast_add(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
631        self.check_broadcast_binary("broadcast_add", other)?;
632        Ok(Self {
633            inner: self.inner.broadcast_add(&other.inner),
634        })
635    }
636
637    /// Element-wise subtraction with auto-broadcasting.
638    pub fn broadcast_sub(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
639        self.check_broadcast_binary("broadcast_sub", other)?;
640        Ok(Self {
641            inner: self.inner.broadcast_sub(&other.inner),
642        })
643    }
644
645    /// Element-wise multiplication with auto-broadcasting.
646    pub fn broadcast_mul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
647        self.check_broadcast_binary("broadcast_mul", other)?;
648        Ok(Self {
649            inner: self.inner.broadcast_mul(&other.inner),
650        })
651    }
652
653    /// Element-wise division with auto-broadcasting.
654    pub fn broadcast_div(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
655        self.check_broadcast_binary("broadcast_div", other)?;
656        Ok(Self {
657            inner: self.inner.broadcast_div(&other.inner),
658        })
659    }
660
661    fn check_strict_binary(
662        &self,
663        name: &'static str,
664        other: &Self,
665    ) -> std::result::Result<(), fuel_ir::Error> {
666        if self.inner.dtype() != other.inner.dtype() {
667            return Err(fuel_ir::Error::Msg(format!(
668                "{name}: dtype mismatch lhs={:?} rhs={:?}",
669                self.inner.dtype(),
670                other.inner.dtype(),
671            ))
672            .bt());
673        }
674        let a_shape = self.inner.shape();
675        let b_shape = other.inner.shape();
676        if a_shape.dims() != b_shape.dims() {
677            return Err(fuel_ir::Error::Msg(format!(
678                "{name}: shape mismatch lhs={:?} rhs={:?}",
679                a_shape.dims(),
680                b_shape.dims(),
681            ))
682            .bt());
683        }
684        Ok(())
685    }
686
687    fn check_broadcast_binary(
688        &self,
689        name: &'static str,
690        other: &Self,
691    ) -> std::result::Result<(), fuel_ir::Error> {
692        if self.inner.dtype() != other.inner.dtype() {
693            return Err(fuel_ir::Error::Msg(format!(
694                "{name}: dtype mismatch lhs={:?} rhs={:?}",
695                self.inner.dtype(),
696                other.inner.dtype(),
697            ))
698            .bt());
699        }
700        let a_shape = self.inner.shape();
701        let b_shape = other.inner.shape();
702        let a_dims = a_shape.dims();
703        let b_dims = b_shape.dims();
704        // Standard NumPy-style broadcast compatibility: from the right,
705        // each pair of dims must be equal, or one of them must be 1.
706        let rank = a_dims.len().max(b_dims.len());
707        for i in 0..rank {
708            let ad = a_dims
709                .get(a_dims.len().wrapping_sub(1 + i))
710                .copied()
711                .unwrap_or(1);
712            let bd = b_dims
713                .get(b_dims.len().wrapping_sub(1 + i))
714                .copied()
715                .unwrap_or(1);
716            if ad != bd && ad != 1 && bd != 1 {
717                return Err(fuel_ir::Error::Msg(format!(
718                    "{name}: shapes {:?} and {:?} are not broadcast-compatible",
719                    a_dims, b_dims,
720                ))
721                .bt());
722            }
723        }
724        Ok(())
725    }
726
727    // ---- unary ----
728
729    /// Element-wise negation.
730    pub fn neg(&self) -> Self {
731        Self {
732            inner: self.inner.neg(),
733        }
734    }
735
736    /// Element-wise square.
737    pub fn sqr(&self) -> Self {
738        Self {
739            inner: self.inner.sqr(),
740        }
741    }
742
743    /// Element-wise square root.
744    pub fn sqrt(&self) -> Self {
745        Self {
746            inner: self.inner.sqrt(),
747        }
748    }
749
750    /// Element-wise exponential.
751    pub fn exp(&self) -> Self {
752        Self {
753            inner: self.inner.exp(),
754        }
755    }
756
757    /// Element-wise natural logarithm.
758    pub fn log(&self) -> Self {
759        Self {
760            inner: self.inner.log(),
761        }
762    }
763
764    /// Rectified linear unit.
765    pub fn relu(&self) -> Self {
766        Self {
767            inner: self.inner.relu(),
768        }
769    }
770
771    /// SiLU / Swish activation.
772    pub fn silu(&self) -> Self {
773        Self {
774            inner: self.inner.silu(),
775        }
776    }
777
778    /// GELU activation (tanh approximation).
779    pub fn gelu_tanh(&self) -> Self {
780        Self {
781            inner: self.inner.gelu_tanh(),
782        }
783    }
784
785    /// Logistic sigmoid.
786    pub fn sigmoid(&self) -> Self {
787        Self {
788            inner: self.inner.sigmoid(),
789        }
790    }
791
792    /// Hyperbolic tangent.
793    pub fn tanh(&self) -> Self {
794        Self {
795            inner: self.inner.tanh(),
796        }
797    }
798
799    /// Element-wise sine.
800    pub fn sin(&self) -> Self {
801        Self {
802            inner: self.inner.sin(),
803        }
804    }
805
806    /// Element-wise cosine.
807    pub fn cos(&self) -> Self {
808        Self {
809            inner: self.inner.cos(),
810        }
811    }
812
813    /// Heaviside step (`1` where `x > 0`, else `0`) — the derivative
814    /// of [`Self::relu`].
815    pub fn step(&self) -> Self {
816        Self {
817            inner: self.inner.step(),
818        }
819    }
820
821    /// Element-wise reciprocal (`1 / x`).
822    pub fn recip(&self) -> Self {
823        Self {
824            inner: self.inner.recip(),
825        }
826    }
827
828    /// Element-wise absolute value (`|x|`).
829    pub fn abs(&self) -> Self {
830        Self {
831            inner: self.inner.abs(),
832        }
833    }
834
835    /// Element-wise floor (`⌊x⌋`). Same dtype as input.
836    /// Backward is silently zero (non-differentiable almost everywhere).
837    pub fn floor(&self) -> Self {
838        Self {
839            inner: self.inner.floor(),
840        }
841    }
842
843    /// Element-wise ceiling (`⌈x⌉`). Same dtype as input.
844    /// Backward is silently zero.
845    pub fn ceil(&self) -> Self {
846        Self {
847            inner: self.inner.ceil(),
848        }
849    }
850
851    /// Element-wise round-to-nearest with **banker's rounding**
852    /// (round-half-to-even, IEEE 754 roundeven). Backward is silently
853    /// zero. Differs from C99 `round()` at exact halves: 0.5 → 0,
854    /// 2.5 → 2, etc.
855    pub fn round(&self) -> Self {
856        Self {
857            inner: self.inner.round(),
858        }
859    }
860
861    /// Element-wise sign (`-1` / `0` / `1`); `sign(0) = 0` by
862    /// subgradient convention. Same dtype as input. Backward is
863    /// silently zero.
864    pub fn sign(&self) -> Self {
865        Self {
866            inner: self.inner.sign(),
867        }
868    }
869
870    /// Element-wise Gauss error function (`erf(x)`). Same dtype as
871    /// input. Differentiable: `d/dx erf(x) = (2/√π) * exp(-x²)`.
872    pub fn erf(&self) -> Self {
873        Self {
874            inner: self.inner.erf(),
875        }
876    }
877
878    /// GELU activation, **exact erf form** (`0.5 * x * (1 + erf(x/√2))`).
879    /// Distinct from [`Self::gelu_tanh`] (tanh approximation). Same dtype
880    /// as input. Differentiable.
881    pub fn gelu(&self) -> Self {
882        Self {
883            inner: self.inner.gelu(),
884        }
885    }
886
887    /// Element-wise binary power `pow(self, other)` (real exponent).
888    /// Both operands must share dtype + shape. Distinct from
889    /// [`Self::powi`] (scalar `i32` exponent). Differentiable.
890    /// **Returns `Result`**: dtype/shape mismatch surfaces as a
891    /// typed error.
892    pub fn pow(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
893        Ok(Self {
894            inner: self.inner.pow(&other.inner)?,
895        })
896    }
897
898    /// Element-wise reciprocal square root (`1 / sqrt(x)`). Same
899    /// dtype as input. One op rather than `sqrt(x).recip()` — saves
900    /// a kernel launch and matches the RMSNorm shape. Differentiable.
901    pub fn rsqrt(&self) -> Self {
902        Self {
903            inner: self.inner.rsqrt(),
904        }
905    }
906
907    /// Element-wise remainder, **PyTorch convention**:
908    /// `a - floor(a/b) * b` (sign of result matches divisor; matches
909    /// `torch.remainder`, not C99 fmod). Differentiable through `a`
910    /// and `b`. **Returns `Result`**: dtype/shape mismatch surfaces
911    /// as a typed error.
912    pub fn rem(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
913        Ok(Self {
914            inner: self.inner.rem(&other.inner)?,
915        })
916    }
917
918    /// Reverse element order along `dim`. Materializing op (real
919    /// byte shuffle). Differentiable; backward is itself.
920    /// Accepts any [`Dim`] (`usize`, `D::Minus1`, etc.).
921    pub fn flip<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
922        let shape = self.inner.shape();
923        let dim = dim.to_index(&shape, "flip")?;
924        Ok(Self {
925            inner: self.inner.flip(dim)?,
926        })
927    }
928
929    /// Cyclic shift along `dim` by `shift` positions (positive →
930    /// higher indices, wrapping). Differentiable; backward is
931    /// `roll(dim, -shift)`.
932    pub fn roll<D: Dim>(&self, dim: D, shift: i64) -> std::result::Result<Self, fuel_ir::Error> {
933        let shape = self.inner.shape();
934        let dim = dim.to_index(&shape, "roll")?;
935        Ok(Self {
936            inner: self.inner.roll(dim, shift)?,
937        })
938    }
939
940    /// Running cumulative sum along `dim`. Same shape as input.
941    /// Differentiable; backward is reverse cumsum (`flip → cumsum
942    /// → flip`).
943    pub fn cumsum<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
944        let shape = self.inner.shape();
945        let dim = dim.to_index(&shape, "cumsum")?;
946        Ok(Self {
947            inner: self.inner.cumsum(dim)?,
948        })
949    }
950
951    /// Multi-dim Pad: `padding[i] = (before, after)` for axis `i`,
952    /// length must equal tensor rank. Output shape:
953    /// `out[i] = in[i] + padding[i].0 + padding[i].1`. Only Constant
954    /// mode is implemented; Reflect / Replicate exist as enum stubs
955    /// that error at realize time. Differentiable for Constant.
956    /// **Returns `Result`**: rank mismatch surfaces as a typed error.
957    pub fn pad(
958        &self,
959        padding: Vec<(usize, usize)>,
960        mode: fuel_graph::PadMode,
961        value: f64,
962    ) -> std::result::Result<Self, fuel_ir::Error> {
963        Ok(Self {
964            inner: self.inner.pad(padding, mode, value)?,
965        })
966    }
967
968    /// Element-wise integer power (`x.powi(n)`).
969    pub fn powi(&self, n: i32) -> Self {
970        Self {
971            inner: self.inner.powi(n),
972        }
973    }
974
975    // ---- linear algebra & shape ----
976
977    /// N-D batched matrix multiply with automatic rank-2 broadcasting.
978    /// Shape incompatibility (rank < 2 or contracting-dim mismatch)
979    /// surfaces as a typed error at build time.
980    pub fn matmul(&self, other: &Self) -> std::result::Result<Self, fuel_ir::Error> {
981        let a_dims = self.inner.shape().dims().to_vec();
982        let b_dims = other.inner.shape().dims().to_vec();
983        if a_dims.len() < 2 || b_dims.len() < 2 {
984            return Err(fuel_ir::Error::Msg(format!(
985                "matmul: both operands must be rank >= 2, got lhs={a_dims:?} rhs={b_dims:?}",
986            ))
987            .bt());
988        }
989        let a_k = a_dims[a_dims.len() - 1];
990        let b_k = b_dims[b_dims.len() - 2];
991        if a_k != b_k {
992            return Err(fuel_ir::Error::Msg(format!(
993                "matmul: contracting dim mismatch lhs[..., M, {a_k}] vs rhs[..., {b_k}, N]",
994            ))
995            .bt());
996        }
997        Ok(Self {
998            inner: self.inner.matmul(&other.inner),
999        })
1000    }
1001
1002    /// Data-determined-M matmul (sparse-MoE / capacity-buffer): like
1003    /// [`Self::matmul`], but computes only `row_count` rows of the
1004    /// `self.shape[-2]`-row capacity buffer, the rest left zeroed.
1005    /// `row_count` is a [`fuel_ir::DynScalar`] resolved at compile if
1006    /// input-determined, else at execute from the producer-bound `SymEnv`
1007    /// (e.g. `Op::NonZeroIndices`'s per-expert count). F32-only today.
1008    pub fn matmul_dyn_m(
1009        &self,
1010        other: &Self,
1011        row_count: fuel_ir::DynScalar,
1012    ) -> std::result::Result<Self, fuel_ir::Error> {
1013        let a_dims = self.inner.shape().dims().to_vec();
1014        let b_dims = other.inner.shape().dims().to_vec();
1015        if a_dims.len() < 2 || b_dims.len() < 2 {
1016            return Err(fuel_ir::Error::Msg(format!(
1017                "matmul_dyn_m: both operands must be rank >= 2, got lhs={a_dims:?} rhs={b_dims:?}",
1018            ))
1019            .bt());
1020        }
1021        let a_k = a_dims[a_dims.len() - 1];
1022        let b_k = b_dims[b_dims.len() - 2];
1023        if a_k != b_k {
1024            return Err(fuel_ir::Error::Msg(format!(
1025                "matmul_dyn_m: contracting dim mismatch lhs[..., M, {a_k}] vs rhs[..., {b_k}, N]",
1026            ))
1027            .bt());
1028        }
1029        Ok(Self {
1030            inner: self.inner.matmul_dyn_m(&other.inner, row_count),
1031        })
1032    }
1033
1034    /// Quantized matmul: `C = self @ dequant(W_Q)`. See
1035    /// [`fuel_graph::NodeHandle::qmatmul`] for details. The weight bytes
1036    /// tensor must be a flat U32 const holding the raw Q-block byte
1037    /// stream (length = n_bytes / 4).
1038    ///
1039    /// Dtype / rank / k / block-alignment / byte-count mismatches
1040    /// surface as typed errors at build time rather than panicking
1041    /// inside the inner `fuel_graph` call.
1042    pub fn qmatmul(
1043        &self,
1044        weight_bytes: &Self,
1045        quant_type: fuel_graph::QuantType,
1046        k: usize,
1047        n: usize,
1048    ) -> std::result::Result<Self, fuel_ir::Error> {
1049        if self.inner.dtype() != fuel_ir::DType::F32 {
1050            return Err(fuel_ir::Error::Msg(format!(
1051                "qmatmul: activations must be F32, got {:?}",
1052                self.inner.dtype(),
1053            ))
1054            .bt());
1055        }
1056        if weight_bytes.inner.dtype() != fuel_ir::DType::U32 {
1057            return Err(fuel_ir::Error::Msg(format!(
1058                "qmatmul: weight_bytes must be U32 (raw block bytes reinterpreted), got {:?}",
1059                weight_bytes.inner.dtype(),
1060            ))
1061            .bt());
1062        }
1063        let a_shape = self.inner.shape();
1064        let a_dims = a_shape.dims();
1065        if a_dims.len() < 2 {
1066            return Err(fuel_ir::Error::Msg(format!(
1067                "qmatmul: activations must be rank >= 2, got {a_dims:?}",
1068            ))
1069            .bt());
1070        }
1071        if a_dims[a_dims.len() - 1] != k {
1072            return Err(fuel_ir::Error::Msg(format!(
1073                "qmatmul: last dim of activations ({}) must equal k ({k})",
1074                a_dims[a_dims.len() - 1],
1075            ))
1076            .bt());
1077        }
1078        let block_size = quant_type.elements_per_block();
1079        if !k.is_multiple_of(block_size) {
1080            return Err(fuel_ir::Error::Msg(format!(
1081                "qmatmul: k={k} must be a multiple of {quant_type:?}'s block size ({block_size})",
1082            ))
1083            .bt());
1084        }
1085        let expected_bytes = n * (k / block_size) * quant_type.bytes_per_block();
1086        let expected_u32_elems = expected_bytes.div_ceil(4);
1087        let actual_elems = weight_bytes.inner.shape().elem_count();
1088        if actual_elems != expected_u32_elems {
1089            return Err(fuel_ir::Error::Msg(format!(
1090                "qmatmul: weight_bytes has {actual_elems} u32 elements, expected {expected_u32_elems} for N={n}, K={k}, {quant_type:?}",
1091            )).bt());
1092        }
1093        Ok(Self {
1094            inner: self.inner.qmatmul(&weight_bytes.inner, quant_type, k, n),
1095        })
1096    }
1097
1098    /// Transpose the last two dims. Returns a typed error on rank < 2
1099    /// rather than panicking — build-time validation surfaces a useful
1100    /// diagnostic.
1101    pub fn transpose(&self) -> std::result::Result<Self, fuel_ir::Error> {
1102        Ok(Self {
1103            inner: self.inner.try_transpose()?,
1104        })
1105    }
1106
1107    /// Permute axes by the given ordering. Accepts any [`Dims`]
1108    /// implementer — `(0, 2, 1)`, `[0, 2, 1]`, `&[0, 2, 1]`, etc.
1109    /// Validates rank match + dim bounds + duplicate check at build time.
1110    pub fn permute<D: Dims>(&self, axes: D) -> std::result::Result<Self, fuel_ir::Error> {
1111        let shape = self.inner.shape();
1112        let axes = axes.to_indexes(&shape, "permute")?;
1113        Ok(Self {
1114            inner: self.inner.try_permute(&axes)?,
1115        })
1116    }
1117
1118    /// Reshape to a new shape with matching element count.
1119    /// Element-count mismatch surfaces as a typed error at build time.
1120    pub fn reshape(&self, shape: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
1121        Ok(Self {
1122            inner: self.inner.try_reshape(shape)?,
1123        })
1124    }
1125
1126    /// Drop the size-1 dimension at position `dim` (range `0..rank`).
1127    /// Metadata-only view; bytes shared with `self`. **Returns
1128    /// `Result`** rather than panicking — bad `dim` (out of bounds
1129    /// or `shape[dim] != 1`) surfaces as a typed error.
1130    ///
1131    /// Accepts any [`Dim`] implementer — `usize`, `D::Minus1`, `D::Minus2`,
1132    /// `D::Minus(n)`.
1133    pub fn squeeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1134        let shape = self.inner.shape();
1135        let dim = dim.to_index(&shape, "squeeze")?;
1136        Ok(Self {
1137            inner: self.inner.squeeze(dim)?,
1138        })
1139    }
1140
1141    /// Broadcast to a larger shape. Shape-incompatibility surfaces as a
1142    /// typed error at build time.
1143    pub fn broadcast_to(
1144        &self,
1145        shape: impl Into<Shape>,
1146    ) -> std::result::Result<Self, fuel_ir::Error> {
1147        Ok(Self {
1148            inner: self.inner.try_broadcast_to(shape)?,
1149        })
1150    }
1151
1152    /// Apply LayerNorm along the last dim with an affine
1153    /// `gain · x + bias` post-step. Both `gain` and `bias` are
1154    /// length-`hidden` vectors materialized fresh on `self`'s
1155    /// graph; they're broadcast across all leading dims of the
1156    /// output.
1157    ///
1158    /// Equivalent to the per-port `apply_layer_norm(x, ln, hidden,
1159    /// eps)` helpers that several ports inlined — promoted here so
1160    /// the call sites stop drifting.
1161    pub fn layer_norm_affine(
1162        &self,
1163        gain: std::sync::Arc<[f32]>,
1164        bias: std::sync::Arc<[f32]>,
1165        eps: f64,
1166    ) -> std::result::Result<Self, fuel_ir::Error> {
1167        let hidden = gain.len();
1168        debug_assert_eq!(
1169            bias.len(),
1170            hidden,
1171            "layer_norm_affine: gain ({}) and bias ({}) must have the same length",
1172            gain.len(),
1173            bias.len()
1174        );
1175        let normed = self.layer_norm_last_dim(eps)?;
1176        let dims_v: Vec<usize> = self.inner.shape().dims().to_vec();
1177        let mut affine_shape = vec![1_usize; dims_v.len()];
1178        affine_shape[dims_v.len() - 1] = hidden;
1179        let bc_shape = Shape::from_dims(&dims_v);
1180        let g = normed
1181            .const_f32_like(gain, Shape::from_dims(&[hidden]))?
1182            .reshape(Shape::from_dims(&affine_shape))?
1183            .broadcast_to(bc_shape.clone())?;
1184        let b = normed
1185            .const_f32_like(bias, Shape::from_dims(&[hidden]))?
1186            .reshape(Shape::from_dims(&affine_shape))?
1187            .broadcast_to(bc_shape)?;
1188        normed.mul(&g)?.add(&b)
1189    }
1190
1191    /// L2-normalize along `dim`: `x / sqrt(sum(x²) + eps)`. Output
1192    /// shape equals input shape; the normalization divisor is
1193    /// broadcast across `dim` after a keepdim reduction.
1194    ///
1195    /// Common values: `eps = 1e-12` (PyTorch default), `eps = 1e-6`
1196    /// (some retrieval pipelines), `eps = 0.0` (no epsilon — caller
1197    /// guarantees no all-zero rows).
1198    pub fn l2_normalize<D: Dim>(
1199        &self,
1200        dim: D,
1201        eps: f64,
1202    ) -> std::result::Result<Self, fuel_ir::Error> {
1203        let sq = self.sqr();
1204        let summed = sq.sum_keepdim(dim)?;
1205        let with_eps = if eps == 0.0 {
1206            summed
1207        } else {
1208            summed.add_scalar(eps)
1209        };
1210        let l2 = with_eps.sqrt();
1211        let dims_v: Vec<usize> = self.inner.shape().dims().to_vec();
1212        let l2_bc = l2.broadcast_to(Shape::from_dims(&dims_v))?;
1213        self.div(&l2_bc)
1214    }
1215
1216    /// Equivalent to `torch.repeat_interleave(x, repeats, dim)`.
1217    /// Replaces each element along `dim` with `repeats` consecutive
1218    /// copies of itself, expanding that dim by a factor of `repeats`.
1219    /// Implemented via reshape+broadcast+reshape — no new graph op.
1220    ///
1221    /// `repeats == 1` is a no-op clone. `repeats == 0` returns an
1222    /// error at build time.
1223    pub fn repeat_interleave<D: Dim>(
1224        &self,
1225        dim: D,
1226        repeats: usize,
1227    ) -> std::result::Result<Self, fuel_ir::Error> {
1228        let shape = self.inner.shape();
1229        let dim = dim.to_index(&shape, "repeat_interleave")?;
1230        if repeats == 0 {
1231            return Err(fuel_ir::Error::Msg("repeat_interleave: repeats must be ≥ 1".into()).bt());
1232        }
1233        if repeats == 1 {
1234            return Ok(self.clone());
1235        }
1236        let dims_v: Vec<usize> = shape.dims().to_vec();
1237        let mut unsq_shape = dims_v.clone();
1238        unsq_shape.insert(dim + 1, 1);
1239        let mut bc_shape = unsq_shape.clone();
1240        bc_shape[dim + 1] = repeats;
1241        let unsq = self.reshape(Shape::from_dims(&unsq_shape))?;
1242        let bc = unsq.broadcast_to(Shape::from_dims(&bc_shape))?;
1243        let mut out_shape = dims_v.clone();
1244        out_shape[dim] *= repeats;
1245        bc.reshape(Shape::from_dims(&out_shape))
1246    }
1247
1248    /// Slice (narrow) along `dim`: take elements `[start, start+len)`.
1249    /// Bad `dim` / out-of-range slice surfaces as a typed error at build
1250    /// time. Accepts any [`Dim`].
1251    pub fn slice<D: Dim>(
1252        &self,
1253        dim: D,
1254        start: usize,
1255        len: usize,
1256    ) -> std::result::Result<Self, fuel_ir::Error> {
1257        let shape = self.inner.shape();
1258        let dim = dim.to_index(&shape, "slice")?;
1259        let dim_size = shape.dims()[dim];
1260        if start.saturating_add(len) > dim_size {
1261            return Err(fuel_ir::Error::Msg(format!(
1262                "slice: start={start} + len={len} exceeds dim {dim} size {dim_size}",
1263            ))
1264            .bt());
1265        }
1266        Ok(Self {
1267            inner: self.inner.slice(dim, start, len),
1268        })
1269    }
1270
1271    /// Concatenate two tensors along `dim`. Shape mismatch or bad `dim`
1272    /// surfaces as a typed error at build time. Accepts any [`Dim`].
1273    pub fn concat<D: Dim>(
1274        &self,
1275        other: &Self,
1276        dim: D,
1277    ) -> std::result::Result<Self, fuel_ir::Error> {
1278        let shape = self.inner.shape();
1279        let dim = dim.to_index(&shape, "concat")?;
1280        let self_dims = shape.dims().to_vec();
1281        let other_dims = other.inner.shape().dims().to_vec();
1282        if self_dims.len() != other_dims.len() {
1283            return Err(fuel_ir::Error::Msg(format!(
1284                "concat: rank mismatch lhs={self_dims:?} rhs={other_dims:?}",
1285            ))
1286            .bt());
1287        }
1288        for (i, (&a, &b)) in self_dims.iter().zip(other_dims.iter()).enumerate() {
1289            if i != dim && a != b {
1290                return Err(fuel_ir::Error::Msg(format!(
1291                    "concat: dim {i} mismatch lhs={a} rhs={b} (concat dim is {dim})",
1292                ))
1293                .bt());
1294            }
1295        }
1296        Ok(Self {
1297            inner: self.inner.concat(&other.inner, dim),
1298        })
1299    }
1300
1301    /// Add a scalar to every element.
1302    pub fn add_scalar(&self, c: f64) -> Self {
1303        Self {
1304            inner: self.inner.add_scalar(c),
1305        }
1306    }
1307
1308    /// Multiply every element by a scalar.
1309    pub fn mul_scalar(&self, c: f64) -> Self {
1310        Self {
1311            inner: self.inner.mul_scalar(c),
1312        }
1313    }
1314
1315    /// Argmax along a dim, returning a U32 tensor with the reduced
1316    /// dim removed. Non-differentiable. Bad `dim` surfaces as a typed
1317    /// error at build time. Accepts any [`Dim`].
1318    pub fn argmax_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1319        let shape = self.inner.shape();
1320        let dim = dim.to_index(&shape, "argmax_dim")?;
1321        Ok(Self {
1322            inner: self.inner.argmax_dim(dim),
1323        })
1324    }
1325
1326    /// Realize as a `u32` (index) `Vec`.
1327    ///
1328    /// Routes through the [`fuel_dispatch::pipelined::PipelinedExecutor`] like [`Self::realize_f32`]
1329    /// — the legacy fuel-reference-backend executor predates U8-output
1330    /// ops (comparison masks feeding argmin/argmax) and rejects them.
1331    pub fn realize_u32(&self) -> Vec<u32> {
1332        let graph = self.inner.graph().clone();
1333        let target = self.inner.id();
1334        let device = crate::Device::cpu();
1335        crate::pipelined_bridge::realize_one_as::<u32>(&graph, target, &device)
1336            .expect("realize_u32 via PipelinedExecutor")
1337    }
1338
1339    /// Realize as raw bytes (`u8`). A BYTE VIEW: reads a `Bool` mask (0/1 per byte) or a
1340    /// `U8` tensor back to host (GAP-168(c)), and by design does NOT guard the root dtype —
1341    /// it routes through [`crate::pipelined_bridge::realize_one_bytes`] (the raw byte entry,
1342    /// GAP-327), so a `Bool` root (dtype != `U8`) is read as its bytes rather than rejected.
1343    ///
1344    /// **PANICS** on a realize failure; for a fallible byte view use
1345    /// [`crate::pipelined_bridge::realize_one_bytes`]. See [`Self::realize_f32`] for the
1346    /// documented-not-enforced rationale (GAP-186).
1347    pub fn realize_u8(&self) -> Vec<u8> {
1348        let graph = self.inner.graph().clone();
1349        let target = self.inner.id();
1350        let device = crate::Device::cpu();
1351        crate::pipelined_bridge::realize_one_bytes(&graph, target, &device)
1352            .expect("realize_u8 via PipelinedExecutor")
1353    }
1354
1355    // ---- reductions ----
1356
1357    /// Sum of all elements, producing a scalar.
1358    pub fn sum_all(&self) -> Self {
1359        Self {
1360            inner: self.inner.sum_all(),
1361        }
1362    }
1363
1364    /// Arithmetic mean of all elements, producing a scalar.
1365    pub fn mean_all(&self) -> Self {
1366        Self {
1367            inner: self.inner.mean_all(),
1368        }
1369    }
1370
1371    /// Maximum of every element, producing a scalar.
1372    pub fn max_all(&self) -> Self {
1373        Self {
1374            inner: self.inner.max_all(),
1375        }
1376    }
1377
1378    /// Minimum of every element, producing a scalar.
1379    pub fn min_all(&self) -> Self {
1380        Self {
1381            inner: self.inner.min_all(),
1382        }
1383    }
1384
1385    /// Sum along a single dimension (dim removed from output). Bad
1386    /// `dim` surfaces as a typed error at build time. Accepts any [`Dim`].
1387    pub fn sum_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1388        let shape = self.inner.shape();
1389        let dim = dim.to_index(&shape, "sum_dim")?;
1390        Ok(Self {
1391            inner: self.inner.sum_dim(dim),
1392        })
1393    }
1394
1395    /// Max along a single dimension (dim removed from output).
1396    pub fn max_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1397        let shape = self.inner.shape();
1398        let dim = dim.to_index(&shape, "max_dim")?;
1399        Ok(Self {
1400            inner: self.inner.max_dim(dim),
1401        })
1402    }
1403
1404    /// Min along a single dimension (dim removed from output).
1405    pub fn min_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1406        let shape = self.inner.shape();
1407        let dim = dim.to_index(&shape, "min_dim")?;
1408        Ok(Self {
1409            inner: self.inner.min_dim(dim),
1410        })
1411    }
1412
1413    /// Element-wise clamp to `[min, max]`.
1414    pub fn clamp(&self, min: f64, max: f64) -> Self {
1415        Self {
1416            inner: self.inner.clamp(min, max),
1417        }
1418    }
1419
1420    /// Mean along a single dimension.
1421    pub fn mean_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
1422        let shape = self.inner.shape();
1423        let dim = dim.to_index(&shape, "mean_dim")?;
1424        Ok(Self {
1425            inner: self.inner.mean_dim(dim),
1426        })
1427    }
1428
1429    /// Sum-reduce to a smaller broadcast-compatible shape. Inverse of
1430    /// [`Self::broadcast_to`]; reduces over any dim where the source
1431    /// was broadcast against the target.
1432    pub fn reduce_sum_to(&self, target: impl Into<Shape>) -> Self {
1433        Self {
1434            inner: self.inner.reduce_sum_to(target),
1435        }
1436    }
1437
1438    /// Max-reduce to a smaller broadcast-compatible shape — the
1439    /// max-symmetric counterpart of [`Self::reduce_sum_to`].
1440    pub fn reduce_max_to(&self, target: impl Into<Shape>) -> Self {
1441        Self {
1442            inner: self.inner.reduce_max_to(target),
1443        }
1444    }
1445
1446    // ---- compositions ----
1447
1448    /// Softmax along the last dim. Rank-0 input surfaces as a typed
1449    /// error at build time rather than panicking inside `fuel_graph`.
1450    pub fn softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
1451        let shape = self.inner.shape();
1452        let dims = shape.dims();
1453        if dims.is_empty() {
1454            return Err(fuel_ir::Error::Msg(
1455                "softmax_last_dim: input must be rank >= 1, got scalar".into(),
1456            )
1457            .bt());
1458        }
1459        Ok(Self {
1460            inner: self.inner.softmax_last_dim(),
1461        })
1462    }
1463
1464    /// bitsandbytes-style 4-bit NormalFloat quantized matrix
1465    /// multiply. See [`fuel_graph::NodeHandle::nf4_matmul`] for the full
1466    /// shape contract. v1 covers F32/F16/BF16 activations.
1467    pub fn nf4_matmul(&self, w_packed: &Self, absmax: &Self, block_size: usize) -> Self {
1468        Self {
1469            inner: self
1470                .inner
1471                .nf4_matmul(&w_packed.inner, &absmax.inner, block_size),
1472        }
1473    }
1474
1475    /// Mamba-2's State-Space Duality chunked scan (forward). See
1476    /// [`fuel_graph::NodeHandle::ssd_chunk_scan`] for the full shape
1477    /// contract. `chunk_size` is a GPU-parallelism granularity knob;
1478    /// the CPU kernel runs sequential regardless.
1479    pub fn ssd_chunk_scan(
1480        &self,
1481        dt: &Self,
1482        a: &Self,
1483        b: &Self,
1484        c: &Self,
1485        chunk_size: usize,
1486    ) -> Self {
1487        Self {
1488            inner: self
1489                .inner
1490                .ssd_chunk_scan(&dt.inner, &a.inner, &b.inner, &c.inner, chunk_size),
1491        }
1492    }
1493
1494    /// Mamba-1's selective state-space scan (forward). See
1495    /// [`fuel_graph::NodeHandle::selective_scan`] for the full shape
1496    /// contract. Returns just `y` — for the bundled `(y, last_state)`
1497    /// form needed by autoregressive resumption use
1498    /// [`Self::selective_scan_bundled`].
1499    pub fn selective_scan(
1500        &self,
1501        delta: &Self,
1502        a: &Self,
1503        b: &Self,
1504        c: &Self,
1505        delta_softplus: bool,
1506    ) -> Self {
1507        Self {
1508            inner: self.inner.selective_scan(
1509                &delta.inner,
1510                &a.inner,
1511                &b.inner,
1512                &c.inner,
1513                delta_softplus,
1514            ),
1515        }
1516    }
1517
1518    /// Multi-output Mamba-1 SSM scan: returns `(y, last_state)`. `y`
1519    /// matches the single-output [`Self::selective_scan`] result;
1520    /// `last_state` is the final hidden state `[batch, dim, dstate]`
1521    /// used by autoregressive callers to resume from a prefill
1522    /// snapshot. Both Tensors are `Op::View` projections of the
1523    /// same bundled producer Storage — realizing them in the same
1524    /// pass shares the bundle.
1525    pub fn selective_scan_bundled(
1526        &self,
1527        delta: &Self,
1528        a: &Self,
1529        b: &Self,
1530        c: &Self,
1531        delta_softplus: bool,
1532    ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1533        let (y, last_state) = self.inner.selective_scan_bundled(
1534            &delta.inner,
1535            &a.inner,
1536            &b.inner,
1537            &c.inner,
1538            delta_softplus,
1539        )?;
1540        Ok((Self { inner: y }, Self { inner: last_state }))
1541    }
1542
1543    /// Multi-output Mamba-2 SSD scan: returns `(y, last_state)`.
1544    /// Mirrors [`Self::selective_scan_bundled`]. `last_state` has
1545    /// shape `[batch, heads, head_dim, state_dim]`.
1546    pub fn ssd_chunk_scan_bundled(
1547        &self,
1548        dt: &Self,
1549        a: &Self,
1550        b: &Self,
1551        c: &Self,
1552        chunk_size: usize,
1553    ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1554        let (y, last_state) = self
1555            .inner
1556            .ssd_chunk_scan_bundled(&dt.inner, &a.inner, &b.inner, &c.inner, chunk_size)?;
1557        Ok((Self { inner: y }, Self { inner: last_state }))
1558    }
1559
1560    /// Data-determined nonzero-index extraction — the keystone primitive
1561    /// for **data-dependent dynamic shapes**. Returns `(indices, count)`:
1562    /// `indices` is `[capacity]` U32 (`capacity == self.elem_count()`),
1563    /// the first `count` entries being the ascending flat indices of
1564    /// `self`'s nonzero elements; `count` is `[1]` U32, the runtime
1565    /// nonzero count. Both are `Op::View` projections of one bundled
1566    /// producer. The executor also publishes `count`'s realized value into
1567    /// the per-pass `SymEnv` under `count_sym`, so downstream ops can
1568    /// consume it as a dynamic extent (the KV-cache `cached_len` pattern,
1569    /// generalized to a data-determined count). `count_sym` is allocated
1570    /// by the caller (from a [`fuel_ir::SymGen`]).
1571    pub fn nonzero_indices_bundled(
1572        &self,
1573        count_sym: fuel_ir::SymId,
1574    ) -> std::result::Result<(Self, Self), fuel_ir::Error> {
1575        let (indices, count) = self.inner.nonzero_indices_bundled(count_sym)?;
1576        Ok((Self { inner: indices }, Self { inner: count }))
1577    }
1578
1579    /// Allocate a data-determined [`fuel_ir::SymId`] not yet used by any
1580    /// producer on this tensor's graph — see
1581    /// [`fuel_graph::Graph::next_data_determined_sym`]. Lets a builder that
1582    /// emits several [`Self::nonzero_indices_bundled`] producers on one
1583    /// graph (per-expert MoE dispatch, stacked layers) claim non-colliding
1584    /// count syms without threading a [`fuel_ir::SymGen`]: each call
1585    /// reflects the producers already added.
1586    pub fn fresh_data_determined_sym(&self) -> fuel_ir::SymId {
1587        let graph = self.inner.graph();
1588        let g = graph.read().unwrap();
1589        g.next_data_determined_sym()
1590    }
1591
1592    /// Depthwise 1-D causal convolution + bias + optional fused SiLU
1593    /// — the Mamba-1 / Mamba-2 prefill convolution fusion. See
1594    /// [`fuel_graph::NodeHandle::causal_conv1d`] for the full shape
1595    /// contract (caller must left-pad x with `kernel - 1` zeros).
1596    pub fn causal_conv1d(&self, weight: &Self, bias: &Self, use_silu: bool) -> Self {
1597        Self {
1598            inner: self
1599                .inner
1600                .causal_conv1d(&weight.inner, &bias.inner, use_silu),
1601        }
1602    }
1603
1604    /// Fused softmax + cross-entropy with integer (class-index)
1605    /// targets — the standard PyTorch CE loss. See
1606    /// [`fuel_graph::NodeHandle::fused_softmax_cross_entropy`] for the full
1607    /// shape contract.
1608    pub fn fused_softmax_cross_entropy(
1609        &self,
1610        targets: &Self,
1611        reduction: fuel_graph::registry::Reduction,
1612        ignore_index: i64,
1613    ) -> Self {
1614        Self {
1615            inner: self
1616                .inner
1617                .fused_softmax_cross_entropy(&targets.inner, reduction, ignore_index),
1618        }
1619    }
1620
1621    /// LayerNorm along the last dim with the given epsilon. Rank-0
1622    /// or zero-last-dim input surfaces as a typed error at build time.
1623    pub fn layer_norm_last_dim(&self, eps: f64) -> std::result::Result<Self, fuel_ir::Error> {
1624        let shape = self.inner.shape();
1625        let dims = shape.dims();
1626        if dims.last().copied().unwrap_or(0) == 0 {
1627            return Err(fuel_ir::Error::Msg(format!(
1628                "layer_norm_last_dim: input must have non-zero last dim, got {dims:?}",
1629            ))
1630            .bt());
1631        }
1632        Ok(Self {
1633            inner: self.inner.layer_norm_last_dim(eps),
1634        })
1635    }
1636
1637    /// RmsNorm along the last dim (LLaMA's normalization). Rank-0 or
1638    /// zero-last-dim input surfaces as a typed error at build time.
1639    pub fn rms_norm_last_dim(&self, eps: f64) -> std::result::Result<Self, fuel_ir::Error> {
1640        let shape = self.inner.shape();
1641        let dims = shape.dims();
1642        if dims.last().copied().unwrap_or(0) == 0 {
1643            return Err(fuel_ir::Error::Msg(format!(
1644                "rms_norm_last_dim: input must have non-zero last dim, got {dims:?}",
1645            ))
1646            .bt());
1647        }
1648        Ok(Self {
1649            inner: self.inner.rms_norm_last_dim(eps),
1650        })
1651    }
1652
1653    /// Apply rotary position embeddings. See [`fuel_graph::NodeHandle::rope`].
1654    /// Rank < 2 surfaces as a typed error at build time.
1655    pub fn rope(&self, base: f64, start_pos: usize) -> std::result::Result<Self, fuel_ir::Error> {
1656        let shape = self.inner.shape();
1657        let dims = shape.dims();
1658        if dims.len() < 2 {
1659            return Err(fuel_ir::Error::Msg(format!(
1660                "rope: input must have rank >= 2, got {dims:?}",
1661            ))
1662            .bt());
1663        }
1664        Ok(Self {
1665            inner: self.inner.rope(base, start_pos),
1666        })
1667    }
1668
1669    /// Apply RoPE using caller-supplied `cos` and `sin` tables so they
1670    /// can be shared across many layers. See
1671    /// [`fuel_graph::NodeHandle::rope_with_tables`].
1672    ///
1673    /// Rank / dtype / table-shape mismatches surface as typed errors
1674    /// at build time rather than panicking inside `fuel_graph`.
1675    pub fn rope_with_tables(
1676        &self,
1677        cos: &Self,
1678        sin: &Self,
1679    ) -> std::result::Result<Self, fuel_ir::Error> {
1680        if self.inner.dtype() != fuel_ir::DType::F32 {
1681            return Err(fuel_ir::Error::Msg(format!(
1682                "rope: only f32 is supported today, got {:?} (cast explicitly for other dtypes)",
1683                self.inner.dtype(),
1684            ))
1685            .bt());
1686        }
1687        let in_shape = self.inner.shape();
1688        let dims = in_shape.dims();
1689        let rank = dims.len();
1690        if rank < 2 {
1691            return Err(fuel_ir::Error::Msg(format!(
1692                "rope: input must have rank >= 2, got {dims:?}",
1693            ))
1694            .bt());
1695        }
1696        let seq = dims[rank - 2];
1697        let d = dims[rank - 1];
1698        if !d.is_multiple_of(2) {
1699            return Err(fuel_ir::Error::Msg(format!("rope: feature dim {d} must be even",)).bt());
1700        }
1701        let cos_shape = cos.inner.shape();
1702        let cos_dims = cos_shape.dims();
1703        if cos_dims != [seq, d] {
1704            return Err(fuel_ir::Error::Msg(format!(
1705                "rope_with_tables: cos shape {cos_dims:?} does not match [seq, d] = [{seq}, {d}]",
1706            ))
1707            .bt());
1708        }
1709        let sin_shape = sin.inner.shape();
1710        let sin_dims = sin_shape.dims();
1711        if sin_dims != [seq, d] {
1712            return Err(fuel_ir::Error::Msg(format!(
1713                "rope_with_tables: sin shape {sin_dims:?} does not match [seq, d] = [{seq}, {d}]",
1714            ))
1715            .bt());
1716        }
1717        Ok(Self {
1718            inner: self.inner.rope_with_tables(&cos.inner, &sin.inner),
1719        })
1720    }
1721
1722    /// Apply RoPE using caller-supplied `cos`/`sin` tables, emitting the
1723    /// PRIMITIVE decomposition (slice + neg + concat + mul + add — the
1724    /// rotate-half recipe) instead of a single fused `FusedOps::ROPE` node.
1725    /// See [`fuel_graph::NodeHandle::rope_with_tables_decomposed`].
1726    ///
1727    /// CapturedRun 4b-resume: Fuel's `FusedOps::ROPE` is rotate-half (Llama/HF)
1728    /// but has NO correct (rotate-half) CUDA kernel — baracuda's is interleaved
1729    /// (see the rope-convention note). The fused op therefore places on CPU,
1730    /// which breaks CUDA-graph capture. Emitting the decomposition makes every
1731    /// step a primitive with a capture-safe CUDA kernel, so the decode runs
1732    /// entirely on CUDA. Forward-compatible: once a rotate-half fused CUDA rope
1733    /// kernel exists, the optimizer's re-fusion pattern will fold this subgraph
1734    /// back into the fused op automatically (recipe principle).
1735    ///
1736    /// Byte-identical semantics to [`Self::rope_with_tables`] (same rotate-half
1737    /// math); same validation.
1738    pub fn rope_with_tables_decomposed(
1739        &self,
1740        cos: &Self,
1741        sin: &Self,
1742    ) -> std::result::Result<Self, fuel_ir::Error> {
1743        if self.inner.dtype() != fuel_ir::DType::F32 {
1744            return Err(fuel_ir::Error::Msg(format!(
1745                "rope: only f32 is supported today, got {:?} (cast explicitly for other dtypes)",
1746                self.inner.dtype(),
1747            ))
1748            .bt());
1749        }
1750        let in_shape = self.inner.shape();
1751        let dims = in_shape.dims();
1752        let rank = dims.len();
1753        if rank < 2 {
1754            return Err(fuel_ir::Error::Msg(format!(
1755                "rope: input must have rank >= 2, got {dims:?}",
1756            ))
1757            .bt());
1758        }
1759        let seq = dims[rank - 2];
1760        let d = dims[rank - 1];
1761        if !d.is_multiple_of(2) {
1762            return Err(fuel_ir::Error::Msg(format!("rope: feature dim {d} must be even",)).bt());
1763        }
1764        let cos_dims = cos.inner.shape();
1765        if cos_dims.dims() != [seq, d] {
1766            return Err(fuel_ir::Error::Msg(format!(
1767                "rope_with_tables_decomposed: cos shape {:?} does not match [seq, d] = [{seq}, {d}]",
1768                cos_dims.dims(),
1769            )).bt());
1770        }
1771        let sin_dims = sin.inner.shape();
1772        if sin_dims.dims() != [seq, d] {
1773            return Err(fuel_ir::Error::Msg(format!(
1774                "rope_with_tables_decomposed: sin shape {:?} does not match [seq, d] = [{seq}, {d}]",
1775                sin_dims.dims(),
1776            )).bt());
1777        }
1778        Ok(Self {
1779            inner: self
1780                .inner
1781                .rope_with_tables_decomposed(&cos.inner, &sin.inner),
1782        })
1783    }
1784
1785    // ---- indexing ----
1786
1787    /// Pick slices along `dim` using a 1-D U32 index tensor. Accepts
1788    /// any [`Dim`]. Dim bounds / index dtype / index rank mismatches
1789    /// surface as typed errors at build time.
1790    pub fn index_select<D: Dim>(
1791        &self,
1792        dim: D,
1793        indices: &Self,
1794    ) -> std::result::Result<Self, fuel_ir::Error> {
1795        let shape = self.inner.shape();
1796        let dim = dim.to_index(&shape, "index_select")?;
1797        if indices.inner.dtype() != fuel_ir::DType::U32 {
1798            return Err(fuel_ir::Error::Msg(format!(
1799                "index_select: index tensor must be U32, got {:?}",
1800                indices.inner.dtype(),
1801            ))
1802            .bt());
1803        }
1804        let idx_shape = indices.inner.shape();
1805        let idx_dims = idx_shape.dims();
1806        if idx_dims.len() != 1 {
1807            return Err(fuel_ir::Error::Msg(format!(
1808                "index_select: index tensor must be rank 1, got {idx_dims:?}",
1809            ))
1810            .bt());
1811        }
1812        Ok(Self {
1813            inner: self.inner.index_select(dim, &indices.inner),
1814        })
1815    }
1816
1817    /// N-D gather along `dim` using a U32 index tensor with the same
1818    /// rank as `self`; output shape equals the index shape. Accepts
1819    /// any [`Dim`]. Dim bounds / index dtype / rank mismatches surface
1820    /// as typed errors at build time.
1821    pub fn gather<D: Dim>(
1822        &self,
1823        dim: D,
1824        indices: &Self,
1825    ) -> std::result::Result<Self, fuel_ir::Error> {
1826        let shape = self.inner.shape();
1827        let dim = dim.to_index(&shape, "gather")?;
1828        if indices.inner.dtype() != fuel_ir::DType::U32 {
1829            return Err(fuel_ir::Error::Msg(format!(
1830                "gather: index tensor must be U32, got {:?}",
1831                indices.inner.dtype(),
1832            ))
1833            .bt());
1834        }
1835        let data_rank = shape.dims().len();
1836        let idx_shape = indices.inner.shape();
1837        let idx_rank = idx_shape.dims().len();
1838        if data_rank != idx_rank {
1839            return Err(fuel_ir::Error::Msg(format!(
1840                "gather: data and index must have the same rank, got {data_rank} vs {idx_rank}",
1841            ))
1842            .bt());
1843        }
1844        Ok(Self {
1845            inner: self.inner.gather(dim, &indices.inner),
1846        })
1847    }
1848
1849    // ---- dtype ----
1850
1851    /// Convert to a different dtype. Same-dtype is a fast-path no-op
1852    /// (returns a clone) rather than emitting a redundant graph node.
1853    ///
1854    /// The name follows the eager-API convention: users shouldn't need
1855    /// to care whether the underlying bytes are reinterpreted (e.g.
1856    /// integer widening) or transcoded (e.g. f32 → bf16). Build-time
1857    /// validation is currently minimal — Cast itself is unfailing in
1858    /// `fuel_graph`; the Result return is reserved for future
1859    /// kernel-registry checks (Phase A.8c-extension).
1860    pub fn to_dtype(&self, dtype: DType) -> std::result::Result<Self, fuel_ir::Error> {
1861        if self.inner.dtype() == dtype {
1862            return Ok(self.clone());
1863        }
1864        Ok(Self {
1865            inner: self.inner.cast(dtype),
1866        })
1867    }
1868
1869    /// Detach this tensor from autograd. On lazy, autograd is structural
1870    /// (every graph edge participates in backward unless explicitly cut
1871    /// by a non-differentiable op), so there's no per-tensor toggle —
1872    /// `detach()` is the identity function. Provided for eager-API
1873    /// parity so consumer code that calls `.detach()` compiles
1874    /// unchanged.
1875    pub fn detach(&self) -> Self {
1876        self.clone()
1877    }
1878
1879    /// Whether autograd is tracking this tensor. On lazy, every tensor
1880    /// participates in autograd structurally; `track_op` returns true
1881    /// unconditionally for API parity with eager.
1882    pub fn track_op(&self) -> bool {
1883        true
1884    }
1885
1886    // ---- realization (the pipelined bridge) ----
1887    //
1888    // Signature note (executor-unification Session 1, re-audit gap 8):
1889    // all five typed realize entries (`realize_f32` / `_f64` / `_bf16`
1890    // / `_f16` / `_u32`) return `Vec<T>` and panic via `.expect` on
1891    // executor errors. The signatures predate the Result-returning
1892    // policy and `realize_f32` alone has 350+ in-repo call sites
1893    // across ~60 files — converting the family to `Result` is a
1894    // coordinated breaking sweep that must move all five together
1895    // (one consistent error story), so it gets its own session
1896    // rather than riding an executor-port commit. Until then the
1897    // `.expect`s stay, uniformly.
1898
1899    /// Realize this tensor as an `f32` `Vec`.
1900    ///
1901    /// Routes unconditionally through the pipelined bridge: walk the
1902    /// graph, pre-realize Consts onto CPU, plan + dispatch through
1903    /// `PipelinedExecutor`, read back the root's bytes.
1904    ///
1905    /// Judge profile data still shapes dispatch — on this same path.
1906    /// When a profile is cached ([`crate::judge::populate_dispatch_table`]
1907    /// ran this process, or a prior run persisted one for this
1908    /// hardware), [`crate::judge::cached_oracle`] feeds the picker:
1909    /// `compile_plan`'s Layer-2 cost refinement and the JudgeAware
1910    /// runtime selector both rank alternatives (portable CPU vs
1911    /// AOCL/MKL kernel-source siblings included) by measured latency.
1912    /// Executor-unification Session 3 (2026-06-11) deleted the legacy
1913    /// `judge::cached()` branch that swapped in a Router-backed
1914    /// `GraphExecutor` instead — the picker consumes the same Judge
1915    /// data without leaving the production executor.
1916    ///
1917    /// **Convenience accessor — PANICS on a realize failure** (`.expect()`).
1918    /// That is a deliberate choice for the test / example / notebook callers
1919    /// who want `.realize_f32()[0]` without error-handling clutter, NOT a trap:
1920    /// a caller that must PROPAGATE a realize failure (any serving / production
1921    /// path) has a documented fallible sibling —
1922    /// [`crate::pipelined_bridge::realize_one_as`] (with `::<f32>`) — which
1923    /// returns `Result`. GAP-186: this is DOCUMENTED, NOT ENFORCED. `realize_*`
1924    /// is a genuine public API (13 `fuel-core/tests/` integration crates plus
1925    /// `fuel-examples` call it), so it cannot be made
1926    /// test-only; the never-panic obligation lives on the production callers,
1927    /// which use the fallible sibling directly (as `train.rs::param_to_host`
1928    /// does).
1929    pub fn realize_f32(&self) -> Vec<f32> {
1930        let graph = self.inner.graph().clone();
1931        let target = self.inner.id();
1932        let device = crate::Device::cpu();
1933        crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device)
1934            .expect("realize_f32 via PipelinedExecutor")
1935    }
1936
1937    /// Realize on CPU as an **independent correctness oracle**: like
1938    /// [`Self::realize_f32`] but with cost-based cross-device placement
1939    /// suppressed, so the whole graph runs on the CPU backend's bit-stable
1940    /// kernels and is never relocated to a GPU by the optimizer.
1941    ///
1942    /// [`Self::realize_f32`] pins CPU only as a *soft* host anchor — since the
1943    /// Step-E cost-based auto-placement, its optimizer may price model nodes
1944    /// onto a present GPU and insert an H2D `Op::Copy`, which both defeats the
1945    /// oracle's independence (it would validate a backend against itself) and,
1946    /// on a single-device realize, crashes for lack of a seeded GPU handle.
1947    /// This entry hard-pins CPU (`allow_cost_placement = false`); by the
1948    /// always-built coverage commitment the CPU backend supplies a kernel for
1949    /// every primitive op, so nothing is ever stranded. This is the
1950    /// pairwise-consensus oracle that replaces the retiring
1951    /// `fuel-reference-backend`.
1952    pub fn realize_f32_reference(&self) -> Vec<f32> {
1953        let graph = self.inner.graph().clone();
1954        let target = self.inner.id();
1955        let device = crate::Device::cpu();
1956        crate::pipelined_bridge::realize_one_reference_as::<f32>(&graph, target, &device)
1957            .expect("realize_f32_reference via PipelinedExecutor")
1958    }
1959
1960    /// Realize as an `f64` `Vec`.
1961    ///
1962    /// Routes through the [`fuel_dispatch::pipelined::PipelinedExecutor`] like
1963    /// [`Self::realize_f32`] — executor-unification Session 1
1964    /// (re-audit gap 8) retires the typed `fuel_graph_cpu` recursive
1965    /// evaluator from the public API. The root must already be
1966    /// F64-dtype (insert [`Self::to_dtype`] otherwise). The dtype guard
1967    /// lives at the single realize funnel
1968    /// [`crate::pipelined_bridge::realize_one_as`] (GAP-327): a mismatch
1969    /// returns [`fuel_ir::Error::UnexpectedDType`], which the `.expect`
1970    /// below turns into a panic here — so the byte reinterpretation never
1971    /// silently returns garbage.
1972    pub fn realize_f64(&self) -> Vec<f64> {
1973        let graph = self.inner.graph().clone();
1974        let target = self.inner.id();
1975        let device = crate::Device::cpu();
1976        crate::pipelined_bridge::realize_one_as::<f64>(&graph, target, &device)
1977            .expect("realize_f64 via PipelinedExecutor")
1978    }
1979
1980    /// Realize as a `bf16` `Vec`. See [`Self::realize_f64`] for the
1981    /// routing + dtype-guard rationale.
1982    pub fn realize_bf16(&self) -> Vec<half::bf16> {
1983        let graph = self.inner.graph().clone();
1984        let target = self.inner.id();
1985        let device = crate::Device::cpu();
1986        crate::pipelined_bridge::realize_one_as::<half::bf16>(&graph, target, &device)
1987            .expect("realize_bf16 via PipelinedExecutor")
1988    }
1989
1990    /// Realize as an `f16` `Vec`. See [`Self::realize_f64`] for the
1991    /// routing + dtype-guard rationale.
1992    pub fn realize_f16(&self) -> Vec<half::f16> {
1993        let graph = self.inner.graph().clone();
1994        let target = self.inner.id();
1995        let device = crate::Device::cpu();
1996        crate::pipelined_bridge::realize_one_as::<half::f16>(&graph, target, &device)
1997            .expect("realize_f16 via PipelinedExecutor")
1998    }
1999
2000    /// Realize on a CUDA GPU via [`PipelinedExecutor`].
2001    ///
2002    /// Phase 7.6 step 9c E.2: signature change from
2003    /// `&mut GraphExecutor<CudaBackend>` to `&CudaDevice`. The
2004    /// pipelined executor doesn't carry a const_pool — each call
2005    /// re-uploads weights. For autoregressive decoding loops where
2006    /// const_pool was load-bearing, use the persistent-StorageCache
2007    /// pattern shipped in Phase E.3 (KVCache migration).
2008    ///
2009    /// # Panics
2010    ///
2011    /// On a realize failure (`.expect()`), like [`Self::realize_f32`]. A caller
2012    /// that must propagate the error uses
2013    /// [`crate::pipelined_bridge::realize_one_as`] with `::<f32>`.
2014    #[cfg(feature = "cuda")]
2015    pub fn realize_f32_cuda(&self, device: &fuel_cuda_backend::CudaDevice) -> Vec<f32> {
2016        let graph = self.inner.graph().clone();
2017        let target = self.inner.id();
2018        let fc_device: crate::Device = device.clone().into();
2019        crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2020            .expect("realize_f32_cuda via PipelinedExecutor")
2021    }
2022
2023    // The legacy-executor-signature `realize_f32_vulkan` was deleted in
2024    // executor-unification Session 2 (2026-06-11). This bridge-based
2025    // wrapper restores Vulkan/CUDA realize parity (2026-06-15): it goes
2026    // through `pipelined_bridge::realize_one_as` on a Vulkan `Device`,
2027    // the same production path `realize_f32` / `realize_f32_cuda` use —
2028    // so it exercises the `optimize_graph` realize path on the Vulkan
2029    // backend.
2030    #[cfg(feature = "vulkan")]
2031    pub fn realize_f32_vulkan(
2032        &self,
2033        backend: &std::sync::Arc<fuel_vulkan_backend::VulkanBackend>,
2034    ) -> Vec<f32> {
2035        let graph = self.inner.graph().clone();
2036        let target = self.inner.id();
2037        let fc_device: crate::Device = backend.clone().into();
2038        crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2039            .expect("realize_f32_vulkan via PipelinedExecutor")
2040    }
2041}
2042
2043/// Realize many tensors in a single CPU topo-walk. Phase 7.6 step 9c E.2.
2044pub fn realize_many_f32(tensors: &[&Tensor]) -> Vec<Vec<f32>> {
2045    if tensors.is_empty() {
2046        return Vec::new();
2047    }
2048    let graph = tensors[0].inner.graph().clone();
2049    let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2050    let device = crate::Device::cpu();
2051    crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &device)
2052        .expect("realize_many_f32 via PipelinedExecutor")
2053}
2054
2055/// CUDA variant of realize_many_f32. Phase 7.6 step 9c E.2: signature
2056/// change from `&mut GraphExecutor<CudaBackend>` to `&CudaDevice`.
2057#[cfg(feature = "cuda")]
2058pub fn realize_many_f32_cuda(
2059    tensors: &[&Tensor],
2060    device: &fuel_cuda_backend::CudaDevice,
2061) -> Vec<Vec<f32>> {
2062    if tensors.is_empty() {
2063        return Vec::new();
2064    }
2065    let graph = tensors[0].inner.graph().clone();
2066    let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2067    let fc_device: crate::Device = device.clone().into();
2068    crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &fc_device)
2069        .expect("realize_many_f32_cuda via PipelinedExecutor")
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074    use super::*;
2075    use crate::Shape;
2076
2077    #[test]
2078    fn constructors_wrap_graph_tensor_correctly() {
2079        let t =
2080            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2081        assert_eq!(t.dtype(), DType::F32);
2082        assert_eq!(t.shape().dims(), &[3]);
2083        assert_eq!(t.rank(), 1);
2084        assert_eq!(t.elem_count(), 3);
2085    }
2086
2087    #[test]
2088    fn add_builds_add_node_in_underlying_graph() {
2089        let a =
2090            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2091        let b = a
2092            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2093            .unwrap();
2094        let c = a.add(&b).unwrap();
2095        assert_eq!(c.shape().dims(), &[3]);
2096        // All three tensors share one underlying graph (by Arc cloning
2097        // via const_f32_like / add).
2098        assert!(std::sync::Arc::ptr_eq(
2099            c.graph_tensor().graph(),
2100            a.graph_tensor().graph(),
2101        ));
2102    }
2103
2104    #[test]
2105    fn chained_lazy_method_call_builds_sensible_graph() {
2106        // Exercise a small pipeline typical of what an early LLaMA
2107        // port would write: RmsNorm → matmul → RMS-style residual.
2108        // We just verify the shapes thread through cleanly and the
2109        // final tensor is consistent.
2110        let x = Tensor::from_f32(
2111            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2112            Shape::from_dims(&[2, 3]),
2113            &Device::cpu(),
2114        )
2115        .unwrap();
2116        let w = x
2117            .const_f32_like(
2118                vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
2119                Shape::from_dims(&[3, 3]),
2120            )
2121            .unwrap();
2122        let y = x
2123            .rms_norm_last_dim(1e-6)
2124            .unwrap()
2125            .matmul(&w)
2126            .unwrap()
2127            .relu();
2128        assert_eq!(y.shape().dims(), &[2, 3]);
2129        assert_eq!(y.dtype(), DType::F32);
2130    }
2131
2132    #[test]
2133    fn rope_through_lazy_wrapper() {
2134        // Verify the RoPE builder is reachable through Tensor.
2135        let x = Tensor::from_f32(
2136            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
2137            Shape::from_dims(&[2, 4]),
2138            &Device::cpu(),
2139        )
2140        .unwrap();
2141        let y = x.rope(10000.0, 0).unwrap();
2142        assert_eq!(y.shape().dims(), &[2, 4]);
2143        assert_eq!(y.dtype(), DType::F32);
2144    }
2145
2146    #[test]
2147    fn rope_delta_rotate_equals_direct_shift() {
2148        // rung-2 primitive: a K block rotated at its ORIGINAL positions then
2149        // uniformly delta-rotated by M is byte-equal to the same raw K rotated
2150        // DIRECTLY at the shifted positions. This is the exactness that lets a
2151        // cached prefix be reused at a non-zero offset. Everything is in the POOL
2152        // block layout [block_size, n_kv_heads, head_dim] that `read_block` yields.
2153        let dev = Device::cpu();
2154        let (n_kv_heads, head_dim, bs) = (2usize, 4usize, 4usize);
2155        let theta = 10000.0;
2156        let (p0, m) = (0usize, 8usize); // block at positions 0..4, shift by 8 → 8..12
2157        let raw: Vec<f32> = (0..bs * n_kv_heads * head_dim)
2158            .map(|i| (i as f32 * 0.017).sin())
2159            .collect();
2160        // Reference: rope a pool-layout [bs,Hkv,D] block DIRECTLY at `start_pos`
2161        // (heads forward → rope → back), mirroring the helper's permute so the two
2162        // paths are compared in the same layout.
2163        let rope_pool_at = |data: &[f32], start_pos: usize| -> Vec<f32> {
2164            let k = Tensor::from_f32(
2165                data.to_vec(),
2166                Shape::from_dims(&[bs, n_kv_heads, head_dim]),
2167                &dev,
2168            )
2169            .unwrap();
2170            let k4 = k
2171                .permute([1, 0, 2])
2172                .unwrap()
2173                .reshape(Shape::from_dims(&[1, n_kv_heads, bs, head_dim]))
2174                .unwrap();
2175            let (c, s) = k4.rope_tables_const(theta, start_pos, bs, head_dim);
2176            k4.rope_with_tables_decomposed(&c, &s)
2177                .unwrap()
2178                .reshape(Shape::from_dims(&[n_kv_heads, bs, head_dim]))
2179                .unwrap()
2180                .permute([1, 0, 2])
2181                .unwrap()
2182                .realize_f32()
2183        };
2184        let direct = rope_pool_at(&raw, p0 + m); // rope directly at shifted positions
2185        let at_p0 = rope_pool_at(&raw, p0); // cached, rotated at original positions
2186        let shifted =
2187            Tensor::rope_delta_rotate_block_f32(&dev, &at_p0, theta, m, bs, n_kv_heads, head_dim);
2188        let maxdiff = direct
2189            .iter()
2190            .zip(&shifted)
2191            .map(|(a, b)| (a - b).abs())
2192            .fold(0.0f32, f32::max);
2193        assert!(
2194            maxdiff < 1e-5,
2195            "delta-rotate == direct shift (maxdiff {maxdiff})"
2196        );
2197    }
2198
2199    #[test]
2200    fn cast_switches_dtype_through_wrapper() {
2201        let x =
2202            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2203        let y = x.to_dtype(DType::F64).unwrap();
2204        assert_eq!(y.dtype(), DType::F64);
2205        assert_eq!(y.shape().dims(), &[3]);
2206    }
2207
2208    #[test]
2209    fn indexing_builds_correct_output_shape() {
2210        let data =
2211            Tensor::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), &Device::cpu()).unwrap();
2212        let idx = data
2213            .const_u32_like(vec![0, 2, 1], Shape::from_dims(&[3]))
2214            .unwrap();
2215        let out = data.index_select(0, &idx).unwrap();
2216        assert_eq!(out.shape().dims(), &[3, 4]);
2217    }
2218
2219    // ---- Bridge realization tests ----
2220
2221    #[test]
2222    fn realize_f32_executes_the_underlying_graph() {
2223        // The moment of truth: build a graph through Tensor and
2224        // then realize it end-to-end. (a + b) * a for a = [1, 2, 3],
2225        // b = [4, 5, 6] should yield [5, 14, 27].
2226        let a =
2227            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2228        let b = a
2229            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2230            .unwrap();
2231        let c = a.add(&b).unwrap().mul(&a).unwrap();
2232        let result = c.realize_f32();
2233        assert_eq!(result, vec![5.0, 14.0, 27.0]);
2234    }
2235
2236    #[test]
2237    fn realize_f32_relu_and_maximum_propagate_nan_end_to_end() {
2238        // Pinned NaN-semantics convention (2026-07-08,
2239        // docs/architecture/10-decisions-log.md): Relu/Maximum/Minimum are
2240        // NaN-propagating (torch parity). This guards the full lazy path
2241        // (graph build -> optimize -> dispatch -> CPU kernel -> realize),
2242        // not just the scalar-kernel unit tests in fuel-cpu-backend.
2243        let a = Tensor::from_f32(
2244            vec![f32::NAN, -2.0, 3.0],
2245            Shape::from_dims(&[3]),
2246            &Device::cpu(),
2247        )
2248        .unwrap();
2249        let relu_result = a.relu().realize_f32();
2250        assert!(
2251            relu_result[0].is_nan(),
2252            "relu(NaN) must propagate NaN through realize, got {}",
2253            relu_result[0]
2254        );
2255        assert_eq!(relu_result[1], 0.0, "relu(-2) must clip to 0");
2256        assert_eq!(relu_result[2], 3.0, "relu(3) must pass through");
2257
2258        let b = a
2259            .const_f32_like(vec![1.0, f32::NAN, 2.0], Shape::from_dims(&[3]))
2260            .unwrap();
2261        let max_result = a.maximum(&b).unwrap().realize_f32();
2262        assert!(
2263            max_result[0].is_nan(),
2264            "maximum(NaN, 1) must propagate NaN through realize, got {}",
2265            max_result[0]
2266        );
2267        assert!(
2268            max_result[1].is_nan(),
2269            "maximum(-2, NaN) must propagate NaN through realize, got {}",
2270            max_result[1]
2271        );
2272        assert_eq!(max_result[2], 3.0, "maximum(3, 2) non-NaN sanity");
2273    }
2274
2275    // ===== GAP-048: KISS-Ops §6.15 resolution helpers (fmax_ieee / fmin_ieee /
2276    // rem_trunc) — realized end-to-end because fuel-graph tests only BUILD; the
2277    // VALUE divergence needs a backend. Do NOT move these "closer to the code" in
2278    // fuel-graph: there they cannot realize and become vacuous. =====
2279
2280    #[test]
2281    fn fmax_fmin_ieee_suppress_nan_where_prop_propagates() {
2282        // §6.15-0001 divergence born-red. The IEEE (suppress) and torch-parity
2283        // (propagate) halves diverge ONLY on a NaN operand — a no-NaN fixture
2284        // passes under BOTH and is vacuous, so the fixture must carry NaN.
2285        let a = Tensor::from_f32(
2286            vec![f32::NAN, 2.0, 5.0],
2287            Shape::from_dims(&[3]),
2288            &Device::cpu(),
2289        )
2290        .unwrap();
2291        let b = a
2292            .const_f32_like(vec![3.0, f32::NAN, 4.0], Shape::from_dims(&[3]))
2293            .unwrap();
2294
2295        let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2296        assert_eq!(fmax[0], 3.0, "fmax_ieee(NaN,3) suppresses NaN → 3");
2297        assert_eq!(fmax[1], 2.0, "fmax_ieee(2,NaN) suppresses NaN → 2");
2298        assert_eq!(fmax[2], 5.0, "fmax_ieee(5,4) → 5");
2299        let max = a.maximum(&b).unwrap().realize_f32();
2300        assert!(
2301            max[0].is_nan() && max[1].is_nan(),
2302            "maximum PROPAGATES NaN — the divergence that makes fmax_ieee distinct"
2303        );
2304
2305        let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2306        assert_eq!(fmin[0], 3.0, "fmin_ieee(NaN,3) suppresses NaN → 3");
2307        assert_eq!(fmin[1], 2.0, "fmin_ieee(2,NaN) suppresses NaN → 2");
2308        assert_eq!(fmin[2], 4.0, "fmin_ieee(5,4) → 4");
2309        let min = a.minimum(&b).unwrap().realize_f32();
2310        assert!(
2311            min[0].is_nan() && min[1].is_nan(),
2312            "minimum PROPAGATES NaN — the divergence that makes fmin_ieee distinct"
2313        );
2314    }
2315
2316    #[test]
2317    fn fmax_fmin_ieee_signed_zero_tie_operand_a_wins_bitwise() {
2318        // KISS Appendix A.3: on a ±0 tie (cmp_ge and cmp_le both true) operand `a`
2319        // (self) wins in all four minmax ops. ⚠️ Asserted on to_bits() — a value
2320        // compare cannot tell +0.0 from -0.0 and would pass VACUOUSLY. Fuel has
2321        // live ±0 tie-bias on CPU (#67)/Vulkan (#76) minmax paths, so if the CPU
2322        // `ge`/`where` path is tie-biased this born-red REVEALS it rather than
2323        // hiding it behind a value compare.
2324        //
2325        // ⚠️ SENSITIVITY PROVEN, not assumed (this test passed on first write, and
2326        // a first-write pass demonstrates nothing about its own sensitivity):
2327        // sabotaging the fmax_ieee decomposition `cmp_ge` → `cmp_gt` flips the tie
2328        // to b-wins and this goes RED with left=0 (+0.0) vs right=0x80000000 (-0.0).
2329        // So the a-wins result below is EARNED — the CPU ge/where path resolves the
2330        // tie a-wins, not tie-biased. Testing BOTH operand orders (each asserting
2331        // the *first* operand's zero) is the permanent discriminator: an order
2332        // swap or a collapse-to-constant flips one side; a return-`a`/return-`b`
2333        // collapse is caught by the sibling NaN test (fmax(NaN,3)=3 needs `b`,
2334        // fmax(2,NaN)=2 needs `a`). GAP-048.
2335        let a = Tensor::from_f32(vec![-0.0, 0.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
2336        let b = a
2337            .const_f32_like(vec![0.0, -0.0], Shape::from_dims(&[2]))
2338            .unwrap();
2339
2340        let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2341        assert_eq!(
2342            fmax[0].to_bits(),
2343            (-0.0f32).to_bits(),
2344            "fmax_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2345        );
2346        assert_eq!(
2347            fmax[1].to_bits(),
2348            (0.0f32).to_bits(),
2349            "fmax_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2350        );
2351
2352        let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2353        assert_eq!(
2354            fmin[0].to_bits(),
2355            (-0.0f32).to_bits(),
2356            "fmin_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2357        );
2358        assert_eq!(
2359            fmin[1].to_bits(),
2360            (0.0f32).to_bits(),
2361            "fmin_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2362        );
2363    }
2364
2365    #[test]
2366    fn rem_trunc_diverges_from_floored_rem_on_opposite_signs() {
2367        // §6.15-0003 divergence born-red. rem_trunc (sign of the DIVIDEND, C99
2368        // fmod) vs rem (floored, sign of the divisor) diverge ONLY when the
2369        // operands have opposite signs — a same-sign fixture is vacuous.
2370        let a = Tensor::from_f32(
2371            vec![-7.0, 7.0, -7.0],
2372            Shape::from_dims(&[3]),
2373            &Device::cpu(),
2374        )
2375        .unwrap();
2376        let b = a
2377            .const_f32_like(vec![3.0, -3.0, -3.0], Shape::from_dims(&[3]))
2378            .unwrap();
2379
2380        let rt = a.rem_trunc(&b).unwrap().realize_f32();
2381        assert_eq!(rt[0], -1.0, "-7 rem_trunc 3 = -1 (sign of dividend)");
2382        assert_eq!(rt[1], 1.0, "7 rem_trunc -3 = 1 (sign of dividend)");
2383        assert_eq!(rt[2], -1.0, "-7 rem_trunc -3 = -1");
2384        let rf = a.rem(&b).unwrap().realize_f32();
2385        assert_eq!(
2386            rf[0], 2.0,
2387            "-7 rem 3 = 2 (floored, sign of divisor) — the divergence from rem_trunc"
2388        );
2389    }
2390
2391    #[test]
2392    fn trunc_edges_signed_zero_nan_inf_bitwise() {
2393        // GAP-300: trunc's expansion (q>=0 ? floor : ceil) is FUEL's own — no KISS
2394        // vector catches an error in it, so its edges are verified HERE. ⚠️ ±0 on
2395        // to_bits() (value compare 0.0 == -0.0 is vacuous).
2396        let q = Tensor::from_f32(
2397            vec![
2398                2.7,
2399                -2.7,
2400                -0.0,
2401                0.0,
2402                f32::NAN,
2403                f32::INFINITY,
2404                f32::NEG_INFINITY,
2405            ],
2406            Shape::from_dims(&[7]),
2407            &Device::cpu(),
2408        )
2409        .unwrap();
2410        let t = q.trunc().realize_f32();
2411        assert_eq!(t[0], 2.0, "trunc(2.7) = 2 (toward zero)");
2412        assert_eq!(t[1], -2.0, "trunc(-2.7) = -2 (toward zero, NOT -3)");
2413        assert_eq!(
2414            t[2].to_bits(),
2415            (-0.0f32).to_bits(),
2416            "trunc(-0.0) must PRESERVE -0.0 (bitwise, not +0.0)"
2417        );
2418        assert_eq!(
2419            t[3].to_bits(),
2420            (0.0f32).to_bits(),
2421            "trunc(+0.0) = +0.0 (bitwise)"
2422        );
2423        assert!(t[4].is_nan(), "trunc(NaN) = NaN");
2424        assert_eq!(t[5], f32::INFINITY, "trunc(+inf) = +inf");
2425        assert_eq!(t[6], f32::NEG_INFINITY, "trunc(-inf) = -inf");
2426    }
2427
2428    #[test]
2429    fn realize_f32_matmul_hand_computed() {
2430        // Classic 2x3 @ 3x2 matmul through the bridge.
2431        let a = Tensor::from_f32(
2432            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2433            Shape::from_dims(&[2, 3]),
2434            &Device::cpu(),
2435        )
2436        .unwrap();
2437        let b = a
2438            .const_f32_like(
2439                vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
2440                Shape::from_dims(&[3, 2]),
2441            )
2442            .unwrap();
2443        let c = a.matmul(&b).unwrap();
2444        assert_eq!(c.shape().dims(), &[2, 2]);
2445        assert_eq!(c.realize_f32(), vec![58.0, 64.0, 139.0, 154.0]);
2446    }
2447
2448    #[test]
2449    fn fast_and_reference_agree_on_medium_matmul() {
2450        // 64 × 96 @ 96 × 32 — bigger than anything we could hand-check
2451        // but small enough to verify every element. The fast path
2452        // goes through gemm, the reference path uses the naive triple
2453        // loop; results should agree within float-rounding tolerance.
2454        let m = 64;
2455        let k = 96;
2456        let n = 32;
2457        let a_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.01).sin()).collect();
2458        let b_data: Vec<f32> = (0..k * n).map(|i| (i as f32 * 0.013).cos()).collect();
2459        let a = Tensor::from_f32(a_data, Shape::from_dims(&[m, k]), &Device::cpu()).unwrap();
2460        let b = a.const_f32_like(b_data, Shape::from_dims(&[k, n])).unwrap();
2461        let c = a.matmul(&b).unwrap();
2462        let fast = c.realize_f32();
2463        let reference = c.realize_f32();
2464        assert_eq!(fast.len(), reference.len());
2465        for (i, (&f, &r)) in fast.iter().zip(&reference).enumerate() {
2466            // Accept either absolute or relative tolerance — gemm's
2467            // blocked accumulation order differs from the naive triple
2468            // loop, so values near zero can have large relative diffs
2469            // on tiny absolute diffs. Both bounds are loose enough for
2470            // float-noise but tight enough to catch real bugs.
2471            let diff = (f - r).abs();
2472            let rel = if r.abs() > 1e-6 { diff / r.abs() } else { 0.0 };
2473            assert!(
2474                diff < 1e-4 || rel < 1e-3,
2475                "at index {i}: fast={f}, reference={r}, diff={diff}, rel={rel}",
2476            );
2477        }
2478    }
2479
2480    /// Reference attention (B=1, multi-head, GQA-aware) in plain Rust:
2481    /// `out = softmax( softcap(scale·QKᵀ) [+ causal -inf] ) · V`. q
2482    /// `[hq,sq,d]`, k/v `[hkv,sk,d]` (GQA: q-head `h` attends kv-head
2483    /// `h / (hq/hkv)`), out `[hq,sq,d]`.
2484    fn ref_attention(
2485        q: &[f32],
2486        k: &[f32],
2487        v: &[f32],
2488        hq: usize,
2489        hkv: usize,
2490        sq: usize,
2491        sk: usize,
2492        d: usize,
2493        scale: f32,
2494        causal: bool,
2495        softcap: Option<f32>,
2496        alibi: Option<&[f32]>,
2497    ) -> Vec<f32> {
2498        let g = hq / hkv;
2499        let mut out = vec![0.0f32; hq * sq * d];
2500        for h in 0..hq {
2501            let hk = h / g;
2502            let qh = &q[h * sq * d..(h + 1) * sq * d];
2503            let kh = &k[hk * sk * d..(hk + 1) * sk * d];
2504            let vh = &v[hk * sk * d..(hk + 1) * sk * d];
2505            for i in 0..sq {
2506                let mut scores = vec![0.0f32; sk];
2507                for j in 0..sk {
2508                    let mut s = 0.0f32;
2509                    for l in 0..d {
2510                        s += qh[i * d + l] * kh[j * d + l];
2511                    }
2512                    let mut sc = scale * s;
2513                    if let Some(cap) = softcap {
2514                        sc = cap * (sc / cap).tanh();
2515                    }
2516                    if let Some(slopes) = alibi {
2517                        // alibi bias = slope[h] · (key_pos - query_pos).
2518                        sc += slopes[h] * (j as f32 - i as f32);
2519                    }
2520                    scores[j] = if causal && j > i {
2521                        f32::NEG_INFINITY
2522                    } else {
2523                        sc
2524                    };
2525                }
2526                let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2527                let mut sum = 0.0f32;
2528                let exps: Vec<f32> = scores
2529                    .iter()
2530                    .map(|&s| {
2531                        let e = (s - m).exp();
2532                        sum += e;
2533                        e
2534                    })
2535                    .collect();
2536                for l in 0..d {
2537                    let mut o = 0.0f32;
2538                    for j in 0..sk {
2539                        o += (exps[j] / sum) * vh[j * d + l];
2540                    }
2541                    out[(h * sq + i) * d + l] = o;
2542                }
2543            }
2544        }
2545        out
2546    }
2547
2548    /// Numerical parity: lower a FlashAttn node to its primitive
2549    /// decomposition, realize it on CPU, and assert it matches the plain-Rust
2550    /// reference — verifying the recipe's *math* (scale·QKᵀ → softmax → ·V),
2551    /// the `Triu` `-inf` causal mask, GQA head-repeat, the `tanh` softcap, and
2552    /// the alibi bias (which is the sole config that lowers to `Op::Iota`).
2553    fn flash_decompose_vs_reference(
2554        hq: usize,
2555        hkv: usize,
2556        causal: bool,
2557        softcap: Option<f32>,
2558        alibi: bool,
2559    ) {
2560        let dev = Device::cpu();
2561        let (sq, sk, d) = (2usize, 2usize, 2usize);
2562        // deterministic, varied inputs so the comparison is meaningful.
2563        let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2564        let k_data: Vec<f32> = (0..hkv * sk * d).map(|i| (i as f32 * 0.13).cos()).collect();
2565        let v_data: Vec<f32> = (0..hkv * sk * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2566        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
2567        // swapping the exact constant would perturb these attention-scale parity tests.
2568        #[allow(clippy::approx_constant)]
2569        let scale = 0.7071f32;
2570        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2571        let k = q
2572            .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2573            .unwrap();
2574        let v = q
2575            .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2576            .unwrap();
2577        // Distinct positive slope per head (powers of 1/2 — the alibi default).
2578        let alibi_slopes: Option<Vec<f32>> = if alibi {
2579            Some((0..hq).map(|h| 0.5f32.powi(h as i32 + 1)).collect())
2580        } else {
2581            None
2582        };
2583        let alibi_t = alibi_slopes.as_ref().map(|s| {
2584            q.const_f32_like(s.clone(), Shape::from_dims(&[hq]))
2585                .unwrap()
2586        });
2587        let attn = q
2588            .flash_attn(&k, &v, alibi_t.as_ref(), scale, causal, None, None, softcap)
2589            .unwrap();
2590
2591        // Decompose explicitly, then realize the primitive subgraph.
2592        let graph = attn.inner.graph().clone();
2593        let id = attn.inner.id();
2594        let roots =
2595            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2596        assert_eq!(roots.len(), 1, "lowering should keep a single root");
2597        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
2598            .expect("realize decomposed FlashAttn on CPU");
2599
2600        let expected = ref_attention(
2601            &q_data,
2602            &k_data,
2603            &v_data,
2604            hq,
2605            hkv,
2606            sq,
2607            sk,
2608            d,
2609            scale,
2610            causal,
2611            softcap,
2612            alibi_slopes.as_deref(),
2613        );
2614        assert_eq!(got.len(), expected.len());
2615        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
2616            assert!(
2617                (g - e).abs() < 1e-4,
2618                "FlashAttn decompose mismatch (hq={hq} hkv={hkv} causal={causal} \
2619                 softcap={softcap:?} alibi={alibi}) at {i}: got {g}, expected {e}",
2620            );
2621        }
2622    }
2623
2624    // ---- FlashAttn on masked and NaN rows (ruling 2026-11-25; every path) ----
2625    // (1) a FULLY MASKED row (no key admitted by causal/window) is ZEROS; (2) a NaN in Q, or in
2626    // K/V at a position the query ATTENDS, makes that output NaN (never swallowed); (3) a NaN in a
2627    // V row whose key is MASKED OUT for a query is UNSPECIFIED: an implementation MAY ignore it (the
2628    // fused CPU kernel) or propagate it (the dense decomposition, Vulkan); the result depends on tile
2629    // geometry, so NO test pins either: the row must not crash and, if it is not NaN, must equal the
2630    // NaN-free reference; (4) normal rows are unaffected in a mixed batch.
2631
2632    struct AttnCase {
2633        name: &'static str,
2634        q: Vec<f32>,
2635        k: Vec<f32>,
2636        v: Vec<f32>,
2637        sq: usize,
2638        sk: usize,
2639        causal: bool,
2640        wl: Option<usize>,
2641    }
2642
2643    fn attn_cases() -> Vec<AttnCase> {
2644        let nan = f32::NAN;
2645        let bq = vec![0.5f32, -0.25, 0.1, 0.9, -0.4, 0.3];
2646        let bk = vec![0.3f32, 0.2, -0.1, 0.6];
2647        let bv = vec![1.0f32, 2.0, 3.0, 4.0];
2648        let c = |name, q: Vec<f32>, k: Vec<f32>, v: Vec<f32>, sq, sk, causal, wl| AttnCase {
2649            name,
2650            q,
2651            k,
2652            v,
2653            sq,
2654            sk,
2655            causal,
2656            wl,
2657        };
2658        vec![
2659            c(
2660                "control",
2661                bq[..4].to_vec(),
2662                bk.clone(),
2663                bv.clone(),
2664                2,
2665                2,
2666                false,
2667                None,
2668            ),
2669            // sq=3 > sk=2, causal, window_left=0: row 2 attends nothing.
2670            c(
2671                "fully-masked-row-mixed",
2672                bq.clone(),
2673                bk.clone(),
2674                bv.clone(),
2675                3,
2676                2,
2677                true,
2678                Some(0),
2679            ),
2680            c(
2681                "nan-q-row1",
2682                vec![0.5, -0.25, nan, 0.9],
2683                bk.clone(),
2684                bv.clone(),
2685                2,
2686                2,
2687                false,
2688                None,
2689            ),
2690            c(
2691                "nan-k-row1",
2692                bq[..4].to_vec(),
2693                vec![0.3, 0.2, nan, 0.6],
2694                bv.clone(),
2695                2,
2696                2,
2697                false,
2698                None,
2699            ),
2700            c(
2701                "nan-v-row1",
2702                bq[..4].to_vec(),
2703                bk.clone(),
2704                vec![1.0, 2.0, nan, 4.0],
2705                2,
2706                2,
2707                false,
2708                None,
2709            ),
2710            // PIP #715 M1: a non-finite score at a MASKED-OUT position must never reach the softmax.
2711            // sq=3 > sk=2, causal, window_left=0: row 2 attends nothing, and its Q is NaN. Contract (1)
2712            // "a fully masked row is zeros" takes precedence over (2) "NaN in Q makes the row NaN":
2713            // nothing is attended, so nothing is poisoned (the fused CPU kernel's result).
2714            c(
2715                "nan-q-fully-masked-row",
2716                vec![0.5, -0.25, 0.1, 0.9, nan, 0.3],
2717                bk.clone(),
2718                bv.clone(),
2719                3,
2720                2,
2721                true,
2722                Some(0),
2723            ),
2724            // Row 0 does not attend key 1 (causal); key 1 is NaN / +inf. Row 0 must be its NaN-free value.
2725            c(
2726                "nan-k-masked-key",
2727                bq[..4].to_vec(),
2728                vec![0.3, 0.2, nan, nan],
2729                bv.clone(),
2730                2,
2731                2,
2732                true,
2733                None,
2734            ),
2735            c(
2736                "inf-k-masked-key",
2737                bq[..4].to_vec(),
2738                vec![0.3, 0.2, f32::INFINITY, f32::INFINITY],
2739                bv.clone(),
2740                2,
2741                2,
2742                true,
2743                None,
2744            ),
2745            c(
2746                "nan-v-masked-key",
2747                bq[..4].to_vec(),
2748                bk.clone(),
2749                vec![1.0, 2.0, nan, 4.0],
2750                2,
2751                2,
2752                true,
2753                None,
2754            ),
2755        ]
2756    }
2757
2758    /// What one output element must be.
2759    #[derive(Debug, Clone, Copy)]
2760    enum Want {
2761        /// Must be NaN.
2762        Nan,
2763        /// Must equal this value within 1e-4.
2764        Val(f32),
2765        /// UNSPECIFIED (contract (3)): NaN is allowed; otherwise it must equal this NaN-free reference.
2766        NanOrVal(f32),
2767        /// Not asserted (the attended non-finite score row: a pre-existing fused/decomposed difference, PIP L1).
2768        Any,
2769    }
2770
2771    fn attn_expected(name: &str) -> Vec<Want> {
2772        use Want::{Any as a, Nan as n, NanOrVal as o, Val as s};
2773        match name {
2774            "control" => vec![s(1.8943309), s(2.894331), s(2.1126559), s(3.1126556)],
2775            "fully-masked-row-mixed" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2776            "nan-q-row1" => vec![s(1.8943309), s(2.894331), n, n],
2777            "nan-k-row1" => vec![n, n, n, n],
2778            "nan-v-row1" => vec![n, s(2.894331), n, s(3.1126556)],
2779            // Row 0 attends only key 0 (the NaN V row is masked out for it): UNSPECIFIED; the
2780            // NaN-free reference is [1, 2]. Row 1 attends the NaN V row: column 0 must be NaN.
2781            "nan-v-masked-key" => vec![o(1.0), o(2.0), n, s(3.1126556)],
2782            "nan-q-fully-masked-row" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2783            "nan-k-masked-key" => vec![s(1.0), s(2.0), n, n],
2784            "inf-k-masked-key" => vec![s(1.0), s(2.0), a, a],
2785            other => panic!("no expectation for {other}"),
2786        }
2787    }
2788
2789    fn attn_check(name: &str, path: &str, got: &[f32], want: &[Want]) -> Option<String> {
2790        assert_eq!(got.len(), want.len(), "{name}/{path}");
2791        let bad: Vec<String> = got
2792            .iter()
2793            .zip(want)
2794            .enumerate()
2795            .filter(|(_, (g, w))| match w {
2796                Want::Nan => !g.is_nan(),
2797                Want::Val(x) => g.is_nan() || (**g - *x).abs() > 1e-4,
2798                Want::NanOrVal(x) => !g.is_nan() && (**g - *x).abs() > 1e-4,
2799                Want::Any => false,
2800            })
2801            .map(|(i, (g, w))| format!("[{i}] got {g} want {w:?}"))
2802            .collect();
2803        (!bad.is_empty()).then(|| format!("{name}/{path}: {}", bad.join("; ")))
2804    }
2805
2806    // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2: the expected values in
2807    // `attn_expected` were computed with exactly 0.7071 (same posture as `flash_decompose_vs_reference`).
2808    #[allow(clippy::approx_constant)]
2809    fn attn_tensor(c: &AttnCase) -> Tensor {
2810        let dev = Device::cpu();
2811        let q = Tensor::from_f32(c.q.clone(), Shape::from_dims(&[1, 1, c.sq, 2]), &dev).unwrap();
2812        let k = q
2813            .const_f32_like(c.k.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2814            .unwrap();
2815        let v = q
2816            .const_f32_like(c.v.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2817            .unwrap();
2818        q.flash_attn(&k, &v, None, 0.7071, c.causal, c.wl, None, None)
2819            .unwrap()
2820    }
2821
2822    #[test]
2823    fn flash_attn_fused_cpu_follows_the_masked_and_nan_row_contract() {
2824        let mut bad = Vec::new();
2825        for c in attn_cases() {
2826            let got = attn_tensor(&c).realize_f32();
2827            bad.extend(attn_check(c.name, "fused", &got, &attn_expected(c.name)));
2828        }
2829        assert!(bad.is_empty(), "{bad:#?}");
2830    }
2831
2832    #[test]
2833    fn flash_attn_decomposed_cpu_follows_the_masked_and_nan_row_contract() {
2834        let mut bad = Vec::new();
2835        for c in attn_cases() {
2836            let attn = attn_tensor(&c);
2837            let graph = attn.inner.graph().clone();
2838            let id = attn.inner.id();
2839            let roots =
2840                fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2841            let got =
2842                crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
2843                    .expect("realize decomposed FlashAttn on CPU");
2844            bad.extend(attn_check(
2845                c.name,
2846                "decomposed",
2847                &got,
2848                &attn_expected(c.name),
2849            ));
2850        }
2851        assert!(bad.is_empty(), "{bad:#?}");
2852    }
2853
2854    #[test]
2855    fn flash_attn_decompose_vanilla() {
2856        flash_decompose_vs_reference(1, 1, false, None, false);
2857    }
2858
2859    #[test]
2860    fn flash_attn_decompose_causal() {
2861        flash_decompose_vs_reference(1, 1, true, None, false);
2862    }
2863
2864    #[test]
2865    fn flash_attn_decompose_gqa_causal() {
2866        flash_decompose_vs_reference(2, 1, true, None, false); // Hq=2, Hkv=1 (head-repeat)
2867    }
2868
2869    #[test]
2870    fn flash_attn_decompose_softcap() {
2871        flash_decompose_vs_reference(1, 1, false, Some(0.5), false); // small cap → tanh saturates
2872    }
2873
2874    #[test]
2875    fn flash_attn_decompose_alibi() {
2876        // alibi is the only config that lowers to Op::Iota (relative-position
2877        // values) — this exercises the new 0-input Iota execution path.
2878        flash_decompose_vs_reference(2, 2, false, None, true);
2879    }
2880
2881    #[test]
2882    fn flash_attn_decompose_alibi_causal() {
2883        flash_decompose_vs_reference(2, 2, true, None, true);
2884    }
2885
2886    /// Plain-Rust reference for **capacity-K decode attention**: attend `q`
2887    /// (`Sq` queries at absolute positions `[kl−Sq, kl)`) against the first
2888    /// `kl` keys/values of a `cap`-capacity KV buffer, with bottom-right
2889    /// causal masking (query `i` attends keys `j ≤ (kl−Sq)+i`). GQA folds
2890    /// `h → h/(Hq/Hkv)`.
2891    fn ref_decode_attn(
2892        q: &[f32],
2893        k: &[f32],
2894        v: &[f32],
2895        hq: usize,
2896        hkv: usize,
2897        sq: usize,
2898        cap: usize,
2899        kl: usize,
2900        d: usize,
2901        scale: f32,
2902        causal: bool,
2903    ) -> Vec<f32> {
2904        let g = hq / hkv;
2905        let offset = kl - sq;
2906        let mut out = vec![0f32; hq * sq * d];
2907        for h in 0..hq {
2908            let hk = h / g;
2909            for i in 0..sq {
2910                let qh = &q[((h * sq) + i) * d..][..d];
2911                let mut scores = vec![f32::NEG_INFINITY; kl];
2912                for j in 0..kl {
2913                    if causal && j > offset + i {
2914                        continue;
2915                    }
2916                    let kh = &k[((hk * cap) + j) * d..][..d];
2917                    let s: f32 = (0..d).map(|l| qh[l] * kh[l]).sum();
2918                    scores[j] = scale * s;
2919                }
2920                let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2921                let mut sum = 0f32;
2922                let exps: Vec<f32> = scores
2923                    .iter()
2924                    .map(|&s| {
2925                        let e = (s - m).exp();
2926                        sum += e;
2927                        e
2928                    })
2929                    .collect();
2930                for l in 0..d {
2931                    let mut o = 0f32;
2932                    for j in 0..kl {
2933                        o += (exps[j] / sum) * v[((hk * cap) + j) * d + l];
2934                    }
2935                    out[(h * sq + i) * d + l] = o;
2936                }
2937            }
2938        }
2939        out
2940    }
2941
2942    /// Recipe principle (G2): a **concrete** `k_len` FlashAttn is a *static*
2943    /// config that used to return self (`k_len.is_some()` short-circuit). It
2944    /// now decomposes: `Slice` K/V to the live prefix and run the SDPA recipe
2945    /// bottom-right-aligned (`q_pos_offset = kl − Sq`). RED before the fix (an
2946    /// `Op::Fused(FLASH_ATTN)` island survives lowering); GREEN after, matching
2947    /// the decode-attention reference. Uses GQA (Hq=2, Hkv=1), Sq=2 (so the
2948    /// offset causal band is exercised, not a Sq=1 no-op), capacity 4, kl=3.
2949    #[test]
2950    fn flash_attn_decompose_concrete_klen() {
2951        use fuel_graph::Op;
2952        use fuel_graph::registry::FusedOps;
2953        use fuel_ir::DynScalar;
2954        let dev = Device::cpu();
2955        let (hq, hkv, sq, cap, kl, d) = (2usize, 1usize, 2usize, 4usize, 3usize, 2usize);
2956        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
2957        // swapping the exact constant would perturb these attention-scale parity tests.
2958        #[allow(clippy::approx_constant)]
2959        let scale = 0.7071f32;
2960        let causal = true;
2961        let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2962        let k_data: Vec<f32> = (0..hkv * cap * d)
2963            .map(|i| (i as f32 * 0.13).cos())
2964            .collect();
2965        let v_data: Vec<f32> = (0..hkv * cap * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2966        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2967        let k = q
2968            .inner
2969            .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2970            .unwrap();
2971        let v = q
2972            .inner
2973            .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2974            .unwrap();
2975        // Concrete k_len — the fused node that formerly returned self.
2976        let attn = q.inner.flash_attn_dyn(
2977            &k,
2978            &v,
2979            None,
2980            scale,
2981            causal,
2982            None,
2983            None,
2984            None,
2985            DynScalar::Concrete(kl),
2986        );
2987
2988        let graph = attn.graph().clone();
2989        let id = attn.id();
2990        let roots =
2991            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2992        assert_eq!(roots.len(), 1, "lowering should keep a single root");
2993
2994        // Born-red discriminator: no Op::Fused(FLASH_ATTN) reachable from the root.
2995        {
2996            let g = graph.read().unwrap();
2997            let mut stack = vec![roots[0]];
2998            let mut seen = std::collections::HashSet::new();
2999            while let Some(nid) = stack.pop() {
3000                if !seen.insert(nid) {
3001                    continue;
3002                }
3003                let node = g.node(nid);
3004                assert!(
3005                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::FLASH_ATTN),
3006                    "concrete-k_len FlashAttn still fused after lowering (self-return)",
3007                );
3008                for &inp in &node.inputs {
3009                    stack.push(inp);
3010                }
3011            }
3012        }
3013
3014        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3015            .expect("realize decomposed concrete-k_len FlashAttn on CPU");
3016        let expected = ref_decode_attn(
3017            &q_data, &k_data, &v_data, hq, hkv, sq, cap, kl, d, scale, causal,
3018        );
3019        assert_eq!(got.len(), expected.len());
3020        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
3021            assert!(
3022                (gv - ev).abs() < 1e-4,
3023                "concrete-k_len decode mismatch at {i}: got {gv}, expected {ev}",
3024            );
3025        }
3026    }
3027
3028    /// Bit-exact comparison of two `f32` slices (via raw bit patterns), so a
3029    /// last-ULP divergence is not masked by `==` and NaNs compare by pattern.
3030    fn assert_f32_bits_eq(got: &[f32], want: &[f32], ctx: &str) {
3031        assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3032        for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3033            assert_eq!(
3034                g.to_bits(),
3035                w.to_bits(),
3036                "{ctx}: bit mismatch at {i}: got {g} (0x{:08x}), want {w} (0x{:08x})",
3037                g.to_bits(),
3038                w.to_bits(),
3039            );
3040        }
3041    }
3042
3043    /// Assert two positive-`f32` slices agree to within `max_ulp` ULPs. Used
3044    /// to document the (migration-orthogonal) 1-ULP gap between a primitive
3045    /// `Div` and the fused kernel's reciprocal-multiply.
3046    fn assert_f32_within_ulp(got: &[f32], want: &[f32], max_ulp: i64, ctx: &str) {
3047        assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3048        for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3049            let d = (g.to_bits() as i64 - w.to_bits() as i64).abs();
3050            assert!(
3051                d <= max_ulp,
3052                "{ctx}: {d} ULP at {i} (> {max_ulp}): got {g} (0x{:08x}), want {w} (0x{:08x})",
3053                g.to_bits(),
3054                w.to_bits(),
3055            );
3056        }
3057    }
3058
3059    /// Real-backend accumulation-order parity for the Increment-C-slice-1
3060    /// "shrink-via-swap" reduce spellings (prior-review nit, I3).
3061    ///
3062    /// The migration parity tests in `fuel-graph`
3063    /// (`*_matches_frozen_legacy`) run BOTH the recipe decompose and the
3064    /// frozen legacy builder through a shared toy-`f64` reference
3065    /// interpreter, so they pin recipe STRUCTURE only and — by construction
3066    /// — cannot exercise the concern that the CPU backend's `SumDim`
3067    /// (reduction chassis `reduce`) and `ReduceSumTo` (chassis `reduce_to`),
3068    /// or `MaxDim` vs `ReduceMaxTo`, might accumulate a last-dim reduction in
3069    /// a DIFFERENT order and diverge in `f32`. The recipe swapped
3070    /// `ReduceSumTo(keepdim)` → `SumDim(last)`+`Unsqueeze` (and the max
3071    /// side likewise), so the two spellings dispatch two DIFFERENT CPU
3072    /// reduce kernels.
3073    ///
3074    /// This realizes both spellings as BARE reduce roots on the ACTUAL CPU
3075    /// backend — a bare reduce cannot re-fuse into a `SoftmaxLastDim`
3076    /// (no surrounding `Div`/`Exp`), and there is no `SumDim`↔`ReduceSumTo`
3077    /// canonicalization, so the two reduce kernels genuinely execute — over
3078    /// data engineered so a left-fold and a right-fold `f32` sum DIFFER,
3079    /// which gives the bit-exact equality real teeth. Result: bit-exact,
3080    /// because both chassis fold every element into its output slot in
3081    /// row-major flat order (`reduce`: `for flat in 0..total_input`;
3082    /// `reduce_to`: `for in_flat in 0..in_elems`).
3083    #[test]
3084    fn reduce_swap_sumdim_vs_reducesumto_bit_exact_on_cpu_backend() {
3085        let dev = Device::cpu();
3086        let (rows, cols) = (2usize, 4usize);
3087        // Each row is order-sensitive in f32 (catastrophic cancellation):
3088        // its left-fold sum differs from its right-fold sum, so bit-exact
3089        // equality of the two spellings is a NON-trivial statement about the
3090        // backend's accumulation order.
3091        let data: Vec<f32> = vec![1e8, 1.0, -1e8, 1.0, 3.0e7, 2.0, -3.0e7, -1.0];
3092
3093        // Independent host references: fold each row left-to-right and
3094        // right-to-left in f32. They disagree — the data is adversarial.
3095        let mut left_fold = vec![0.0f32; rows];
3096        let mut right_fold = vec![0.0f32; rows];
3097        for r in 0..rows {
3098            let row = &data[r * cols..(r + 1) * cols];
3099            let mut acc = 0.0f32;
3100            for &v in row.iter() {
3101                acc += v;
3102            }
3103            left_fold[r] = acc;
3104            let mut acc_r = 0.0f32;
3105            for &v in row.iter().rev() {
3106                acc_r += v;
3107            }
3108            right_fold[r] = acc_r;
3109        }
3110        assert_ne!(
3111            left_fold, right_fold,
3112            "test data must be accumulation-order-sensitive so the parity has teeth",
3113        );
3114
3115        let x = Tensor::from_f32(data.clone(), Shape::from_dims(&[rows, cols]), &dev).unwrap();
3116        // Recipe spelling: rank-reducing SumDim(last) (chassis `reduce`).
3117        let sumdim = x.inner.sum_dim(1);
3118        let got_sumdim = crate::pipelined_bridge::realize_one_as::<f32>(
3119            &sumdim.graph().clone(),
3120            sumdim.id(),
3121            &dev,
3122        )
3123        .expect("realize SumDim(last) on CPU");
3124        // Legacy spelling: ReduceSumTo(keepdim [rows,1]) (chassis `reduce_to`).
3125        let reducesumto = x.inner.reduce_sum_to(Shape::from_dims(&[rows, 1]));
3126        let got_reducesumto = crate::pipelined_bridge::realize_one_as::<f32>(
3127            &reducesumto.graph().clone(),
3128            reducesumto.id(),
3129            &dev,
3130        )
3131        .expect("realize ReduceSumTo(keepdim) on CPU");
3132
3133        // The load-bearing parity: the two reduce kernels agree bit-exactly.
3134        assert_f32_bits_eq(&got_sumdim, &got_reducesumto, "SumDim vs ReduceSumTo");
3135        // Correctness + which order: both equal the row-major left-fold (and,
3136        // because the data is adversarial, NOT the right-fold).
3137        assert_f32_bits_eq(&got_sumdim, &left_fold, "SumDim vs left-fold");
3138
3139        // Max side: MaxDim(last) (chassis `reduce`) vs ReduceMaxTo(keepdim)
3140        // (chassis `reduce_to`). Max is order-independent, but the swap still
3141        // dispatches two DIFFERENT CPU kernels; confirm they agree bit-exactly
3142        // and equal the per-row maximum.
3143        let maxdim = x.inner.max_dim(1);
3144        let got_maxdim = crate::pipelined_bridge::realize_one_as::<f32>(
3145            &maxdim.graph().clone(),
3146            maxdim.id(),
3147            &dev,
3148        )
3149        .expect("realize MaxDim(last) on CPU");
3150        let reducemaxto = x.inner.reduce_max_to(Shape::from_dims(&[rows, 1]));
3151        let got_reducemaxto = crate::pipelined_bridge::realize_one_as::<f32>(
3152            &reducemaxto.graph().clone(),
3153            reducemaxto.id(),
3154            &dev,
3155        )
3156        .expect("realize ReduceMaxTo(keepdim) on CPU");
3157        let row_max: Vec<f32> = (0..rows)
3158            .map(|r| {
3159                data[r * cols..(r + 1) * cols]
3160                    .iter()
3161                    .cloned()
3162                    .fold(f32::NEG_INFINITY, f32::max)
3163            })
3164            .collect();
3165        assert_f32_bits_eq(&got_maxdim, &got_reducemaxto, "MaxDim vs ReduceMaxTo");
3166        assert_f32_bits_eq(&got_maxdim, &row_max, "MaxDim vs per-row max");
3167    }
3168
3169    /// End-to-end real-backend parity for the migrated `SoftmaxLastDim`
3170    /// (Increment C slice 1 pilot, I3). The migration swapped the keepdim
3171    /// reduce spelling `ReduceMaxTo`/`ReduceSumTo(keepdim)` →
3172    /// `MaxDim`/`SumDim(last)` + `Unsqueeze(append)` (the D3 shrink-via-swap).
3173    /// This realizes the WHOLE softmax on the ACTUAL CPU backend two ways and
3174    /// asserts the swap is numerically inert:
3175    /// * RECIPE path — `lowering_only` lowers the fused node to its recipe
3176    ///   (`SumDim`/`MaxDim` spelling) primitive subgraph, then realize it;
3177    /// * LEGACY path — the pre-migration `ReduceMaxTo`/`ReduceSumTo` primitive
3178    ///   subgraph, hand-built here with the same `Sub`/`Exp`/`Div`.
3179    ///
3180    /// The two must be BIT-EXACT: `reduce_swap_…` proves `SumDim`≡`ReduceSumTo`
3181    /// and `MaxDim`≡`ReduceMaxTo` bit-exactly on the CPU backend, and every
3182    /// other node (and the true-`Div` normalize) is identical, so the whole
3183    /// pipeline agrees to the bit. (The runtime-fusion pass does NOT re-fuse
3184    /// either primitive subgraph back to the `SoftmaxLastDim` kernel — see the
3185    /// secondary assertion, which measures the migration-ORTHOGONAL 1-ULP gap
3186    /// between the primitive `Div` and the fused kernel's reciprocal-multiply
3187    /// `e*(1/sum)`.) Adversarial mixed-magnitude rows make it non-trivial.
3188    #[test]
3189    fn softmax_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3190        let dev = Device::cpu();
3191        let (rows, cols) = (3usize, 5usize);
3192        let data: Vec<f32> = (0..rows * cols)
3193            .map(|i| ((i as f32) * 0.37).sin() * 4.0 - (i as f32) * 0.11)
3194            .collect();
3195        let shape = || Shape::from_dims(&[rows, cols]);
3196        let keepdim = || Shape::from_dims(&[rows, 1]);
3197
3198        // RECIPE path: lower the fused node to the recipe (SumDim spelling).
3199        let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3200            .unwrap()
3201            .softmax_last_dim()
3202            .expect("softmax recipe build");
3203        let graph = recipe.inner.graph().clone();
3204        let id = recipe.inner.id();
3205        let roots =
3206            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3207        assert_eq!(roots.len(), 1, "lowering keeps a single root");
3208        let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3209            .expect("realize recipe-decomposed softmax on CPU");
3210
3211        // LEGACY path: the pre-migration ReduceMaxTo/ReduceSumTo(keepdim)
3212        // spelling, hand-built with identical Sub/Exp/Div.
3213        let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3214        let m = x.reduce_max_to(keepdim());
3215        let mb = m.broadcast_to(shape());
3216        let s = x.sub(&mb);
3217        let e = s.exp();
3218        let d = e.reduce_sum_to(keepdim());
3219        let db = d.broadcast_to(shape());
3220        let legacy = e.div(&db);
3221        let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3222            &legacy.graph().clone(),
3223            legacy.id(),
3224            &dev,
3225        )
3226        .expect("realize legacy softmax on CPU");
3227
3228        // PRIMARY: the migration is numerically inert — bit-exact.
3229        assert_f32_bits_eq(&recipe_out, &legacy_out, "softmax recipe vs legacy");
3230        // Sanity: it is a real softmax (each row sums to ~1).
3231        for r in 0..rows {
3232            let sum: f32 = recipe_out[r * cols..(r + 1) * cols].iter().sum();
3233            assert!((sum - 1.0).abs() < 1e-5, "row {r} softmax sum = {sum}");
3234        }
3235
3236        // SECONDARY (documentation): the fused/production kernel differs by
3237        // at most 1 ULP — NOT from the migration but from its reciprocal-
3238        // multiply normalize (`e*(1/sum)`) vs the primitive true-`Div`.
3239        let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3240            .unwrap()
3241            .softmax_last_dim()
3242            .expect("softmax fused build")
3243            .realize_f32();
3244        assert_f32_within_ulp(&recipe_out, &fused_out, 1, "softmax recipe vs fused kernel");
3245    }
3246
3247    /// End-to-end real-backend parity for the migrated `RmsNormLastDim`
3248    /// (Increment C slice 1, T7, I3) — the norm counterpart of
3249    /// `softmax_last_dim_recipe_decompose_matches_legacy_on_cpu`. Here the D3
3250    /// shrink-via-swap replaced the keepdim `Reshape` with `Unsqueeze`
3251    /// (append) while the reducing `MeanDim(last)` is UNCHANGED, so the swap
3252    /// is metadata-only; the recipe-decompose realize must match a hand-built
3253    /// legacy `Reshape`-keepdim subgraph bit-exactly on the CPU backend.
3254    #[test]
3255    fn rms_norm_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3256        let dev = Device::cpu();
3257        let (rows, cols) = (3usize, 6usize);
3258        let eps = 1e-6f64;
3259        let data: Vec<f32> = (0..rows * cols)
3260            .map(|i| ((i as f32) * 0.29).cos() * 2.5 + 0.5)
3261            .collect();
3262        let shape = || Shape::from_dims(&[rows, cols]);
3263        let keepdim = || Shape::from_dims(&[rows, 1]);
3264
3265        // RECIPE path: lower the fused node (MeanDim + Unsqueeze spelling).
3266        let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3267            .unwrap()
3268            .rms_norm_last_dim(eps)
3269            .expect("rms_norm recipe build");
3270        let graph = recipe.inner.graph().clone();
3271        let id = recipe.inner.id();
3272        let roots =
3273            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3274        assert_eq!(roots.len(), 1, "lowering keeps a single root");
3275        let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3276            .expect("realize recipe-decomposed rms_norm on CPU");
3277
3278        // LEGACY path: MeanDim(last) + Reshape-keepdim spelling, same eps and
3279        // same true-`Div` normalize.
3280        let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3281        let sq = x.sqr();
3282        let mean = sq.mean_dim(1);
3283        let mean_kd = mean.reshape(keepdim());
3284        let denom_sq = mean_kd.add_scalar(eps);
3285        let denom = denom_sq.sqrt();
3286        let denom_b = denom.broadcast_to(shape());
3287        let legacy = x.div(&denom_b);
3288        let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3289            &legacy.graph().clone(),
3290            legacy.id(),
3291            &dev,
3292        )
3293        .expect("realize legacy rms_norm on CPU");
3294
3295        // PRIMARY: the keepdim swap is metadata-only — bit-exact.
3296        assert_f32_bits_eq(&recipe_out, &legacy_out, "rms_norm recipe vs legacy");
3297
3298        // SECONDARY (documentation): the fused kernel's reciprocal-multiply
3299        // (`x*rms_inv`) differs from the primitive true-`Div` by ≤1 ULP.
3300        let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3301            .unwrap()
3302            .rms_norm_last_dim(eps)
3303            .expect("rms_norm fused build")
3304            .realize_f32();
3305        assert_f32_within_ulp(
3306            &recipe_out,
3307            &fused_out,
3308            1,
3309            "rms_norm recipe vs fused kernel",
3310        );
3311    }
3312
3313    /// Recipe principle (G2/G3 — part 1): SelectiveScan is the constitution's
3314    /// canonical **basis gap** (a higher-order `Scan` primitive). Fuel now HAS
3315    /// that primitive (`Op::Scan`), so `decompose` lowers to it — closing G3.
3316    /// This test flips the former surfaced-gap posture: (a) NON-REGRESSION —
3317    /// the fused CPU kernel still realizes `y = 12`; (b) VERIFICATION —
3318    /// `lowering_only` leaves NO `Op::Fused(SELECTIVE_SCAN)`, an `Op::Scan`
3319    /// terminal is present, and `unroll_scan` + realize of the ys oracle
3320    /// contains `y = 12` (`h = 3`). The fused kernel remains the executed
3321    /// production path; the `Op::Scan` recipe is the optimizer base-map cover
3322    /// + the numeric verify oracle.
3323    #[test]
3324    fn selective_scan_decompose_lowers_to_scan_and_matches() {
3325        use fuel_graph::Op;
3326        use fuel_graph::registry::FusedOps;
3327        let dev = Device::cpu();
3328        let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3329        let delta = u
3330            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3331            .unwrap();
3332        let a = u
3333            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3334            .unwrap();
3335        let b = u
3336            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3337            .unwrap();
3338        let c = u
3339            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3340            .unwrap();
3341        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ false);
3342
3343        // (a) NON-REGRESSION: the fused kernel still runs and produces 12.0.
3344        let got = y.realize_f32();
3345        assert_eq!(got.len(), 1);
3346        assert!((got[0] - 12.0).abs() < 1e-4, "fused kernel y: {}", got[0]);
3347
3348        // (b) VERIFICATION: lowering leaves NO Op::Fused(SELECTIVE_SCAN); an
3349        // Op::Scan terminal is present; unroll+realize matches h=3,y=12.
3350        let graph = y.inner.graph().clone();
3351        let id = y.inner.id();
3352        let roots =
3353            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3354        assert_eq!(roots.len(), 1);
3355        let scan_id = {
3356            let g = graph.read().unwrap();
3357            let mut stack = vec![roots[0]];
3358            let mut seen = std::collections::HashSet::new();
3359            let mut scan_id = None;
3360            while let Some(nid) = stack.pop() {
3361                if !seen.insert(nid) {
3362                    continue;
3363                }
3364                let node = g.node(nid);
3365                assert!(
3366                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SELECTIVE_SCAN),
3367                    "SelectiveScan must lower to Op::Scan, not remain fused"
3368                );
3369                if matches!(node.op, Op::Scan { .. }) {
3370                    scan_id = Some(nid);
3371                }
3372                for &inp in &node.inputs {
3373                    stack.push(inp);
3374                }
3375            }
3376            scan_id.expect("an Op::Scan terminal must be present after lowering")
3377        };
3378        // Unroll the Op::Scan (seqlen = 1) and realize the ys oracle.
3379        let ys = {
3380            let mut g = graph.write().unwrap();
3381            fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3382                .expect("unroll")
3383                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3384        };
3385        let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3386            .expect("realize unrolled selective_scan oracle on CPU");
3387        assert!(
3388            oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3389            "unroll oracle must contain y = 12, got {oracle:?}"
3390        );
3391    }
3392
3393    /// Recipe principle (G2/G3 — part 2): SsdChunkScan (Mamba-2's State-Space
3394    /// Duality scan) was the constitution's twin **basis gap** to SelectiveScan.
3395    /// Fuel now HAS the higher-order `Op::Scan` primitive, so `decompose` lowers
3396    /// to it — closing G3 part 2. The SSD recurrence carries a per-head SCALAR
3397    /// gate `exp(dt·a_h)` (`a` is `[heads]`, broadcast across the whole
3398    /// `head_dim×state_dim` block), with NO softplus. This test mirrors the
3399    /// SelectiveScan gate test: (a) NON-REGRESSION — the fused CPU kernel still
3400    /// realizes `y = 12`; (b) VERIFICATION — `lowering_only` leaves NO
3401    /// `Op::Fused(SSD_CHUNK_SCAN)`, an `Op::Scan` terminal is present, and
3402    /// `unroll_scan` + realize of the ys oracle contains `y = 12`.
3403    /// Fixture (batch=heads=head_dim=state_dim=1, seqlen=chunk_size=1):
3404    /// `x=2, dt=0.5, a=-1, b=3, c=4` → `exp(0.5·-1)·0 + 0.5·3·2 = 3`, `y = 3·4 = 12`.
3405    #[test]
3406    fn ssd_chunk_scan_decompose_lowers_to_scan_and_matches() {
3407        use fuel_graph::Op;
3408        use fuel_graph::registry::FusedOps;
3409        let dev = Device::cpu();
3410        // x [batch, seqlen, heads, head_dim] = [1,1,1,1]; dt [b,s,h]=[1,1,1];
3411        // a [heads]=[1]; b/c [b,s,h,state]=[1,1,1,1].
3412        let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3413        let dt = x
3414            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3415            .unwrap();
3416        let a = x
3417            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3418            .unwrap();
3419        let b = x
3420            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3421            .unwrap();
3422        let c = x
3423            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3424            .unwrap();
3425        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, /* chunk_size */ 1);
3426
3427        // (a) NON-REGRESSION: the fused kernel still runs and produces 12.0.
3428        let got = y.realize_f32();
3429        assert!(
3430            (got[0] - 12.0).abs() < 1e-4,
3431            "fused ssd kernel y: {}",
3432            got[0]
3433        );
3434
3435        // (b) VERIFICATION: lowering leaves NO Op::Fused(SSD_CHUNK_SCAN); an
3436        // Op::Scan terminal is present; unroll+realize matches h=3, y=12.
3437        let graph = y.inner.graph().clone();
3438        let id = y.inner.id();
3439        let roots =
3440            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3441        let scan_id = {
3442            let g = graph.read().unwrap();
3443            let mut stack = vec![roots[0]];
3444            let mut seen = std::collections::HashSet::new();
3445            let mut scan_id = None;
3446            while let Some(nid) = stack.pop() {
3447                if !seen.insert(nid) {
3448                    continue;
3449                }
3450                let node = g.node(nid);
3451                assert!(
3452                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SSD_CHUNK_SCAN),
3453                    "SsdChunkScan must lower to Op::Scan, not remain fused"
3454                );
3455                if matches!(node.op, Op::Scan { .. }) {
3456                    scan_id = Some(nid);
3457                }
3458                for &inp in &node.inputs {
3459                    stack.push(inp);
3460                }
3461            }
3462            scan_id.expect("an Op::Scan terminal must be present after lowering")
3463        };
3464        let ys = {
3465            let mut g = graph.write().unwrap();
3466            fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3467                .expect("unroll")
3468                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3469        };
3470        let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3471            .expect("realize unrolled ssd_chunk_scan oracle on CPU");
3472        assert!(
3473            oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3474            "oracle y=12, got {oracle:?}"
3475        );
3476    }
3477
3478    // ---- Op::Scan Phase 2 (C3/C4/C5): numeric BPTT finite-difference gates ---
3479    //
3480    // Prove the lower_scans_for_backward pre-pass gradients are correct against
3481    // finite differences over the SAME unrolled graph (self-consistent, decoupled
3482    // from kernel F64-accumulate parity). These need realize, so they live here.
3483
3484    #[test]
3485    fn affine_scan_bptt_matches_finite_difference() {
3486        use fuel_graph::{Node, NodeHandle, Op, ScanEmit, ScanRole};
3487        use fuel_ir::{DType, Shape};
3488        let dev = Device::cpu();
3489        // f(init, a, b): carry_{t+1} = a*carry_t + b, carry_0 = init, bound = 3, loss = carry_3.
3490        // Closed form: carry_3 = a^3*init + b*(a^2 + a + 1). d/dinit = a^3.
3491        let build = |init_v: f32,
3492                     a_v: f32,
3493                     b_v: f32|
3494         -> (
3495            std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
3496            fuel_graph::NodeId,
3497            fuel_graph::NodeHandle,
3498            fuel_graph::NodeHandle,
3499            fuel_graph::NodeHandle,
3500        ) {
3501            let init =
3502                NodeHandle::from_f32(vec![init_v], Shape::from_dims(&[1]), dev.as_dyn()).unwrap();
3503            let g = init.graph().clone();
3504            let a = NodeHandle::from_existing(g.clone(), init.id())
3505                .const_f32_like(vec![a_v], Shape::from_dims(&[1]))
3506                .unwrap();
3507            let b = NodeHandle::from_existing(g.clone(), init.id())
3508                .const_f32_like(vec![b_v], Shape::from_dims(&[1]))
3509                .unwrap();
3510            let nc = {
3511                let mut gw = g.write().unwrap();
3512                let s = Shape::from_dims(&[1]);
3513                let hole = gw.push(Node {
3514                    op: Op::ScanPlaceholder {
3515                        role: ScanRole::Carry,
3516                        index: 0,
3517                    },
3518                    inputs: vec![],
3519                    shape: s.clone(),
3520                    dtype: DType::F32,
3521                });
3522                let ac = gw.push(Node {
3523                    op: Op::Mul,
3524                    inputs: vec![a.id(), hole],
3525                    shape: s.clone(),
3526                    dtype: DType::F32,
3527                });
3528                gw.push(Node {
3529                    op: Op::Add,
3530                    inputs: vec![ac, b.id()],
3531                    shape: s.clone(),
3532                    dtype: DType::F32,
3533                })
3534            };
3535            let nc_t = NodeHandle::from_existing(g.clone(), nc);
3536            let out = init
3537                .scan(
3538                    &[],
3539                    &[a.clone(), b.clone()],
3540                    &nc_t,
3541                    &nc_t,
3542                    3,
3543                    ScanEmit::Final,
3544                )
3545                .expect("scan");
3546            (g, out.id(), init, a, b)
3547        };
3548        // Forward value via unroll+realize (self-consistent oracle).
3549        let fwd = |init_v: f32, a_v: f32, b_v: f32| -> f32 {
3550            let (g, out_id, _i, _a, _b) = build(init_v, a_v, b_v);
3551            let scan_id = {
3552                let gr = g.read().unwrap();
3553                gr.node(out_id).inputs[0]
3554            };
3555            let carry = {
3556                let mut gw = g.write().unwrap();
3557                fuel_graph::scan::unroll_scan(&mut gw, scan_id, 3)
3558                    .expect("unroll")
3559                    .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3560            }; // emit=Final -> selected=final_carry
3561            crate::pipelined_bridge::realize_one_as::<f32>(&g, carry, &dev).expect("realize")[0]
3562        };
3563        // Autograd grad w.r.t. init at (1.0, 0.5, 0.1).
3564        let (g, out_id, init, a, b) = build(1.0, 0.5, 0.1);
3565        let out = fuel_graph::NodeHandle::from_existing(g.clone(), out_id);
3566        let grads = out.backward();
3567        let realize_grad = |t: &fuel_graph::NodeHandle| {
3568            crate::pipelined_bridge::realize_one_as::<f32>(
3569                &g,
3570                grads.get(t).expect("grad").id(),
3571                &dev,
3572            )
3573            .expect("realize grad")[0]
3574        };
3575        let g_init = realize_grad(&init);
3576        let g_a = realize_grad(&a);
3577        let g_b = realize_grad(&b);
3578        // Central finite differences.
3579        let h = 1e-3f32;
3580        let fd = |dinit: f32, da: f32, db: f32| {
3581            (fwd(1.0 + dinit, 0.5 + da, 0.1 + db) - fwd(1.0 - dinit, 0.5 - da, 0.1 - db))
3582                / (2.0 * h)
3583        };
3584        assert!(
3585            (g_init - fd(h, 0.0, 0.0)).abs() < 2e-2,
3586            "d/dinit: autograd {g_init} vs FD {}",
3587            fd(h, 0.0, 0.0)
3588        );
3589        assert!(
3590            (g_a - fd(0.0, h, 0.0)).abs() < 2e-2,
3591            "d/da: autograd {g_a} vs FD {}",
3592            fd(0.0, h, 0.0)
3593        );
3594        assert!(
3595            (g_b - fd(0.0, 0.0, h)).abs() < 2e-2,
3596            "d/db: autograd {g_b} vs FD {}",
3597            fd(0.0, 0.0, h)
3598        );
3599    }
3600
3601    #[test]
3602    fn selective_scan_is_differentiable_backward_matches_fd() {
3603        let dev = Device::cpu();
3604        let fwd = |u_v: f32| -> f32 {
3605            let u = Tensor::from_f32(vec![u_v], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3606            let delta = u
3607                .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3608                .unwrap();
3609            let a = u
3610                .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3611                .unwrap();
3612            let b = u
3613                .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3614                .unwrap();
3615            let c = u
3616                .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3617                .unwrap();
3618            u.selective_scan(&delta, &a, &b, &c, false).realize_f32()[0]
3619        };
3620        // Autograd at u=2.0.
3621        let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3622        let delta = u
3623            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3624            .unwrap();
3625        let a = u
3626            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3627            .unwrap();
3628        let b = u
3629            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3630            .unwrap();
3631        let c = u
3632            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3633            .unwrap();
3634        let y = u.selective_scan(&delta, &a, &b, &c, false);
3635        let grads = y.inner.backward();
3636        let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3637        let g_u =
3638            crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3639                .expect("realize")[0];
3640        let h = 1e-3;
3641        let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3642        assert!(
3643            (g_u - fd).abs() < 5e-2,
3644            "selective_scan d/du: autograd {g_u} vs FD {fd}"
3645        );
3646    }
3647
3648    #[test]
3649    fn ssd_chunk_scan_is_differentiable_backward_matches_fd() {
3650        let dev = Device::cpu();
3651        // x [batch,seqlen,heads,head_dim]=[1,1,1,1]; dt [b,s,h]=[1,1,1]; a [heads]=[1];
3652        // b/c [b,s,h,state]=[1,1,1,1]. Single step: h = dt*b*x = 1.5x, y = c*h = 6x (linear).
3653        let fwd = |x_v: f32| -> f32 {
3654            let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3655            let dt = x
3656                .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3657                .unwrap();
3658            let a = x
3659                .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3660                .unwrap();
3661            let b = x
3662                .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3663                .unwrap();
3664            let c = x
3665                .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3666                .unwrap();
3667            x.ssd_chunk_scan(&dt, &a, &b, &c, 1).realize_f32()[0]
3668        };
3669        // Autograd at x=2.0.
3670        let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3671        let dt = x
3672            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3673            .unwrap();
3674        let a = x
3675            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3676            .unwrap();
3677        let b = x
3678            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3679            .unwrap();
3680        let c = x
3681            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3682            .unwrap();
3683        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3684        let grads = y.inner.backward();
3685        let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
3686        let g_x =
3687            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
3688                .expect("realize")[0];
3689        let h = 1e-3;
3690        let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3691        assert!(
3692            (g_x - fd).abs() < 5e-2,
3693            "ssd_chunk_scan d/dx: autograd {g_x} vs FD {fd}"
3694        );
3695    }
3696
3697    /// Autograd gradient of `act(x)` at a scalar `x`, and the central finite
3698    /// difference of the functional forward at the same point.
3699    fn act_grad_and_fd(
3700        x_v: f32,
3701        act: impl Fn(&Tensor) -> Tensor,
3702        fd_act: impl Fn(&Tensor) -> Tensor,
3703    ) -> (f32, f32) {
3704        let dev = Device::cpu();
3705        let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1]), &dev).unwrap();
3706        let y = act(&x);
3707        let grads = y.inner.backward();
3708        let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3709        let g =
3710            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3711                .expect("realize")[0];
3712        let fwd = |v: f32| -> f32 {
3713            let t = Tensor::from_f32(vec![v], Shape::from_dims(&[1]), &dev).unwrap();
3714            fd_act(&t).realize_f32()[0]
3715        };
3716        let h = 1e-2f32;
3717        (g, (fwd(x_v + h) - fwd(x_v - h)) / (2.0 * h))
3718    }
3719
3720    /// GeluTanh backward used to panic ("inference-only"); it must now match
3721    /// the finite difference of the forward across the curve, including the
3722    /// negative lobe and x = 0.
3723    #[test]
3724    fn gelu_tanh_backward_matches_finite_difference() {
3725        for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3726            let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh(), |x| x.gelu_tanh());
3727            assert!(
3728                (g - fd).abs() < 2e-3,
3729                "gelu_tanh d/dx at {x_v}: autograd {g} vs FD {fd}"
3730            );
3731        }
3732    }
3733
3734    /// Same gradient through the in-place op (its input is read pre-mutation).
3735    #[test]
3736    fn gelu_tanh_inplace_backward_matches_finite_difference() {
3737        for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3738            let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh_inplace(), |x| x.gelu_tanh());
3739            assert!(
3740                (g - fd).abs() < 2e-3,
3741                "gelu_tanh_inplace d/dx at {x_v}: autograd {g} vs FD {fd}"
3742            );
3743        }
3744    }
3745
3746    /// Retained sabotage sibling: the finite-difference harness must be able to
3747    /// tell GeluTanh's derivative from a wrong one. SiLU's autograd gradient is
3748    /// checked against GeluTanh's FD at a point where they differ by far more
3749    /// than the tolerance above; if this ever passes the tolerance the two
3750    /// gates above have gone vacuous.
3751    #[test]
3752    fn finite_difference_harness_rejects_a_wrong_activation_gradient() {
3753        let (g_silu, fd_gelu) = act_grad_and_fd(-1.5, |x| x.silu(), |x| x.gelu_tanh());
3754        assert!(
3755            (g_silu - fd_gelu).abs() > 2e-2,
3756            "silu grad {g_silu} too close to gelu_tanh FD {fd_gelu}: harness cannot discriminate"
3757        );
3758    }
3759
3760    /// Autograd gradient of `sum(build(x))` wrt the input `x` and its central
3761    /// finite difference, per element. `build` receives the differentiated
3762    /// input (a graph leaf) and must build every other operand on its graph.
3763    fn grad_vs_fd(
3764        x_vals: &[f32],
3765        x_shape: &[usize],
3766        build: impl Fn(&Tensor) -> Tensor,
3767    ) -> (Vec<f32>, Vec<f32>) {
3768        grad_vs_fd_impl(x_vals, x_shape, build, false)
3769    }
3770
3771    /// As [`grad_vs_fd`], for a fused op with no backend kernel: the FORWARD
3772    /// values are realized after lowering the fused node to primitives.
3773    fn grad_vs_fd_lowered(
3774        x_vals: &[f32],
3775        x_shape: &[usize],
3776        build: impl Fn(&Tensor) -> Tensor,
3777    ) -> (Vec<f32>, Vec<f32>) {
3778        grad_vs_fd_impl(x_vals, x_shape, build, true)
3779    }
3780
3781    fn grad_vs_fd_impl(
3782        x_vals: &[f32],
3783        x_shape: &[usize],
3784        build: impl Fn(&Tensor) -> Tensor,
3785        lower_forward: bool,
3786    ) -> (Vec<f32>, Vec<f32>) {
3787        let dev = Device::cpu();
3788        let x = Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3789        let y = build(&x);
3790        let grads = y.inner.backward();
3791        let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3792        let g =
3793            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3794                .expect("realize");
3795        let fwd_sum = |vals: &[f32]| -> f32 {
3796            let t = Tensor::from_f32(vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3797            let y = build(&t);
3798            if lower_forward {
3799                let graph = y.inner.graph().clone();
3800                let roots = fuel_graph::opt::RuleRegistry::lowering_only()
3801                    .optimize_to_fixpoint(&graph, &[y.inner.id()]);
3802                crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3803                    .expect("realize lowered forward")
3804                    .iter()
3805                    .sum()
3806            } else {
3807                y.realize_f32().iter().sum()
3808            }
3809        };
3810        let h = 1e-2f32;
3811        let fd = (0..x_vals.len())
3812            .map(|i| {
3813                let (mut p, mut m) = (x_vals.to_vec(), x_vals.to_vec());
3814                p[i] += h;
3815                m[i] -= h;
3816                (fwd_sum(&p) - fwd_sum(&m)) / (2.0 * h)
3817            })
3818            .collect();
3819        (g, fd)
3820    }
3821
3822    fn assert_grad_close(label: &str, g: &[f32], fd: &[f32]) {
3823        assert_eq!(g.len(), fd.len(), "{label}: length");
3824        for (i, (a, b)) in g.iter().zip(fd).enumerate() {
3825            assert!(
3826                (a - b).abs() < 5e-3 + 5e-3 * b.abs(),
3827                "{label}[{i}]: autograd {a} vs FD {b}"
3828            );
3829        }
3830    }
3831
3832    /// A fused op with no hand-written backward arm used to reach the "no
3833    /// backward arm wired yet" panic. Its total `decompose` is differentiable,
3834    /// so the backward pre-pass now lowers it first (ROADMAP item 17, H11).
3835    #[test]
3836    fn nf4_matmul_activation_gradient_matches_finite_difference() {
3837        let (g, fd) = grad_vs_fd(&[1.0, 2.0, 2.0, 4.0], &[1, 4], |act| {
3838            let w_packed = Tensor::from_graph_tensor(
3839                act.graph_tensor()
3840                    .const_u8_like(vec![247_u8, 247, 127, 127], Shape::from_dims(&[2, 2]))
3841                    .unwrap(),
3842            );
3843            let absmax = act
3844                .const_f32_like(vec![1.0_f32, 2.0, 10.0, 20.0], Shape::from_dims(&[2, 2]))
3845                .unwrap();
3846            act.nf4_matmul(&w_packed, &absmax, 2)
3847        });
3848        assert_grad_close("nf4_matmul d/dact", &g, &fd);
3849    }
3850
3851    /// AWQ: arbitrary packed words are valid data (any nibble is a code), so a
3852    /// fixed set of words exercises the decompose's dequantize-then-matmul
3853    /// path under autograd. Kernel layout: `K = 64`, `group_size = 64`
3854    /// (`zeros_w = 2`), `N = 8`.
3855    #[test]
3856    fn awq_matmul_activation_gradient_matches_finite_difference() {
3857        let x_vals: Vec<f32> = (0..64).map(|k| ((k * 7) % 13) as f32 * 0.1 - 0.6).collect();
3858        let (g, fd) = grad_vs_fd_lowered(&x_vals, &[1, 64], |act| {
3859            let words: Vec<u32> = (0..64u32)
3860                .map(|i| i.wrapping_mul(0x9E37_79B1) ^ 0x1234_5678)
3861                .collect();
3862            let weight = act
3863                .graph_tensor()
3864                .const_u32_like(words, Shape::from_dims(&[8, 8]))
3865                .unwrap();
3866            let zeros = act
3867                .graph_tensor()
3868                .const_u32_like(vec![0x7777_7777; 16], Shape::from_dims(&[8, 2]))
3869                .unwrap();
3870            let scales: Vec<half::f16> = (0..128)
3871                .map(|i| half::f16::from_f32(0.05 + 0.01 * (i % 7) as f32))
3872                .collect();
3873            let scales = act
3874                .const_f16_like(scales, Shape::from_dims(&[8, 16]))
3875                .unwrap();
3876            Tensor::from_graph_tensor(act.graph_tensor().awq_matmul(
3877                &weight,
3878                &zeros,
3879                scales.graph_tensor(),
3880                64,
3881                8,
3882            ))
3883        });
3884        assert_grad_close("awq_matmul d/dact", &g, &fd);
3885    }
3886
3887    #[test]
3888    fn causal_conv1d_weight_and_bias_gradients_match_finite_difference() {
3889        let x_data = vec![0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7];
3890        for use_silu in [false, true] {
3891            // d/dweight: weight is the differentiated leaf.
3892            let (g, fd) = grad_vs_fd(&[0.5, -0.25, 0.75, 0.1, 0.9, -0.4], &[2, 1, 3], |w| {
3893                let x = w
3894                    .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3895                    .unwrap();
3896                let b = w
3897                    .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3898                    .unwrap();
3899                x.causal_conv1d(w, &b, use_silu)
3900            });
3901            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dw"), &g, &fd);
3902            // d/dbias.
3903            let (g, fd) = grad_vs_fd(&[0.05, -0.05], &[2], |b| {
3904                let x = b
3905                    .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3906                    .unwrap();
3907                let w = b
3908                    .const_f32_like(
3909                        vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3910                        Shape::from_dims(&[2, 1, 3]),
3911                    )
3912                    .unwrap();
3913                x.causal_conv1d(&w, b, use_silu)
3914            });
3915            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dbias"), &g, &fd);
3916        }
3917    }
3918
3919    #[test]
3920    fn causal_conv1d_input_gradient_matches_finite_difference() {
3921        // x [1, 2, 4] (channels 2, seq 2, kernel 3 -> left-padded length 4).
3922        for use_silu in [false, true] {
3923            let (g, fd) = grad_vs_fd(
3924                &[0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7],
3925                &[1, 2, 4],
3926                |x| {
3927                    let w = x
3928                        .const_f32_like(
3929                            vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3930                            Shape::from_dims(&[2, 1, 3]),
3931                        )
3932                        .unwrap();
3933                    let b = x
3934                        .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3935                        .unwrap();
3936                    x.causal_conv1d(&w, &b, use_silu)
3937                },
3938            );
3939            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dx"), &g, &fd);
3940        }
3941    }
3942
3943    // Review Fix 2: the seqlen=1 SSM gates above multiply exp(dt*a) by a zero
3944    // initial carry, so `y` is linear in the input and the multi-step recurrent
3945    // gate is never FD-checked for the SSM ops. These seqlen>=2 gates carry a
3946    // NON-ZERO h across steps (a < 0), so d(sum y)/d(early input) flows THROUGH
3947    // the gate exp(dt*a) — the multi-step BPTT the headline SSM deliverable needs.
3948
3949    #[test]
3950    fn selective_scan_seqlen2_bptt_matches_finite_difference() {
3951        let dev = Device::cpu();
3952        // u/delta [batch,seqlen,dim]=[1,2,1]; a [dim,dstate]=[1,1] (< 0, stable gate);
3953        // b/c [batch,seqlen,dstate]=[1,2,1]. loss = sum(y) (ones-seed over [1,2,1]).
3954        let fwd = |u_vals: &[f32]| -> f32 {
3955            let u = Tensor::from_f32(u_vals.to_vec(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3956            let delta = u
3957                .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3958                .unwrap();
3959            let a = u
3960                .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3961                .unwrap();
3962            let b = u
3963                .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3964                .unwrap();
3965            let c = u
3966                .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3967                .unwrap();
3968            u.selective_scan(&delta, &a, &b, &c, false)
3969                .realize_f32()
3970                .iter()
3971                .sum()
3972        };
3973        let u0 = vec![1.0f32, 2.0];
3974        let u = Tensor::from_f32(u0.clone(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3975        let delta = u
3976            .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3977            .unwrap();
3978        let a = u
3979            .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3980            .unwrap();
3981        let b = u
3982            .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3983            .unwrap();
3984        let c = u
3985            .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3986            .unwrap();
3987        let y = u.selective_scan(&delta, &a, &b, &c, false);
3988        let grads = y.inner.backward(); // ones-seed over [1,2,1] == grad of sum(y)
3989        let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3990        let g_u =
3991            crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3992                .expect("realize");
3993        // FD over u_1 (index 0): d(sum y)/d u_1 = dB + c*exp(dt*a)*dB — the second
3994        // term is the recurrent gate carrying u_1 into y_2.
3995        let h = 1e-3f32;
3996        let mut up = u0.clone();
3997        up[0] += h;
3998        let mut um = u0.clone();
3999        um[0] -= h;
4000        let fd0 = (fwd(&up) - fwd(&um)) / (2.0 * h);
4001        assert!(
4002            (g_u[0] - fd0).abs() < 5e-2,
4003            "selective_scan seqlen2 dL/du_1: autograd {} vs FD {fd0}",
4004            g_u[0]
4005        );
4006        // Non-triviality: the gate contribution makes this strictly > the pure-dB
4007        // seqlen=1 grad — a real, non-vacuous multi-step gradient (~1.19 here).
4008        assert!(
4009            g_u[0].abs() > 0.5,
4010            "recurrent-gate grad must be non-trivial, got {g_u:?}"
4011        );
4012    }
4013
4014    #[test]
4015    fn ssd_chunk_scan_seqlen4_chunk2_bptt_matches_finite_difference() {
4016        let dev = Device::cpu();
4017        // seqlen=4, chunk=2 -> a 2-CHUNK Op::Scan (bound=2): the inter-chunk state
4018        // carry passes exp(dt*a) across chunks. x [b,s,h,hd]=[1,4,1,1]; dt [b,s,h]=[1,4,1];
4019        // a [heads]=[1] (< 0); b/c [b,s,h,state]=[1,4,1,1].
4020        let fwd = |x_vals: &[f32]| -> f32 {
4021            let x =
4022                Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4023            let dt = x
4024                .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4025                .unwrap();
4026            let a = x
4027                .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4028                .unwrap();
4029            let b = x
4030                .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4031                .unwrap();
4032            let c = x
4033                .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4034                .unwrap();
4035            x.ssd_chunk_scan(&dt, &a, &b, &c, 2)
4036                .realize_f32()
4037                .iter()
4038                .sum()
4039        };
4040        let x0 = vec![1.0f32, 2.0, 3.0, 4.0];
4041        let x = Tensor::from_f32(x0.clone(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4042        let dt = x
4043            .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4044            .unwrap();
4045        let a = x
4046            .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4047            .unwrap();
4048        let b = x
4049            .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4050            .unwrap();
4051        let c = x
4052            .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4053            .unwrap();
4054        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 2);
4055        let grads = y.inner.backward();
4056        let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
4057        let g_x =
4058            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
4059                .expect("realize");
4060        // FD over x_0 (a chunk-0 input): its contribution to y_3/y_4 (chunk 1)
4061        // rides the cross-chunk gate exp(dt*a) — multi-step BPTT.
4062        let h = 1e-3f32;
4063        let mut xp = x0.clone();
4064        xp[0] += h;
4065        let mut xm = x0.clone();
4066        xm[0] -= h;
4067        let fd0 = (fwd(&xp) - fwd(&xm)) / (2.0 * h);
4068        assert!(
4069            (g_x[0] - fd0).abs() < 5e-2,
4070            "ssd_chunk_scan seqlen4 dL/dx_0: autograd {} vs FD {fd0}",
4071            g_x[0]
4072        );
4073        assert!(
4074            g_x[0].abs() > 0.5,
4075            "cross-chunk-gate grad must be non-trivial, got {g_x:?}"
4076        );
4077    }
4078
4079    // ---- Task 8: general-dimension SSM parity gate (C7 non-regression) ------
4080    //
4081    // The all-1s gap-test fixtures above (Task 6/7) share a single flat order
4082    // across every axis, so they cannot catch an axis transposition in the
4083    // decompose. The tests below run each SSM op at DISTINGUISHING multi-dim
4084    // sizes and assert the `unroll_scan` oracle (over the lowered `Op::Scan`)
4085    // matches the fused kernel element-wise, which is only possible if every
4086    // per-step slice / broadcast / reduce axis in the Task-6/7 decompose lines
4087    // up with the kernel's layout.
4088
4089    /// Walk the lowered graph from `root`, assert NO `Op::Fused(fused_id)`
4090    /// survives the `lowering_only()` pass, and return the `Op::Scan` terminal
4091    /// the decompose emitted (there must be exactly one on the SSM path).
4092    fn find_scan_terminal(
4093        graph: &std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
4094        root: fuel_graph::NodeId,
4095        fused_id: fuel_graph::registry::FusedOpId,
4096    ) -> fuel_graph::NodeId {
4097        use fuel_graph::Op;
4098        let g = graph.read().unwrap();
4099        let mut stack = vec![root];
4100        let mut seen = std::collections::HashSet::new();
4101        let mut scan_id = None;
4102        while let Some(nid) = stack.pop() {
4103            if !seen.insert(nid) {
4104                continue;
4105            }
4106            let node = g.node(nid);
4107            assert!(
4108                !matches!(node.op, Op::Fused(fid, _) if fid == fused_id),
4109                "SSM op must lower to Op::Scan, not remain fused",
4110            );
4111            if matches!(node.op, Op::Scan { .. }) {
4112                scan_id = Some(nid);
4113            }
4114            for &inp in &node.inputs {
4115                stack.push(inp);
4116            }
4117        }
4118        scan_id.expect("an Op::Scan terminal must be present after lowering")
4119    }
4120
4121    /// Reindex a flat row-major `[seqlen, batch, tail]` buffer — the layout
4122    /// `unroll_scan` stacks its per-step ys into (scan axis 0) — to
4123    /// `[batch, seqlen, tail]`, the fused kernel's `y` layout, so the two align
4124    /// element-wise. `tail` is the product of the trailing per-token dims (`dim`
4125    /// for selective_scan; `heads*head_dim` for ssd) — a contiguous block whose
4126    /// internal order is preserved by the batch/seqlen swap.
4127    ///
4128    /// This is done in host code deliberately: the executor treats `Op::Permute`
4129    /// as a metadata-only view (shared bytes + strided layout), so realizing a
4130    /// `Permute` *root* can hand back byte-shared storage still in seqlen-major
4131    /// order — an unreliable comparand. Realizing the contiguous unroll `Concat`
4132    /// (`ys`) and permuting the flat host bytes here is unambiguous.
4133    fn scan_ys_to_fused_layout(ys: &[f32], seqlen: usize, batch: usize, tail: usize) -> Vec<f32> {
4134        assert_eq!(ys.len(), seqlen * batch * tail, "ys layout mismatch");
4135        let mut out = vec![0f32; ys.len()];
4136        for s in 0..seqlen {
4137            for bb in 0..batch {
4138                for t in 0..tail {
4139                    out[(bb * seqlen + s) * tail + t] = ys[(s * batch + bb) * tail + t];
4140                }
4141            }
4142        }
4143        out
4144    }
4145
4146    /// Task 8 (part 1) — `selective_scan` general-dimension parity.
4147    ///
4148    /// **C7 non-regression:** `PipelinedExecutor::realize` dispatches
4149    /// `Op::Fused(SELECTIVE_SCAN)` **directly** to its kernel and never runs a
4150    /// `RuleRegistry` lowering pass, so `decompose`→`Op::Scan` is reached ONLY by
4151    /// the `lowering_only()` verification below — the fused kernel is the
4152    /// executed path *by construction*. The `realize_f32()` leg (a) is the proof
4153    /// the fused kernel still runs (no `O(seqlen)` unroll on the hot path).
4154    ///
4155    /// **Distinguishing dims** batch=2, seqlen=3, dim=2, dstate=2 with EVERY
4156    /// element distinct and asymmetric: `u`/`delta` index `dim`, `b`/`c` index
4157    /// `dstate`, and `a` is a full `[dim,dstate]` gate — so a dim↔dstate
4158    /// broadcast swap multiplies wrong pairs, and because `h` threads across the
4159    /// (order-sensitive) seqlen recurrence, a batch↔seqlen transpose changes the
4160    /// result. The all-1s fixture cannot see either; this can.
4161    #[test]
4162    fn selective_scan_multidim_unroll_matches_fused_kernel() {
4163        use fuel_graph::registry::FusedOps;
4164        let dev = Device::cpu();
4165        let (batch, seqlen, dim, dstate) = (2usize, 3usize, 2usize, 2usize);
4166        // [batch, seqlen, dim] — all distinct, mixed signs.
4167        let u = Tensor::from_f32(
4168            vec![
4169                0.5, -0.3, 1.0, 0.2, -0.5, 0.7, 0.25, 0.9, -0.8, 0.4, 0.6, -0.1,
4170            ],
4171            Shape::from_dims(&[batch, seqlen, dim]),
4172            &dev,
4173        )
4174        .unwrap();
4175        // [batch, seqlen, dim] — positive (delta is a rate); all distinct.
4176        let delta = u
4177            .const_f32_like(
4178                vec![
4179                    0.1, 0.2, 0.3, 0.15, 0.25, 0.4, 0.35, 0.05, 0.2, 0.3, 0.12, 0.28,
4180                ],
4181                Shape::from_dims(&[batch, seqlen, dim]),
4182            )
4183            .unwrap();
4184        // [dim, dstate] — negative (Mamba a<0 → stable gate in (0,1)); distinct.
4185        let a = u
4186            .const_f32_like(
4187                vec![-0.7, -0.3, -0.5, -0.9],
4188                Shape::from_dims(&[dim, dstate]),
4189            )
4190            .unwrap();
4191        // [batch, seqlen, dstate] — distinct.
4192        let b = u
4193            .const_f32_like(
4194                vec![
4195                    1.0, 0.5, 0.25, 0.75, 0.6, 0.2, 0.8, 0.4, 0.3, 0.9, 0.55, 0.15,
4196                ],
4197                Shape::from_dims(&[batch, seqlen, dstate]),
4198            )
4199            .unwrap();
4200        // [batch, seqlen, dstate] — distinct.
4201        let c = u
4202            .const_f32_like(
4203                vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3, 1.2, 0.6, 0.9, 0.4, 0.7, 1.1],
4204                Shape::from_dims(&[batch, seqlen, dstate]),
4205            )
4206            .unwrap();
4207        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ false);
4208
4209        // (a) Fused kernel (executed production path) runs and is well-shaped.
4210        let fused = y.realize_f32();
4211        assert_eq!(fused.len(), batch * seqlen * dim);
4212
4213        // (b) Unroll oracle over the lowered Op::Scan matches the fused kernel.
4214        let graph = y.inner.graph().clone();
4215        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4216            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4217        assert_eq!(roots.len(), 1);
4218        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4219        let ys = {
4220            let mut g = graph.write().unwrap();
4221            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4222                .expect("unroll")
4223                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4224        };
4225        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4226            .expect("realize selective_scan unroll oracle on CPU");
4227        // ys is [seqlen,batch,dim]; fused y is [batch,seqlen,dim].
4228        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4229        assert_eq!(oracle.len(), fused.len());
4230        let mut max_drift = 0f32;
4231        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4232            let d = (o - f).abs();
4233            max_drift = max_drift.max(d);
4234            // 1e-3 sabotage-calibrated: native-F32 unroll vs F64-accumulate
4235            // kernel. Honest drift here is ~1e-6 (printed); a batch/seqlen or
4236            // dim/dstate transpose diverges by O(0.1..10) — far above 1e-3.
4237            assert!(
4238                d < 1e-3,
4239                "selective_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4240            );
4241        }
4242        eprintln!("selective_scan multidim: max honest drift = {max_drift:e}");
4243    }
4244
4245    /// Task 8 (part 1, softplus) — `selective_scan` with `delta_softplus=true`,
4246    /// the branch unexercised at T=1. `delta` carries mixed-sign values so the
4247    /// stable softplus form `Relu(x)+Log(1+Exp(Neg(Abs(x))))` does real work on
4248    /// both the `x>0` and `x<0` sides before the scan. Same fused-vs-oracle
4249    /// parity as the non-softplus case.
4250    #[test]
4251    fn selective_scan_softplus_multitoken_unroll_matches_fused_kernel() {
4252        use fuel_graph::registry::FusedOps;
4253        let dev = Device::cpu();
4254        let (batch, seqlen, dim, dstate) = (1usize, 3usize, 2usize, 2usize);
4255        let u = Tensor::from_f32(
4256            vec![0.5, -0.3, 1.0, 0.2, -0.5, 0.7],
4257            Shape::from_dims(&[batch, seqlen, dim]),
4258            &dev,
4259        )
4260        .unwrap();
4261        // Mixed signs → softplus exercises max(x,0) AND ln(1+exp(-|x|)).
4262        let delta = u
4263            .const_f32_like(
4264                vec![-0.5, 0.2, 0.8, -1.0, 0.3, -0.2],
4265                Shape::from_dims(&[batch, seqlen, dim]),
4266            )
4267            .unwrap();
4268        let a = u
4269            .const_f32_like(
4270                vec![-0.7, -0.3, -0.5, -0.9],
4271                Shape::from_dims(&[dim, dstate]),
4272            )
4273            .unwrap();
4274        let b = u
4275            .const_f32_like(
4276                vec![1.0, 0.5, 0.25, 0.75, 0.6, 0.2],
4277                Shape::from_dims(&[batch, seqlen, dstate]),
4278            )
4279            .unwrap();
4280        let c = u
4281            .const_f32_like(
4282                vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3],
4283                Shape::from_dims(&[batch, seqlen, dstate]),
4284            )
4285            .unwrap();
4286        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ true);
4287
4288        let fused = y.realize_f32();
4289        assert_eq!(fused.len(), batch * seqlen * dim);
4290
4291        let graph = y.inner.graph().clone();
4292        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4293            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4294        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4295        let ys = {
4296            let mut g = graph.write().unwrap();
4297            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4298                .expect("unroll")
4299                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4300        };
4301        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4302            .expect("realize selective_scan softplus oracle on CPU");
4303        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4304        let mut max_drift = 0f32;
4305        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4306            let d = (o - f).abs();
4307            max_drift = max_drift.max(d);
4308            assert!(
4309                d < 1e-3,
4310                "selective_scan softplus mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4311            );
4312        }
4313        eprintln!("selective_scan softplus: max honest drift = {max_drift:e}");
4314    }
4315
4316    /// Task 8 (part 2) — `ssd_chunk_scan` general-dimension parity.
4317    ///
4318    /// **C7 non-regression** (same construction as part 1): the executor
4319    /// dispatches `Op::Fused(SSD_CHUNK_SCAN)` straight to its kernel; the
4320    /// `decompose`→`Op::Scan` recipe is reached only by `lowering_only()` here.
4321    ///
4322    /// **Distinguishing dims** batch=2, seqlen=4, heads=2, head_dim=2,
4323    /// state_dim=2, chunk_size=2. Per-head `a = [-0.6, -1.0]` (head 0's gate
4324    /// leaking into head 1 flips the decay); `x` (indexes head_dim), `b`/`c`
4325    /// (index state_dim) use three DIFFERENT value ramps, so a head_dim↔state_dim
4326    /// broadcast swap (`bc_x` vs `bc_state`) mixes the wrong axes, and the
4327    /// seqlen recurrence + batch↔seqlen permute are exercised because batch>1.
4328    /// Every element is distinct.
4329    #[test]
4330    fn ssd_chunk_scan_multidim_unroll_matches_fused_kernel() {
4331        use fuel_graph::registry::FusedOps;
4332        let dev = Device::cpu();
4333        let (batch, seqlen, heads, head_dim, state_dim, chunk) =
4334            (2usize, 4usize, 2usize, 2usize, 2usize, 2usize);
4335        // Distinct value ramps (different base + slope per tensor) guarantee no
4336        // accidental symmetry; dt stays positive, a stays negative (stable gate).
4337        let x_data: Vec<f32> = (0..batch * seqlen * heads * head_dim)
4338            .map(|i| 0.20 + 0.05 * i as f32)
4339            .collect();
4340        let dt_data: Vec<f32> = (0..batch * seqlen * heads)
4341            .map(|i| 0.10 + 0.04 * i as f32)
4342            .collect();
4343        let b_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4344            .map(|i| 0.15 + 0.03 * i as f32)
4345            .collect();
4346        let c_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4347            .map(|i| 0.25 + 0.035 * i as f32)
4348            .collect();
4349        let x = Tensor::from_f32(
4350            x_data,
4351            Shape::from_dims(&[batch, seqlen, heads, head_dim]),
4352            &dev,
4353        )
4354        .unwrap();
4355        let dt = x
4356            .const_f32_like(dt_data, Shape::from_dims(&[batch, seqlen, heads]))
4357            .unwrap();
4358        let a = x
4359            .const_f32_like(vec![-0.6f32, -1.0], Shape::from_dims(&[heads]))
4360            .unwrap();
4361        let b = x
4362            .const_f32_like(b_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4363            .unwrap();
4364        let c = x
4365            .const_f32_like(c_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4366            .unwrap();
4367        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, chunk);
4368
4369        // (a) Fused kernel (executed production path) runs and is well-shaped.
4370        let fused = y.realize_f32();
4371        assert_eq!(fused.len(), batch * seqlen * heads * head_dim);
4372
4373        // (b) Unroll oracle over the lowered Op::Scan matches the fused kernel.
4374        let graph = y.inner.graph().clone();
4375        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4376            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4377        assert_eq!(roots.len(), 1);
4378        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SSD_CHUNK_SCAN);
4379        let ys = {
4380            let mut g = graph.write().unwrap();
4381            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4382                .expect("unroll")
4383                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4384        };
4385        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4386            .expect("realize ssd_chunk_scan unroll oracle on CPU");
4387        // ys is [seqlen,batch,heads,head_dim]; fused y is
4388        // [batch,seqlen,heads,head_dim]. tail = heads*head_dim (contiguous).
4389        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, heads * head_dim);
4390        assert_eq!(oracle.len(), fused.len());
4391        let mut max_drift = 0f32;
4392        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4393            let d = (o - f).abs();
4394            max_drift = max_drift.max(d);
4395            assert!(
4396                d < 1e-3,
4397                "ssd_chunk_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4398            );
4399        }
4400        eprintln!("ssd_chunk_scan multidim: max honest drift = {max_drift:e}");
4401    }
4402
4403    /// Recipe principle (G2): Nf4Matmul must decompose to a **fused-free**
4404    /// primitive subgraph whose realize matches the fused kernel. RED before
4405    /// the total decompose landed (the self-return left an
4406    /// `Op::Fused(NF4_MATMUL)` opaque island in the base map); GREEN after.
4407    /// Uses the hand-computed two-outputs / two-blocks case (expected `[10,
4408    /// 50]`) shared with `fuel_cpu_backend`'s byte-kernel test, so the
4409    /// indicator-sum codebook + nibble unpack + per-block scale are checked
4410    /// against the same numbers the fused CPU kernel produces.
4411    #[test]
4412    fn nf4_matmul_decompose_matches_kernel() {
4413        use fuel_graph::Op;
4414        use fuel_graph::registry::FusedOps;
4415        let dev = Device::cpu();
4416        // n=2, k=4, block_size=2; w_packed [2, 2] U8, absmax [2, 2] F32.
4417        let weight = crate::nf4::nf4_from_bytes(
4418            vec![247_u8, 247, 127, 127],
4419            vec![1.0_f32, 2.0, 10.0, 20.0],
4420            2,
4421            4,
4422            2,
4423            &dev,
4424        )
4425        .expect("nf4_from_bytes");
4426        let act = Tensor::from_graph_tensor(
4427            weight
4428                .w_packed
4429                .graph_tensor()
4430                .const_f32_like(vec![1.0_f32, 2.0, 2.0, 4.0], Shape::from_dims(&[1, 4]))
4431                .unwrap(),
4432        );
4433        let y = weight.matmul(&act);
4434
4435        // Decompose explicitly, then realize the primitive subgraph.
4436        let graph = y.inner.graph().clone();
4437        let id = y.inner.id();
4438        let roots =
4439            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
4440        assert_eq!(roots.len(), 1, "lowering should keep a single root");
4441
4442        // Born-red discriminator: no Op::Fused(NF4_MATMUL) reachable from the
4443        // realized root — a self-returning decompose fails exactly here.
4444        {
4445            let g = graph.read().unwrap();
4446            let mut stack = vec![roots[0]];
4447            let mut seen = std::collections::HashSet::new();
4448            while let Some(nid) = stack.pop() {
4449                if !seen.insert(nid) {
4450                    continue;
4451                }
4452                let node = g.node(nid);
4453                assert!(
4454                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::NF4_MATMUL),
4455                    "decomposed graph still contains an Op::Fused(NF4_MATMUL) island",
4456                );
4457                for &inp in &node.inputs {
4458                    stack.push(inp);
4459                }
4460            }
4461        }
4462
4463        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
4464            .expect("realize decomposed Nf4Matmul on CPU");
4465        assert_eq!(got.len(), 2);
4466        assert!((got[0] - 10.0).abs() < 1e-4, "out 0: {}", got[0]);
4467        assert!((got[1] - 50.0).abs() < 1e-4, "out 1: {}", got[1]);
4468    }
4469
4470    /// Build a one-output fused-op node directly on `anchor`'s graph, lower it
4471    /// to primitives, realize on CPU, and return the F32 values. The decompose
4472    /// parity tests for backward helpers use this — those ops have no public
4473    /// builder (autograd creates them), so the test constructs the
4474    /// `Op::Fused` node by hand.
4475    fn lower_realize_fused(
4476        anchor: &Tensor,
4477        op: fuel_graph::Op,
4478        inputs: Vec<fuel_graph::NodeId>,
4479        shape: Shape,
4480    ) -> Vec<f32> {
4481        let graph = anchor.inner.graph().clone();
4482        let fused_id = {
4483            let mut g = graph.write().unwrap();
4484            g.push(fuel_graph::Node {
4485                op,
4486                inputs,
4487                shape,
4488                dtype: DType::F32,
4489            })
4490        };
4491        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4492            .optimize_to_fixpoint(&graph, &[fused_id]);
4493        assert_eq!(roots.len(), 1, "lowering keeps a single root");
4494        crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
4495            .expect("realize decomposed fused op on CPU")
4496    }
4497
4498    #[test]
4499    fn powi_backward_decompose_matches_reference() {
4500        use fuel_graph::registry::{FusedOpParams, FusedOps};
4501        let dev = Device::cpu();
4502        let exp = 3i32;
4503        let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4504        let up_data = vec![1.0f32, 0.5, 2.0, -1.0];
4505        let shape = Shape::from_dims(&[4]);
4506        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4507        let up = x.const_f32_like(up_data.clone(), shape.clone()).unwrap();
4508        let got = lower_realize_fused(
4509            &x,
4510            fuel_graph::Op::Fused(FusedOps::POWI_BACKWARD, FusedOpParams::PowIBackward { exp }),
4511            vec![x.inner.id(), up.inner.id()],
4512            shape,
4513        );
4514        // grad_x = exp · x^(exp-1) · upstream
4515        let expected: Vec<f32> = x_data
4516            .iter()
4517            .zip(&up_data)
4518            .map(|(&x, &u)| exp as f32 * x.powi(exp - 1) * u)
4519            .collect();
4520        assert_eq!(got.len(), expected.len());
4521        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4522            assert!(
4523                (g - e).abs() < 1e-4,
4524                "powi_backward at {i}: got {g}, expected {e}"
4525            );
4526        }
4527    }
4528
4529    /// Increment C — `inplace_affine`'s migrated functional value recipe:
4530    /// `decompose` lowers `Op::Fused(INPLACE_AFFINE, {mul, add})` to
4531    /// `AddScalar(add)(MulScalar(mul)(x))`, which realizes on the CPU backend to
4532    /// the plain affine `mul·x + add`. Bit-exact: the affine kernel pre-casts the
4533    /// f64 scalars to f32 and computes `mul_f32 * x + add_f32`, so the two-op
4534    /// `MulScalar`→`AddScalar` composition matches a hand `(mul as f32)*x + (add
4535    /// as f32)` exactly (the intermediate `* 1.0` / `+ 0.0` are IEEE identities).
4536    #[test]
4537    fn inplace_affine_decompose_matches_affine_reference() {
4538        use fuel_graph::registry::{FusedOpParams, FusedOps};
4539        let dev = Device::cpu();
4540        let (mul, add) = (2.5f64, -1.0f64);
4541        let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4542        let shape = Shape::from_dims(&[4]);
4543        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4544        let got = lower_realize_fused(
4545            &x,
4546            fuel_graph::Op::Fused(
4547                FusedOps::INPLACE_AFFINE,
4548                FusedOpParams::InplaceAffine { mul, add },
4549            ),
4550            vec![x.inner.id()],
4551            shape,
4552        );
4553        // functional affine: out = mul·x + add (scalars pre-cast to f32).
4554        let expected: Vec<f32> = x_data
4555            .iter()
4556            .map(|&v| (mul as f32) * v + add as f32)
4557            .collect();
4558        assert_eq!(got.len(), expected.len());
4559        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4560            assert_eq!(g, e, "inplace_affine at {i}: got {g}, expected {e}");
4561        }
4562    }
4563
4564    #[test]
4565    fn softmax_last_dim_backward_decompose_matches_reference() {
4566        use fuel_graph::registry::{FusedOpParams, FusedOps};
4567        let dev = Device::cpu();
4568        let (rows, cols) = (2usize, 3usize);
4569        // s = a real softmax over the last dim; g = arbitrary upstream.
4570        let logits = [[0.5f32, -1.0, 2.0], [1.0, 0.0, -0.5]];
4571        let mut s_data = Vec::new();
4572        for row in &logits {
4573            let m = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4574            let exps: Vec<f32> = row.iter().map(|&v| (v - m).exp()).collect();
4575            let sum: f32 = exps.iter().sum();
4576            s_data.extend(exps.iter().map(|&e| e / sum));
4577        }
4578        let g_data = vec![1.0f32, -0.5, 0.3, 0.2, 1.5, -1.0];
4579        let shape = Shape::from_dims(&[rows, cols]);
4580        let s = Tensor::from_f32(s_data.clone(), shape.clone(), &dev).unwrap();
4581        let g = s.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4582        let got = lower_realize_fused(
4583            &s,
4584            fuel_graph::Op::Fused(
4585                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
4586                FusedOpParams::SoftmaxLastDimBackward,
4587            ),
4588            vec![s.inner.id(), g.inner.id()],
4589            shape,
4590        );
4591        // grad_x = s · (g − sum(g·s, last))
4592        let mut expected = vec![0.0f32; rows * cols];
4593        for r in 0..rows {
4594            let dot: f32 = (0..cols)
4595                .map(|c| g_data[r * cols + c] * s_data[r * cols + c])
4596                .sum();
4597            for c in 0..cols {
4598                expected[r * cols + c] = s_data[r * cols + c] * (g_data[r * cols + c] - dot);
4599            }
4600        }
4601        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4602            assert!(
4603                (gv - ev).abs() < 1e-5,
4604                "softmax_bwd at {i}: got {gv}, expected {ev}"
4605            );
4606        }
4607    }
4608
4609    #[test]
4610    fn rms_norm_last_dim_backward_decompose_matches_reference() {
4611        use fuel_graph::registry::{FusedOpParams, FusedOps};
4612        let dev = Device::cpu();
4613        let (rows, cols) = (2usize, 3usize);
4614        let eps = 1e-5f64;
4615        let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4616        let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4617        let shape = Shape::from_dims(&[rows, cols]);
4618        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4619        let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4620        let got = lower_realize_fused(
4621            &x,
4622            fuel_graph::Op::Fused(
4623                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
4624                FusedOpParams::RmsNormLastDimBackward { eps },
4625            ),
4626            vec![x.inner.id(), g.inner.id()],
4627            shape,
4628        );
4629        // grad_x = r_rms · (g − x·s / (n·(mean_sq + eps)))
4630        let n = cols as f32;
4631        let mut expected = vec![0.0f32; rows * cols];
4632        for r in 0..rows {
4633            let meansq: f32 = (0..cols).map(|c| x_data[r * cols + c].powi(2)).sum::<f32>() / n;
4634            let denom = meansq + eps as f32;
4635            let rrms = 1.0 / denom.sqrt();
4636            let s: f32 = (0..cols)
4637                .map(|c| g_data[r * cols + c] * x_data[r * cols + c])
4638                .sum();
4639            for c in 0..cols {
4640                let term = x_data[r * cols + c] * s / (n * denom);
4641                expected[r * cols + c] = rrms * (g_data[r * cols + c] - term);
4642            }
4643        }
4644        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4645            assert!(
4646                (gv - ev).abs() < 1e-4,
4647                "rms_norm_bwd at {i}: got {gv}, expected {ev}"
4648            );
4649        }
4650    }
4651
4652    #[test]
4653    fn layer_norm_last_dim_backward_decompose_matches_reference() {
4654        use fuel_graph::registry::{FusedOpParams, FusedOps};
4655        let dev = Device::cpu();
4656        let (rows, cols) = (2usize, 3usize);
4657        let eps = 1e-5f64;
4658        let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4659        let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4660        let shape = Shape::from_dims(&[rows, cols]);
4661        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4662        let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4663        let got = lower_realize_fused(
4664            &x,
4665            fuel_graph::Op::Fused(
4666                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
4667                FusedOpParams::LayerNormLastDimBackward { eps },
4668            ),
4669            vec![x.inner.id(), g.inner.id()],
4670            shape,
4671        );
4672        // grad_x = istd · (g − mean(g) − xhat·mean(g·xhat))
4673        let n = cols as f32;
4674        let mut expected = vec![0.0f32; rows * cols];
4675        for r in 0..rows {
4676            let mean_x: f32 = (0..cols).map(|c| x_data[r * cols + c]).sum::<f32>() / n;
4677            let var: f32 = (0..cols)
4678                .map(|c| (x_data[r * cols + c] - mean_x).powi(2))
4679                .sum::<f32>()
4680                / n;
4681            let istd = 1.0 / (var + eps as f32).sqrt();
4682            let xhat: Vec<f32> = (0..cols)
4683                .map(|c| (x_data[r * cols + c] - mean_x) * istd)
4684                .collect();
4685            let mean_g: f32 = (0..cols).map(|c| g_data[r * cols + c]).sum::<f32>() / n;
4686            let mean_gxh: f32 = (0..cols)
4687                .map(|c| g_data[r * cols + c] * xhat[c])
4688                .sum::<f32>()
4689                / n;
4690            for c in 0..cols {
4691                expected[r * cols + c] =
4692                    istd * (g_data[r * cols + c] - mean_g - xhat[c] * mean_gxh);
4693            }
4694        }
4695        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4696            assert!(
4697                (gv - ev).abs() < 1e-4,
4698                "layer_norm_bwd at {i}: got {gv}, expected {ev}"
4699            );
4700        }
4701    }
4702
4703    #[test]
4704    fn reduce_max_to_backward_decompose_matches_reference() {
4705        use fuel_graph::registry::{FusedOpParams, FusedOps};
4706        let dev = Device::cpu();
4707        // row0 has a tie at the max (two 3.0s → share 10/2); row1 unique max.
4708        let x_data = vec![1.0f32, 3.0, 3.0, 2.0, 0.0, 1.0]; // [2,3]
4709        let up_data = vec![10.0f32, 5.0]; // [2,1] — one per reduced row.
4710        let x_shape = Shape::from_dims(&[2, 3]);
4711        let up_shape = Shape::from_dims(&[2, 1]);
4712        let x = Tensor::from_f32(x_data.clone(), x_shape.clone(), &dev).unwrap();
4713        let up = x.const_f32_like(up_data.clone(), up_shape).unwrap();
4714        let got = lower_realize_fused(
4715            &x,
4716            fuel_graph::Op::Fused(
4717                FusedOps::REDUCE_MAX_TO_BACKWARD,
4718                FusedOpParams::ReduceMaxToBackward,
4719            ),
4720            vec![x.inner.id(), up.inner.id()],
4721            x_shape,
4722        );
4723        // row0: max 3.0 tied 2× → 10/2 each; row1: max 2.0 unique → full 5.0.
4724        let expected = vec![0.0f32, 5.0, 5.0, 5.0, 0.0, 0.0];
4725        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4726            assert!(
4727                (gv - ev).abs() < 1e-5,
4728                "reduce_max_bwd at {i}: got {gv}, expected {ev}"
4729            );
4730        }
4731    }
4732
4733    fn causal_conv1d_check(use_silu: bool) {
4734        use fuel_graph::registry::{FusedOpParams, FusedOps};
4735        let dev = Device::cpu();
4736        let (b, c, k, seq) = (1usize, 2usize, 3usize, 2usize);
4737        let x_seq = seq + (k - 1); // caller pre-pads by K-1.
4738        // x [B,C,x_seq], weight [C,1,K], bias [C] — all row-major.
4739        let x_data = vec![0.0f32, 1.0, 2.0, 3.0, 1.0, 0.0, -1.0, -2.0];
4740        let w_data = vec![0.5f32, 1.0, -0.5, 1.0, 0.0, 2.0];
4741        let bias_data = vec![0.1f32, -0.2];
4742        let x = Tensor::from_f32(x_data.clone(), Shape::from_dims(&[b, c, x_seq]), &dev).unwrap();
4743        let w = x
4744            .const_f32_like(w_data.clone(), Shape::from_dims(&[c, 1, k]))
4745            .unwrap();
4746        let bias = x
4747            .const_f32_like(bias_data.clone(), Shape::from_dims(&[c]))
4748            .unwrap();
4749        let got = lower_realize_fused(
4750            &x,
4751            fuel_graph::Op::Fused(
4752                FusedOps::CAUSAL_CONV1D,
4753                FusedOpParams::CausalConv1d { use_silu },
4754            ),
4755            vec![x.inner.id(), w.inner.id(), bias.inner.id()],
4756            Shape::from_dims(&[b, c, seq]),
4757        );
4758        // out[c,t] = Σ_k w[c,k]·x[c,t+k] + bias[c], optional SiLU.
4759        let mut expected = vec![0.0f32; b * c * seq];
4760        for ch in 0..c {
4761            for t in 0..seq {
4762                let mut acc = 0.0f32;
4763                for kk in 0..k {
4764                    acc += w_data[ch * k + kk] * x_data[ch * x_seq + t + kk];
4765                }
4766                acc += bias_data[ch];
4767                if use_silu {
4768                    acc *= 1.0 / (1.0 + (-acc).exp());
4769                }
4770                expected[ch * seq + t] = acc;
4771            }
4772        }
4773        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4774            assert!(
4775                (gv - ev).abs() < 1e-4,
4776                "causal_conv1d (silu={use_silu}) at {i}: got {gv}, expected {ev}",
4777            );
4778        }
4779    }
4780
4781    #[test]
4782    fn causal_conv1d_decompose_matches_reference() {
4783        causal_conv1d_check(false);
4784        causal_conv1d_check(true);
4785    }
4786
4787    #[test]
4788    fn flash_attn_backward_decompose_matches_reference() {
4789        use fuel_graph::registry::{FusedOpParams, FusedOps};
4790        let dev = Device::cpu();
4791        let (sq, sk, d) = (2usize, 2usize, 2usize);
4792        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
4793        // swapping the exact constant would perturb these attention-scale parity tests.
4794        #[allow(clippy::approx_constant)]
4795        let scale = 0.7071f32;
4796        let q_data = vec![0.1f32, -0.2, 0.3, 0.5]; // [Sq,D]
4797        let k_data = vec![0.4f32, 0.1, -0.3, 0.2]; // [Sk,D]
4798        let v_data = vec![1.0f32, 2.0, -1.0, 0.5]; // [Sk,D]
4799        let do_data = vec![0.5f32, -1.0, 0.2, 0.3]; // [Sq,D]
4800        let qshape = Shape::from_dims(&[1, 1, sq, d]);
4801        let kshape = Shape::from_dims(&[1, 1, sk, d]);
4802        let q = Tensor::from_f32(q_data.clone(), qshape.clone(), &dev).unwrap();
4803        let k = q.const_f32_like(k_data.clone(), kshape.clone()).unwrap();
4804        let v = q.const_f32_like(v_data.clone(), kshape.clone()).unwrap();
4805        let dout = q.const_f32_like(do_data.clone(), qshape.clone()).unwrap();
4806        let params = FusedOpParams::FlashAttnBackward {
4807            softmax_scale: scale,
4808            causal: false,
4809            window_size_left: None,
4810            window_size_right: None,
4811            softcap: None,
4812        };
4813        let inputs = vec![q.inner.id(), k.inner.id(), v.inner.id(), dout.inner.id()];
4814        let dq = lower_realize_fused(
4815            &q,
4816            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_Q, params.clone()),
4817            inputs.clone(),
4818            qshape.clone(),
4819        );
4820        let dk = lower_realize_fused(
4821            &q,
4822            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_K, params.clone()),
4823            inputs.clone(),
4824            kshape.clone(),
4825        );
4826        let dv = lower_realize_fused(
4827            &q,
4828            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_V, params),
4829            inputs,
4830            kshape,
4831        );
4832
4833        // --- reference SDPA backward (B=1, H=1) ---
4834        let mut p = vec![0.0f32; sq * sk];
4835        for i in 0..sq {
4836            let mut scores = vec![0.0f32; sk];
4837            for j in 0..sk {
4838                let mut s = 0.0f32;
4839                for l in 0..d {
4840                    s += q_data[i * d + l] * k_data[j * d + l];
4841                }
4842                scores[j] = scale * s;
4843            }
4844            let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4845            let mut sum = 0.0f32;
4846            let e: Vec<f32> = scores
4847                .iter()
4848                .map(|&s| {
4849                    let x = (s - m).exp();
4850                    sum += x;
4851                    x
4852                })
4853                .collect();
4854            for j in 0..sk {
4855                p[i * sk + j] = e[j] / sum;
4856            }
4857        }
4858        // dV[j,l] = Σ_i P[i,j]·dO[i,l]
4859        let mut ref_dv = vec![0.0f32; sk * d];
4860        for j in 0..sk {
4861            for l in 0..d {
4862                ref_dv[j * d + l] = (0..sq).map(|i| p[i * sk + j] * do_data[i * d + l]).sum();
4863            }
4864        }
4865        // dP[i,j] = Σ_l dO[i,l]·v[j,l]
4866        let mut dp = vec![0.0f32; sq * sk];
4867        for i in 0..sq {
4868            for j in 0..sk {
4869                dp[i * sk + j] = (0..d).map(|l| do_data[i * d + l] * v_data[j * d + l]).sum();
4870            }
4871        }
4872        // dScores_raw[i,j] = scale · P[i,j]·(dP[i,j] − Σ_j' dP·P)
4873        let mut dsr = vec![0.0f32; sq * sk];
4874        for i in 0..sq {
4875            let rowdot: f32 = (0..sk).map(|j| dp[i * sk + j] * p[i * sk + j]).sum();
4876            for j in 0..sk {
4877                dsr[i * sk + j] = scale * p[i * sk + j] * (dp[i * sk + j] - rowdot);
4878            }
4879        }
4880        // dQ[i,l] = Σ_j dsr[i,j]·k[j,l] ; dK[j,l] = Σ_i dsr[i,j]·q[i,l]
4881        let mut ref_dq = vec![0.0f32; sq * d];
4882        for i in 0..sq {
4883            for l in 0..d {
4884                ref_dq[i * d + l] = (0..sk).map(|j| dsr[i * sk + j] * k_data[j * d + l]).sum();
4885            }
4886        }
4887        let mut ref_dk = vec![0.0f32; sk * d];
4888        for j in 0..sk {
4889            for l in 0..d {
4890                ref_dk[j * d + l] = (0..sq).map(|i| dsr[i * sk + j] * q_data[i * d + l]).sum();
4891            }
4892        }
4893        let check = |name: &str, got: &[f32], exp: &[f32]| {
4894            assert_eq!(got.len(), exp.len(), "{name} length");
4895            for (i, (&gv, &ev)) in got.iter().zip(exp).enumerate() {
4896                assert!(
4897                    (gv - ev).abs() < 1e-4,
4898                    "{name} at {i}: got {gv}, expected {ev}"
4899                );
4900            }
4901        };
4902        check("dQ", &dq, &ref_dq);
4903        check("dK", &dk, &ref_dk);
4904        check("dV", &dv, &ref_dv);
4905    }
4906
4907    #[test]
4908    fn paged_attn_decompose_matches_reference() {
4909        use fuel_graph::registry::{FusedOpParams, FusedOps};
4910        let dev = Device::cpu();
4911        // B=1, Hq=Hkv=1, Sq=1 (decode), D=2; block_size=2, max_blk=2 → kv_len=4.
4912        let block_size = 2usize;
4913        let scale = 1.0f32;
4914        // k_cache / v_cache: [num_blocks=3, block_size=2, Hkv=1, D=2]. Block 1
4915        // is unused (not in the block table) and holds sentinel 9s.
4916        let kc = vec![
4917            1.0f32, 0.0, 0.0, 1.0, 9.0, 9.0, 9.0, 9.0, 1.0, 1.0, 2.0, 0.0,
4918        ];
4919        let vc = vec![
4920            1.0f32, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0,
4921        ];
4922        let q_data = vec![0.5f32, 0.5]; // [1,1,1,2]
4923        let bt = vec![0u32, 2u32]; // block_table [1,2]: sequence uses blocks 0 and 2
4924        let cl = vec![3u32]; // context_lens [1]: only the first 3 keys are valid
4925
4926        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, 1, 1, 2]), &dev).unwrap();
4927        let kcache = q
4928            .const_f32_like(kc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4929            .unwrap();
4930        let vcache = q
4931            .const_f32_like(vc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4932            .unwrap();
4933        let block_table = q.const_u32_like(bt, Shape::from_dims(&[1, 2])).unwrap();
4934        let context_lens = q.const_u32_like(cl, Shape::from_dims(&[1])).unwrap();
4935        let params = FusedOpParams::PagedAttn {
4936            softmax_scale: scale,
4937            block_size,
4938            softcap: None,
4939        };
4940        let inputs = vec![
4941            q.inner.id(),
4942            kcache.inner.id(),
4943            vcache.inner.id(),
4944            block_table.inner.id(),
4945            context_lens.inner.id(),
4946        ];
4947        let got = lower_realize_fused(
4948            &q,
4949            fuel_graph::Op::Fused(FusedOps::PAGED_ATTN, params),
4950            inputs,
4951            Shape::from_dims(&[1, 1, 1, 2]),
4952        );
4953
4954        // reference: gather blocks [0, 2] → k_seq/v_seq[4][2]; mask j ≥ 3;
4955        // softmax; weighted sum of v.
4956        let (kv_len, ctx) = (4usize, 3usize);
4957        let mut k_seq = vec![];
4958        let mut v_seq = vec![];
4959        for &blk in &[0usize, 2usize] {
4960            for p in 0..block_size {
4961                let base = (blk * block_size + p) * 2; // Hkv=1, D=2
4962                k_seq.push([kc[base], kc[base + 1]]);
4963                v_seq.push([vc[base], vc[base + 1]]);
4964            }
4965        }
4966        let mut scores = vec![0.0f32; kv_len];
4967        for j in 0..kv_len {
4968            let s = q_data[0] * k_seq[j][0] + q_data[1] * k_seq[j][1];
4969            scores[j] = if j >= ctx {
4970                f32::NEG_INFINITY
4971            } else {
4972                scale * s
4973            };
4974        }
4975        let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4976        let mut sum = 0.0f32;
4977        let e: Vec<f32> = scores
4978            .iter()
4979            .map(|&s| {
4980                let x = (s - m).exp();
4981                sum += x;
4982                x
4983            })
4984            .collect();
4985        let mut expected = vec![0.0f32; 2];
4986        for j in 0..kv_len {
4987            for l in 0..2 {
4988                expected[l] += (e[j] / sum) * v_seq[j][l];
4989            }
4990        }
4991        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4992            assert!(
4993                (gv - ev).abs() < 1e-4,
4994                "paged_attn at {i}: got {gv}, expected {ev}"
4995            );
4996        }
4997    }
4998
4999    #[test]
5000    #[cfg(feature = "cuda")]
5001    fn cuda_executor_matches_cpu_on_add_mul() {
5002        let a =
5003            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5004        let b = a
5005            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
5006            .unwrap();
5007        let c = a.add(&b).unwrap().mul(&a).unwrap();
5008        let cpu_result = c.realize_f32();
5009        let executor = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5010        let cuda_result = c.realize_f32_cuda(&executor);
5011        assert_eq!(cpu_result, cuda_result);
5012    }
5013
5014    /// END-TO-END SMOKE ONLY — NOT a CUDA-kernel pin. Verifies the lazy
5015    /// realize path produces the NaN-propagating `maximum`/`minimum`
5016    /// convention (pinned 2026-07-08,
5017    /// `docs/architecture/10-decisions-log.md`) and that a CPU realize and
5018    /// a CUDA-device realize of the same graph agree on NaN-ness.
5019    ///
5020    /// CAVEAT (orchestrator sabotage finding, 2026-07-08): cost-based
5021    /// placement may route a tiny elementwise op to CPU on BOTH legs even
5022    /// under `realize_f32_cuda`, so this test does NOT guarantee the CUDA
5023    /// kernel executed — a wrong CUDA binding can pass it. The real
5024    /// CUDA-kernel pin is the direct binding-table invocation test
5025    /// `fuel-dispatch/tests/cuda_dispatch_live.rs::cuda_maximum_minimum_propagate_nan_f32`.
5026    ///
5027    /// Gated `#[cfg(feature = "cuda")]` + `#[ignore]`; skips cleanly if no
5028    /// CUDA device is present. Run:
5029    ///   `cargo test -p fuel-core --features cuda --lib \
5030    ///    maximum_minimum_nan_convention_lazy_realize_smoke -- --ignored --nocapture`
5031    #[test]
5032    #[cfg(feature = "cuda")]
5033    #[ignore = "requires a live CUDA device"]
5034    fn maximum_minimum_nan_convention_lazy_realize_smoke() {
5035        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5036            Ok(d) => d,
5037            Err(e) => {
5038                return fuel_test_support::hardware::skip(
5039                    fuel_test_support::hardware::Hardware::Cuda,
5040                    fuel_test_support::hardware::Missing::device(format!(
5041                        "CudaDevice::new(0): {e:?}"
5042                    )),
5043                );
5044            }
5045        };
5046        let a = Tensor::from_f32(
5047            vec![f32::NAN, -2.0, 3.0, f32::NAN],
5048            Shape::from_dims(&[4]),
5049            &Device::cpu(),
5050        )
5051        .unwrap();
5052        let b = a
5053            .const_f32_like(vec![1.0, f32::NAN, 2.0, f32::NAN], Shape::from_dims(&[4]))
5054            .unwrap();
5055
5056        let max_lazy = a.maximum(&b).unwrap();
5057        let cpu_max = max_lazy.realize_f32();
5058        let cuda_max = max_lazy.realize_f32_cuda(&cuda);
5059        for i in 0..4 {
5060            assert_eq!(
5061                cpu_max[i].is_nan(),
5062                cuda_max[i].is_nan(),
5063                "maximum[{i}] NaN-ness must match: cpu={}, cuda={}",
5064                cpu_max[i],
5065                cuda_max[i],
5066            );
5067            if !cpu_max[i].is_nan() {
5068                assert_eq!(cpu_max[i], cuda_max[i], "maximum[{i}]");
5069            }
5070        }
5071
5072        let min_lazy = a.minimum(&b).unwrap();
5073        let cpu_min = min_lazy.realize_f32();
5074        let cuda_min = min_lazy.realize_f32_cuda(&cuda);
5075        for i in 0..4 {
5076            assert_eq!(
5077                cpu_min[i].is_nan(),
5078                cuda_min[i].is_nan(),
5079                "minimum[{i}] NaN-ness must match: cpu={}, cuda={}",
5080                cpu_min[i],
5081                cuda_min[i],
5082            );
5083            if !cpu_min[i].is_nan() {
5084                assert_eq!(cpu_min[i], cuda_min[i], "minimum[{i}]");
5085            }
5086        }
5087    }
5088
5089    /// END-TO-END SMOKE ONLY — NOT a CUDA-kernel pin. Verifies the lazy
5090    /// realize path produces the NaN-propagating `relu` convention (torch
5091    /// parity, pinned 2026-07-08, `docs/architecture/10-decisions-log.md`)
5092    /// and that a CPU realize and a CUDA-device realize of the same graph
5093    /// agree on NaN-ness. Successor of the transitional-divergence pin
5094    /// `relu_cuda_still_scrubs_nan_pending_alpha76_rebind`, flipped at the
5095    /// alpha.76 `unary_relu_propagating_*` rebind.
5096    ///
5097    /// CAVEAT (orchestrator sabotage finding, 2026-07-08): cost-based
5098    /// placement may route a tiny elementwise op to CPU on BOTH legs even
5099    /// under `realize_f32_cuda`, so this test does NOT guarantee the CUDA
5100    /// kernel executed — it stayed green with the CUDA binding deliberately
5101    /// reverted to the scrubbing stem. The real CUDA-kernel pin (verified
5102    /// born-red against that sabotage) is the direct binding-table
5103    /// invocation test
5104    /// `fuel-dispatch/tests/cuda_dispatch_live.rs::cuda_relu_propagates_nan_f32`
5105    /// (+ its bf16 sibling).
5106    ///
5107    /// Gated `#[cfg(feature = "cuda")]` + `#[ignore]`; skips cleanly if no
5108    /// CUDA device is present. Run:
5109    ///   `cargo test -p fuel-core --features cuda --lib \
5110    ///    relu_nan_convention_lazy_realize_smoke -- --ignored --nocapture`
5111    #[test]
5112    #[cfg(feature = "cuda")]
5113    #[ignore = "requires a live CUDA device"]
5114    fn relu_nan_convention_lazy_realize_smoke() {
5115        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5116            Ok(d) => d,
5117            Err(e) => {
5118                return fuel_test_support::hardware::skip(
5119                    fuel_test_support::hardware::Hardware::Cuda,
5120                    fuel_test_support::hardware::Missing::device(format!(
5121                        "CudaDevice::new(0): {e:?}"
5122                    )),
5123                );
5124            }
5125        };
5126        let a = Tensor::from_f32(
5127            vec![f32::NAN, -2.0, 3.0],
5128            Shape::from_dims(&[3]),
5129            &Device::cpu(),
5130        )
5131        .unwrap();
5132        let relu_lazy = a.relu();
5133        let cpu_result = relu_lazy.realize_f32();
5134        let cuda_result = relu_lazy.realize_f32_cuda(&cuda);
5135
5136        for i in 0..3 {
5137            assert_eq!(
5138                cpu_result[i].is_nan(),
5139                cuda_result[i].is_nan(),
5140                "relu[{i}] NaN-ness must match: cpu={}, cuda={}",
5141                cpu_result[i],
5142                cuda_result[i],
5143            );
5144            if !cpu_result[i].is_nan() {
5145                assert_eq!(cpu_result[i], cuda_result[i], "relu[{i}]");
5146            }
5147        }
5148    }
5149
5150    #[test]
5151    #[cfg(feature = "cuda")]
5152    fn cuda_executor_matches_cpu_on_matmul() {
5153        let a = Tensor::from_f32(
5154            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5155            Shape::from_dims(&[2, 3]),
5156            &Device::cpu(),
5157        )
5158        .unwrap();
5159        let b = a
5160            .const_f32_like(
5161                vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
5162                Shape::from_dims(&[3, 2]),
5163            )
5164            .unwrap();
5165        let c = a.matmul(&b).unwrap();
5166        let cpu = c.realize_f32();
5167        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5168        let cuda = c.realize_f32_cuda(&exe);
5169        assert_eq!(cpu.len(), cuda.len());
5170        for (i, (a, b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5171            assert!((a - b).abs() < 1e-3, "matmul[{i}]: cpu={a}, cuda={b}",);
5172        }
5173    }
5174
5175    #[test]
5176    #[cfg(feature = "cuda")]
5177    fn cuda_executor_matches_cpu_on_broadcast_matmul() {
5178        // Rank-3 × rank-2 matmul (what the transformer forward does).
5179        // The graph auto-broadcasts the rank-2 to rank-3.
5180        let x = Tensor::from_f32(
5181            (0..12).map(|i| i as f32 * 0.1).collect::<Vec<_>>(),
5182            Shape::from_dims(&[1, 3, 4]),
5183            &Device::cpu(),
5184        )
5185        .unwrap();
5186        let w = x
5187            .const_f32_like(
5188                (0..8).map(|i| i as f32 * 0.2).collect::<Vec<_>>(),
5189                Shape::from_dims(&[4, 2]),
5190            )
5191            .unwrap();
5192        let y = x.matmul(&w).unwrap();
5193        let cpu = y.realize_f32();
5194        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5195        let cuda = y.realize_f32_cuda(&exe);
5196        assert_eq!(cpu.len(), cuda.len());
5197        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5198            assert!((a - b).abs() < 1e-3, "bcast_mm[{i}]: cpu={a}, cuda={b}");
5199        }
5200    }
5201
5202    #[test]
5203    #[cfg(feature = "cuda")]
5204    fn cuda_executor_matches_cpu_on_permute() {
5205        let x = Tensor::from_f32(
5206            (0..24).map(|i| i as f32).collect::<Vec<_>>(),
5207            Shape::from_dims(&[1, 2, 3, 4]),
5208            &Device::cpu(),
5209        )
5210        .unwrap();
5211        let y = x.permute([0, 2, 1, 3_usize]).unwrap();
5212        let cpu = y.realize_f32();
5213        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5214        let cuda = y.realize_f32_cuda(&exe);
5215        assert_eq!(cpu, cuda, "permute mismatch");
5216    }
5217
5218    #[test]
5219    #[cfg(feature = "cuda")]
5220    fn cuda_executor_matches_cpu_on_softmax() {
5221        let x = Tensor::from_f32(
5222            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5223            Shape::from_dims(&[2, 3]),
5224            &Device::cpu(),
5225        )
5226        .unwrap();
5227        let y = x.softmax_last_dim().unwrap();
5228        let cpu = y.realize_f32();
5229        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5230        let cuda = y.realize_f32_cuda(&exe);
5231        assert_eq!(cpu.len(), cuda.len());
5232        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5233            assert!((a - b).abs() < 1e-4, "softmax[{i}]: cpu={a}, cuda={b}");
5234        }
5235    }
5236
5237    /// Phase 7.5 PR 3 / 3.5 live CUDA equivalence: realize a graph with
5238    /// `Op::SoftmaxLastDim` through the rule-registry pipeline using
5239    /// `RuleRegistry::lowering_only()` so the executor sees the
5240    /// 7-node lowered subgraph instead of the fused op. The composed
5241    /// CUDA execution path (ReduceMaxTo + BroadcastTo + Sub + Exp +
5242    /// ReduceSumTo + BroadcastTo + Div) must match the fused CPU
5243    /// baseline within tight epsilon.
5244    ///
5245    /// Post PR-3.5 follow-up: ReduceMaxTo / ReduceSumTo run natively
5246    /// on CUDA via the legacy executor's `Op::ReduceXxxTo` arm (which
5247    /// delegates to `backend.reduce` and relabels the result to the
5248    /// keepdim shape), so the lowered subgraph stays GPU-resident
5249    /// end-to-end. Two D2H/H2D round-trips per softmax used to be
5250    /// the cost on the prior commit — both gone now.
5251    #[test]
5252    #[cfg(feature = "cuda")]
5253    fn cuda_executor_matches_cpu_on_softmax_via_lowering() {
5254        // Use a non-trivial input shape so the broadcast paths and
5255        // the ReduceSumTo step both have actual work to do.
5256        let n = 24;
5257        let last = 5;
5258        let data: Vec<f32> = (0..n * last)
5259            .map(|i| ((i as f32) * 0.13).sin() * 2.0 - 0.7)
5260            .collect();
5261        let x = Tensor::from_f32(data, Shape::from_dims(&[n, last]), &Device::cpu()).unwrap();
5262        let y = x.softmax_last_dim().unwrap();
5263
5264        // CPU baseline: fused SoftmaxLastDim through the standard
5265        // realize_f32 path (no rule-registry pipeline involved).
5266        let cpu = y.realize_f32();
5267
5268        // CUDA via the lowered subgraph: run the lowering-only
5269        // rule registry to fixpoint first so fusion can't re-collapse
5270        // the lowered pattern back to Op::SoftmaxLastDim. Then
5271        // realize the remapped target via PipelinedExecutor.
5272        // (Phase 7.6 step 9c E.2: optimizer is caller-composed.)
5273        let graph = y.inner.graph().clone();
5274        let registry = fuel_graph::opt::RuleRegistry::lowering_only();
5275        let remapped = registry.optimize_to_fixpoint(&graph, &[y.inner.id()]);
5276        let dev = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5277        let fc_device: crate::Device = dev.clone().into();
5278        let cuda = crate::pipelined_bridge::realize_one_as::<f32>(&graph, remapped[0], &fc_device)
5279            .expect("realize lowered softmax on CUDA");
5280
5281        assert_eq!(cpu.len(), cuda.len());
5282        let mut max_abs_err = 0.0_f32;
5283        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5284            let err = (a - b).abs();
5285            if err > max_abs_err {
5286                max_abs_err = err;
5287            }
5288            assert!(
5289                err < 1e-5,
5290                "lowered softmax[{i}]: cpu={a} (fused), cuda={b} (composed), err={err}",
5291            );
5292        }
5293        eprintln!("max_abs_err over lowered-vs-fused softmax: {max_abs_err:.3e}");
5294    }
5295
5296    #[test]
5297    #[cfg(feature = "cuda")]
5298    fn cuda_executor_matches_cpu_on_concat_slice() {
5299        let a = Tensor::from_f32(
5300            vec![1.0, 2.0, 3.0, 4.0],
5301            Shape::from_dims(&[2, 2]),
5302            &Device::cpu(),
5303        )
5304        .unwrap();
5305        let b = a
5306            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], Shape::from_dims(&[2, 2]))
5307            .unwrap();
5308        let cat = a.concat(&b, 1).unwrap(); // [2, 4]
5309        let sliced = cat.slice(1, 1, 2).unwrap(); // [2, 2]
5310        let cpu = sliced.realize_f32();
5311        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5312        let cuda = sliced.realize_f32_cuda(&exe);
5313        assert_eq!(cpu, cuda, "concat+slice mismatch");
5314    }
5315
5316    #[test]
5317    #[cfg(feature = "cuda")]
5318    fn cuda_executor_matches_cpu_on_rms_norm() {
5319        let x = Tensor::from_f32(
5320            (0..8).map(|i| i as f32 * 0.5 - 1.5).collect::<Vec<_>>(),
5321            Shape::from_dims(&[2, 4]),
5322            &Device::cpu(),
5323        )
5324        .unwrap();
5325        let y = x.rms_norm_last_dim(1e-5).unwrap();
5326        let cpu = y.realize_f32();
5327        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5328        let cuda = y.realize_f32_cuda(&exe);
5329        assert_eq!(cpu.len(), cuda.len());
5330        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5331            assert!((a - b).abs() < 1e-3, "rms_norm[{i}]: cpu={a}, cuda={b}");
5332        }
5333    }
5334
5335    #[test]
5336    fn realize_f64_through_bridge() {
5337        let a =
5338            Tensor::from_f64(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5339        let b = a.mul(&a).unwrap();
5340        assert_eq!(b.realize_f64(), vec![2.25, 6.25, 12.25]);
5341    }
5342
5343    /// GAP-327 regression test (was the born-red probe; now LIVE — the guard has landed).
5344    ///
5345    /// The realize funnel `pipelined_bridge::extract_cpu_bytes_typed` guards the byte
5346    /// reinterpretation on the root's dtype: `realize_one_as::<T>` returns
5347    /// `Error::UnexpectedDType` on a mismatch, and the typed `realize_fNN` accessors (which
5348    /// `.expect` that result) panic. The BYTE VIEW `realize_one_bytes` is the deliberate
5349    /// UNGUARDED escape hatch and still returns raw bytes for any dtype. Measured by probe
5350    /// (GAP-327) before the fix: realize_f32()/realize_one_as::<f32> on an F64 [1.0, 2.0]
5351    /// root returned Ok([0.0, 1.875, 0.0, 2.0]) — silent reinterpretation; this asserts that
5352    /// is now rejected while the byte view is not. See docs/gaps.md GAP-327.
5353    #[test]
5354    fn gap327_realize_f32_on_f64_root_must_reject_not_reinterpret() {
5355        let t =
5356            Tensor::from_f64(vec![1.0_f64, 2.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
5357        let graph = t.inner.graph().clone();
5358        let target = t.inner.id();
5359        let device = Device::cpu();
5360
5361        // Silence the panic hook only around the catch_unwind measurements; restore it
5362        // before the assertions so a real failure still prints.
5363        let prev_hook = std::panic::take_hook();
5364        std::panic::set_hook(Box::new(|_| {}));
5365        // Control 1 (RIGHT dtype): realize_f64 on the F64 root succeeds.
5366        let ctl_f64 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f64()));
5367        // Control 2 (guard FIRES): a MISMATCHED guarded accessor panics — proves the harness
5368        // observes guards, so the subject rejection below is real and not a swallowed nothing.
5369        let ctl_f16 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f16()));
5370        // SUBJECT A: realize_f32 on the F64 root must now panic (guard -> Err -> .expect).
5371        let subj_method =
5372            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f32()));
5373        std::panic::set_hook(prev_hook);
5374
5375        // SUBJECT B: realize_one_as::<f32> must return Err(UnexpectedDType) (matched by variant).
5376        let subj_raw = crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device);
5377        // BYTE VIEW: the unguarded escape hatch must still return the root's RAW bytes
5378        // (2 x f64 = 16 bytes) — a dtype mismatch is NOT an error for the byte view.
5379        let bytes_view = crate::pipelined_bridge::realize_one_bytes(&graph, target, &device);
5380
5381        assert!(
5382            ctl_f64.is_ok(),
5383            "control: realize_f64 on an F64 root must succeed; got {ctl_f64:?}"
5384        );
5385        assert!(
5386            ctl_f16.is_err(),
5387            "positive control: realize_f16() on an F64 root must panic (guard fires); if it \
5388             does not, the harness is not observing panics and the subject asserts are vacuous"
5389        );
5390        assert!(
5391            subj_method.is_err(),
5392            "realize_f32() on an F64 root must REJECT (panic), not silently reinterpret bytes"
5393        );
5394        assert!(
5395            matches!(subj_raw, Err(fuel_ir::Error::UnexpectedDType { .. })),
5396            "realize_one_as::<f32> on an F64 root must return Err(UnexpectedDType), not \
5397             Ok(reinterpreted bytes); got {subj_raw:?}"
5398        );
5399        assert!(
5400            matches!(&bytes_view, Ok(b) if b.len() == 16),
5401            "byte view realize_one_bytes on an F64 [1.0, 2.0] root must return 16 raw bytes \
5402             (unguarded), not an error; got {bytes_view:?}"
5403        );
5404    }
5405
5406    #[test]
5407    fn lazy_tensor_mini_llama_block_forward() {
5408        // A minimal LLaMA-style attention-only "block" built entirely
5409        // through Tensor. No training, just the forward pass:
5410        //
5411        //   h = x + (RmsNorm(x) @ W_qkv → split Q/K/V → RoPE → attention → out proj)
5412        //
5413        // This is the sanity check that every LLaMA primitive is
5414        // reachable through the bridge's API, and that the bridge's
5415        // realize_f32 call actually runs the whole thing.
5416        let seq = 3;
5417        let d_head = 4; // must be even for RoPE
5418        let num_heads = 2;
5419        let d_model = num_heads * d_head; // 8
5420
5421        // Fake input: [1, seq, d_model]
5422        let x_data: Vec<f32> = (0..seq * d_model).map(|i| i as f32 * 0.01).collect();
5423        let x =
5424            Tensor::from_f32(x_data, Shape::from_dims(&[1, seq, d_model]), &Device::cpu()).unwrap();
5425
5426        // Fake weights (just identities for simplicity — makes the
5427        // test easy to verify output finiteness without needing to
5428        // hand-compute).
5429        let w_q = x
5430            .const_f32_like(
5431                identity_matrix(d_model),
5432                Shape::from_dims(&[d_model, d_model]),
5433            )
5434            .unwrap();
5435        let w_k = x
5436            .const_f32_like(
5437                identity_matrix(d_model),
5438                Shape::from_dims(&[d_model, d_model]),
5439            )
5440            .unwrap();
5441        let w_v = x
5442            .const_f32_like(
5443                identity_matrix(d_model),
5444                Shape::from_dims(&[d_model, d_model]),
5445            )
5446            .unwrap();
5447        let w_o = x
5448            .const_f32_like(
5449                identity_matrix(d_model),
5450                Shape::from_dims(&[d_model, d_model]),
5451            )
5452            .unwrap();
5453
5454        // RmsNorm → Q/K/V projection (auto-broadcasting matmul).
5455        let x_norm = x.rms_norm_last_dim(1e-6).unwrap();
5456        let q = x_norm.matmul(&w_q).unwrap();
5457        let k = x_norm.matmul(&w_k).unwrap();
5458        let v = x_norm.matmul(&w_v).unwrap();
5459
5460        // Split heads: [1, seq, 8] → [1, seq, 2, 4] → [1, 2, seq, 4]
5461        let q_h = q
5462            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5463            .unwrap()
5464            .permute([0, 2, 1, 3_usize])
5465            .unwrap();
5466        let k_h = k
5467            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5468            .unwrap()
5469            .permute([0, 2, 1, 3_usize])
5470            .unwrap();
5471        let v_h = v
5472            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5473            .unwrap()
5474            .permute([0, 2, 1, 3_usize])
5475            .unwrap();
5476
5477        // RoPE on Q and K.
5478        let q_r = q_h.rope(10000.0, 0).unwrap();
5479        let k_r = k_h.rope(10000.0, 0).unwrap();
5480
5481        // Scaled dot-product attention.
5482        let k_t = k_r.transpose().unwrap();
5483        let scores = q_r.matmul(&k_t).unwrap();
5484        let attn = scores.softmax_last_dim().unwrap();
5485        let attn_v = attn.matmul(&v_h).unwrap();
5486
5487        // Merge heads + output projection.
5488        let merged = attn_v
5489            .permute([0, 2, 1, 3_usize])
5490            .unwrap()
5491            .reshape(Shape::from_dims(&[1, seq, d_model]))
5492            .unwrap();
5493        let attn_out = merged.matmul(&w_o).unwrap();
5494        let h = x.add(&attn_out).unwrap();
5495
5496        // Realize end-to-end through the bridge.
5497        let result = h.realize_f32();
5498        assert_eq!(result.len(), seq * d_model);
5499        for &v in &result {
5500            assert!(
5501                v.is_finite(),
5502                "bridge-based LLaMA block output non-finite: {v}"
5503            );
5504        }
5505    }
5506
5507    /// Build an identity matrix of size `n × n` in row-major layout.
5508    fn identity_matrix(n: usize) -> Vec<f32> {
5509        let mut out = vec![0.0_f32; n * n];
5510        for i in 0..n {
5511            out[i * n + i] = 1.0;
5512        }
5513        out
5514    }
5515}
5516
5517// Helper method on the wrapper that we didn't include above because the
5518// main struct's `impl` block was getting long. Kept in its own small
5519// `impl` for readability.
5520impl Tensor {
5521    /// Build a second const U32 (index) tensor on the same graph.
5522    pub fn const_u32_like(
5523        &self,
5524        data: impl Into<Arc<[u32]>>,
5525        shape: impl Into<Shape>,
5526    ) -> std::result::Result<Self, fuel_ir::Error> {
5527        Ok(Self {
5528            inner: self.inner.const_u32_like(data, shape)?,
5529        })
5530    }
5531
5532    /// Push a [`fuel_graph::Op::Const`] node on the same graph as
5533    /// `self` **without** populating the graph's storage_map. The
5534    /// caller binds the storage Arc into the realize call via
5535    /// [`InferenceContext::insert`](crate::inference_context::InferenceContext::insert).
5536    ///
5537    /// Used by the Phase E.3.3 forward path to bind pre-allocated
5538    /// KV-cache storage Arcs (`Arc<RwLock<fuel_memory::Storage>>`)
5539    /// into a per-step graph — the graph's legacy storage_map only
5540    /// holds `fuel_backend_contract::Storage`, so direct binding isn't
5541    /// possible without a type conversion.
5542    pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: fuel_ir::DType) -> Self {
5543        Self {
5544            inner: self.inner.const_placeholder_like(shape, dtype),
5545        }
5546    }
5547
5548    /// Append an [`fuel_graph::Op::WriteSlice`] node. Copies `source`'s
5549    /// bytes into `self` at the rectangular slab defined by `ranges`
5550    /// and returns a tensor whose Storage Arc is `self`'s — i.e. the
5551    /// post-write reference to the same underlying buffer.
5552    ///
5553    /// Destructive on `self`: after the write, downstream consumers
5554    /// must read the bytes through the returned tensor's NodeId, not
5555    /// `self`'s.
5556    ///
5557    /// **Returns `Result`**: rank/shape/range mismatches surface as a
5558    /// typed error.
5559    pub fn write_slice(&self, source: &Self, ranges: Vec<(usize, usize)>) -> crate::Result<Self> {
5560        let inner = self.inner.write_slice(&source.inner, ranges)?;
5561        Ok(Self { inner })
5562    }
5563
5564    /// Append an [`fuel_graph::Op::WriteSlice`] whose start on `dyn_axis`
5565    /// is a **runtime** value resolved through the per-pass `SymEnv` at
5566    /// realize (Phase D symbolic extents). `ranges[dyn_axis].0` is
5567    /// ignored (the start is dynamic); the slab width
5568    /// `ranges[dyn_axis].1 - ranges[dyn_axis].0` must equal `source`'s
5569    /// `dyn_axis` dim and not exceed the destination capacity. Backs the
5570    /// persistent decode KV-cache write at the per-token `cached_len`.
5571    pub fn write_slice_dyn(
5572        &self,
5573        source: &Self,
5574        ranges: Vec<(usize, usize)>,
5575        dyn_axis: usize,
5576        offset: fuel_ir::DynScalar,
5577    ) -> crate::Result<Self> {
5578        let inner = self
5579            .inner
5580            .write_slice_dyn(&source.inner, ranges, dyn_axis, offset)?;
5581        Ok(Self { inner })
5582    }
5583
5584    /// Append an [`fuel_graph::Op::WriteSliceRotating`] node — like
5585    /// [`Self::write_slice`] but the `axis` axis wraps modulo
5586    /// `modulus`. `position` is a rank-0 U32 tensor whose value (read
5587    /// at realize time) is wrapped modulo `modulus` to determine the
5588    /// dynamic write start on `axis`. `ranges[axis].0` is ignored
5589    /// (the rotating-axis start is dynamic); the slab width
5590    /// `ranges[axis].1 - ranges[axis].0` must equal `source`'s
5591    /// `axis` dim and must not exceed `modulus`.
5592    ///
5593    /// Destructive on `self`: same scheduling as `write_slice`.
5594    /// Backs sliding-window KV caches (Mistral / Phi-3 sliding-
5595    /// window). Returns `Result`: rank / dtype / axis-bound /
5596    /// modulus / range mismatches surface as typed errors at
5597    /// build time.
5598    pub fn write_slice_rotating(
5599        &self,
5600        source: &Self,
5601        position: &Self,
5602        axis: usize,
5603        modulus: usize,
5604        ranges: Vec<(usize, usize)>,
5605    ) -> crate::Result<Self> {
5606        let inner = self.inner.write_slice_rotating(
5607            &source.inner,
5608            &position.inner,
5609            axis,
5610            modulus,
5611            ranges,
5612        )?;
5613        Ok(Self { inner })
5614    }
5615
5616    /// Append a [`fuel_graph::Op::WriteSliceDoff`] node — write `source`
5617    /// into a slab of `self` whose start on `axis` is read from `offset`
5618    /// (a rank-0 `I64` tensor) **device-side** at kernel launch. No
5619    /// modulo wrap: `offset` is the raw start on `axis`.
5620    /// `ranges[axis].0` is ignored; `ranges[axis].1 - ranges[axis].0`
5621    /// is the write width on `axis` and must equal `source`'s `axis`
5622    /// dim. Bounds (`offset + width <= dest_dims[axis]`) are the
5623    /// caller's contract (device-only at build). Destructive on `self`;
5624    /// same scheduling as `write_slice`. Backs the CUDA-graph-
5625    /// capturable KV-cache append (CapturedRun / `DecodeSession`).
5626    /// Returns `Result`: rank / dtype / axis-bound / static-width /
5627    /// offset-dtype mismatches surface as typed errors at build time.
5628    pub fn write_slice_doff(
5629        &self,
5630        source: &Self,
5631        offset: &Self,
5632        axis: usize,
5633        ranges: Vec<(usize, usize)>,
5634    ) -> crate::Result<Self> {
5635        let inner = self
5636            .inner
5637            .write_slice_doff(&source.inner, &offset.inner, axis, ranges)?;
5638        Ok(Self { inner })
5639    }
5640
5641    /// Append a [`fuel_graph::Op::Fused`] node carrying
5642    /// [`fuel_graph::registry::FusedOpParams::Conv2D`]. See `fuel_graph`'s
5643    /// `Tensor::conv2d` for the full shape contract: `self` must be
5644    /// `[N, Cin, H, W]`; `weight` must be `[Cout, Cin/groups, Kh, Kw]`;
5645    /// `bias` is optional and must be `[Cout]` when provided. Returns
5646    /// a rank-4 lazy tensor `[N, Cout, Hout, Wout]`.
5647    ///
5648    /// Rank / channel / `groups` / stride mismatches surface as typed
5649    /// errors at build time rather than panicking inside the inner
5650    /// `fuel_graph` call.
5651    pub fn conv2d(
5652        &self,
5653        weight: &Self,
5654        bias: Option<&Self>,
5655        stride: (usize, usize),
5656        padding: (usize, usize),
5657        groups: usize,
5658    ) -> std::result::Result<Self, fuel_ir::Error> {
5659        if groups < 1 {
5660            return Err(
5661                fuel_ir::Error::Msg(format!("conv2d: groups must be >= 1, got {groups}",)).bt(),
5662            );
5663        }
5664        let x_shape = self.inner.shape();
5665        let x_dims = x_shape.dims();
5666        let w_shape = weight.inner.shape();
5667        let w_dims = w_shape.dims();
5668        if x_dims.len() != 4 {
5669            return Err(fuel_ir::Error::Msg(format!(
5670                "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
5671            ))
5672            .bt());
5673        }
5674        if w_dims.len() != 4 {
5675            return Err(fuel_ir::Error::Msg(format!(
5676                "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
5677            ))
5678            .bt());
5679        }
5680        let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
5681        let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
5682        if cin != cin_per_g * groups {
5683            return Err(fuel_ir::Error::Msg(format!(
5684                "conv2d: x has {cin} in-channels but weight expects {} ({cin_per_g}*{groups})",
5685                cin_per_g * groups,
5686            ))
5687            .bt());
5688        }
5689        if cout % groups != 0 {
5690            return Err(fuel_ir::Error::Msg(format!(
5691                "conv2d: Cout={cout} must be divisible by groups={groups}",
5692            ))
5693            .bt());
5694        }
5695        if let Some(b) = bias {
5696            let b_shape = b.inner.shape();
5697            let b_dims = b_shape.dims();
5698            if b_dims != [cout] {
5699                return Err(fuel_ir::Error::Msg(format!(
5700                    "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
5701                ))
5702                .bt());
5703            }
5704        }
5705        let (stride_h, stride_w) = stride;
5706        let (pad_h, pad_w) = padding;
5707        if stride_h < 1 || stride_w < 1 {
5708            return Err(fuel_ir::Error::Msg(format!(
5709                "conv2d: stride must be >= 1, got ({stride_h}, {stride_w})",
5710            ))
5711            .bt());
5712        }
5713        let h_padded = h_in + 2 * pad_h;
5714        let w_padded = w_in + 2 * pad_w;
5715        if h_padded < kh || w_padded < kw {
5716            return Err(fuel_ir::Error::Msg(format!(
5717                "conv2d: padded input ({h_padded}x{w_padded}) smaller than kernel ({kh}x{kw})",
5718            ))
5719            .bt());
5720        }
5721        Ok(Self {
5722            inner: self.inner.conv2d(
5723                &weight.inner,
5724                bias.map(|b| &b.inner),
5725                stride,
5726                padding,
5727                groups,
5728            ),
5729        })
5730    }
5731
5732    /// Append a [`fuel_graph::Op::Fused`] node carrying
5733    /// [`fuel_graph::registry::FusedOpParams::FlashAttn`]. `self` is `q`
5734    /// of shape `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]`
5735    /// with `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional)
5736    /// is `[Hq]`. Returns the attention output, shape `[B, Hq, Sq, D]`.
5737    ///
5738    /// Rank / batch / GQA-divisibility / head-dim mismatches surface
5739    /// as typed errors at build time rather than panicking inside the
5740    /// inner `fuel_graph` call.
5741    pub fn flash_attn(
5742        &self,
5743        k: &Self,
5744        v: &Self,
5745        alibi_slopes: Option<&Self>,
5746        softmax_scale: f32,
5747        causal: bool,
5748        window_size_left: Option<usize>,
5749        window_size_right: Option<usize>,
5750        softcap: Option<f32>,
5751    ) -> std::result::Result<Self, fuel_ir::Error> {
5752        let q_shape = self.inner.shape();
5753        let q_dims = q_shape.dims();
5754        let k_shape = k.inner.shape();
5755        let k_dims = k_shape.dims();
5756        let v_shape = v.inner.shape();
5757        let v_dims = v_shape.dims();
5758        if q_dims.len() != 4 {
5759            return Err(fuel_ir::Error::Msg(format!(
5760                "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5761            ))
5762            .bt());
5763        }
5764        if k_dims.len() != 4 {
5765            return Err(fuel_ir::Error::Msg(format!(
5766                "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}",
5767            ))
5768            .bt());
5769        }
5770        if v_dims.len() != 4 {
5771            return Err(fuel_ir::Error::Msg(format!(
5772                "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}",
5773            ))
5774            .bt());
5775        }
5776        let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5777        let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5778        let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5779        if b != bk || b != bv {
5780            return Err(fuel_ir::Error::Msg(
5781                format!("flash_attn: B mismatch q={b} k={bk} v={bv}",),
5782            )
5783            .bt());
5784        }
5785        if hkv != hkv_v {
5786            return Err(fuel_ir::Error::Msg(format!(
5787                "flash_attn: Hkv mismatch k={hkv} vs v={hkv_v}",
5788            ))
5789            .bt());
5790        }
5791        if sk != sk_v {
5792            return Err(fuel_ir::Error::Msg(
5793                format!("flash_attn: Sk mismatch k={sk} vs v={sk_v}",),
5794            )
5795            .bt());
5796        }
5797        if d != dk || d != dv {
5798            return Err(fuel_ir::Error::Msg(format!(
5799                "flash_attn: head_dim mismatch q={d} k={dk} v={dv}",
5800            ))
5801            .bt());
5802        }
5803        if hkv == 0 || hq % hkv != 0 {
5804            return Err(fuel_ir::Error::Msg(format!(
5805                "flash_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5806            ))
5807            .bt());
5808        }
5809        if let Some(a) = alibi_slopes {
5810            let a_shape = a.inner.shape();
5811            let a_dims = a_shape.dims();
5812            if a_dims != [hq] {
5813                return Err(fuel_ir::Error::Msg(format!(
5814                    "flash_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5815                ))
5816                .bt());
5817            }
5818        }
5819        Ok(Self {
5820            inner: self.inner.flash_attn(
5821                &k.inner,
5822                &v.inner,
5823                alibi_slopes.map(|t| &t.inner),
5824                softmax_scale,
5825                causal,
5826                window_size_left,
5827                window_size_right,
5828                softcap,
5829            ),
5830        })
5831    }
5832
5833    /// Append a [`fuel_graph::Op::Fused`] node carrying
5834    /// [`fuel_graph::registry::FusedOpParams::PagedAttn`]. `self` is the Q
5835    /// tensor `[B, Hq, Sq, D]`. `k_cache` / `v_cache` are paged caches
5836    /// `[num_blocks, block_size, Hkv, D]`. `block_table` is `[B,
5837    /// max_blocks]` u32; `context_lens` is `[B]` u32.
5838    ///
5839    /// Rank / batch / GQA-divisibility / block-size / dtype mismatches
5840    /// surface as typed errors at build time rather than panicking
5841    /// inside the inner `fuel_graph` call.
5842    pub fn paged_attn(
5843        &self,
5844        k_cache: &Self,
5845        v_cache: &Self,
5846        block_table: &Self,
5847        context_lens: &Self,
5848        alibi_slopes: Option<&Self>,
5849        softmax_scale: f32,
5850        block_size: usize,
5851        softcap: Option<f32>,
5852    ) -> std::result::Result<Self, fuel_ir::Error> {
5853        if block_size < 1 {
5854            return Err(fuel_ir::Error::Msg("paged_attn: block_size must be >= 1".into()).bt());
5855        }
5856        let q_shape = self.inner.shape();
5857        let q_dims = q_shape.dims();
5858        let kc_shape = k_cache.inner.shape();
5859        let kc_dims = kc_shape.dims();
5860        let vc_shape = v_cache.inner.shape();
5861        let vc_dims = vc_shape.dims();
5862        let bt_shape = block_table.inner.shape();
5863        let bt_dims = bt_shape.dims();
5864        let cl_shape = context_lens.inner.shape();
5865        let cl_dims = cl_shape.dims();
5866        if q_dims.len() != 4 {
5867            return Err(fuel_ir::Error::Msg(format!(
5868                "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5869            ))
5870            .bt());
5871        }
5872        if kc_dims.len() != 4 {
5873            return Err(fuel_ir::Error::Msg(format!(
5874                "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}",
5875            )).bt());
5876        }
5877        if vc_dims.len() != 4 {
5878            return Err(fuel_ir::Error::Msg(format!(
5879                "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}",
5880            )).bt());
5881        }
5882        if bt_dims.len() != 2 {
5883            return Err(fuel_ir::Error::Msg(format!(
5884                "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}",
5885            ))
5886            .bt());
5887        }
5888        if cl_dims.len() != 1 {
5889            return Err(fuel_ir::Error::Msg(format!(
5890                "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}",
5891            ))
5892            .bt());
5893        }
5894        let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5895        if kc_dims[1] != block_size {
5896            return Err(fuel_ir::Error::Msg(format!(
5897                "paged_attn: k_cache block dim {} != block_size {block_size}",
5898                kc_dims[1],
5899            ))
5900            .bt());
5901        }
5902        if vc_dims[1] != block_size {
5903            return Err(fuel_ir::Error::Msg(format!(
5904                "paged_attn: v_cache block dim {} != block_size {block_size}",
5905                vc_dims[1],
5906            ))
5907            .bt());
5908        }
5909        let hkv = kc_dims[2];
5910        if vc_dims[2] != hkv {
5911            return Err(fuel_ir::Error::Msg(format!(
5912                "paged_attn: Hkv mismatch k_cache={hkv} vs v_cache={}",
5913                vc_dims[2],
5914            ))
5915            .bt());
5916        }
5917        if kc_dims[3] != d || vc_dims[3] != d {
5918            return Err(fuel_ir::Error::Msg(format!(
5919                "paged_attn: D mismatch q={d} k={} v={}",
5920                kc_dims[3], vc_dims[3],
5921            ))
5922            .bt());
5923        }
5924        if hkv == 0 || hq % hkv != 0 {
5925            return Err(fuel_ir::Error::Msg(format!(
5926                "paged_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5927            ))
5928            .bt());
5929        }
5930        if bt_dims[0] != b {
5931            return Err(fuel_ir::Error::Msg(format!(
5932                "paged_attn: block_table batch dim {} != B={b}",
5933                bt_dims[0],
5934            ))
5935            .bt());
5936        }
5937        if cl_dims[0] != b {
5938            return Err(fuel_ir::Error::Msg(format!(
5939                "paged_attn: context_lens len {} != B={b}",
5940                cl_dims[0],
5941            ))
5942            .bt());
5943        }
5944        if block_table.inner.dtype() != fuel_ir::DType::U32 {
5945            return Err(fuel_ir::Error::Msg(format!(
5946                "paged_attn: block_table must be U32, got {:?}",
5947                block_table.inner.dtype(),
5948            ))
5949            .bt());
5950        }
5951        if context_lens.inner.dtype() != fuel_ir::DType::U32 {
5952            return Err(fuel_ir::Error::Msg(format!(
5953                "paged_attn: context_lens must be U32, got {:?}",
5954                context_lens.inner.dtype(),
5955            ))
5956            .bt());
5957        }
5958        if let Some(a) = alibi_slopes {
5959            let a_shape = a.inner.shape();
5960            let a_dims = a_shape.dims();
5961            if a_dims != [hq] {
5962                return Err(fuel_ir::Error::Msg(format!(
5963                    "paged_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5964                ))
5965                .bt());
5966            }
5967        }
5968        Ok(Self {
5969            inner: self.inner.paged_attn(
5970                &k_cache.inner,
5971                &v_cache.inner,
5972                &block_table.inner,
5973                &context_lens.inner,
5974                alibi_slopes.map(|t| &t.inner),
5975                softmax_scale,
5976                block_size,
5977                softcap,
5978            ),
5979        })
5980    }
5981
5982    /// Append a [`fuel_graph::Op::Fused`] node carrying
5983    /// [`fuel_graph::registry::FusedOpParams::ConvTranspose2D`]. `self` must
5984    /// be `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
5985    /// (note transposed channel order vs `conv2d`). Returns a rank-4
5986    /// lazy tensor `[N, Cout, Hout, Wout]`.
5987    ///
5988    /// Rank / channel / `groups` / stride / dilation mismatches surface
5989    /// as typed errors at build time rather than panicking inside the
5990    /// inner `fuel_graph` call.
5991    pub fn conv_transpose2d(
5992        &self,
5993        weight: &Self,
5994        stride: (usize, usize),
5995        padding: (usize, usize),
5996        output_padding: (usize, usize),
5997        dilation: (usize, usize),
5998        groups: usize,
5999    ) -> std::result::Result<Self, fuel_ir::Error> {
6000        if groups < 1 {
6001            return Err(fuel_ir::Error::Msg(format!(
6002                "conv_transpose2d: groups must be >= 1, got {groups}",
6003            ))
6004            .bt());
6005        }
6006        let x_shape = self.inner.shape();
6007        let x_dims = x_shape.dims();
6008        let w_shape = weight.inner.shape();
6009        let w_dims = w_shape.dims();
6010        if x_dims.len() != 4 {
6011            return Err(fuel_ir::Error::Msg(format!(
6012                "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
6013            ))
6014            .bt());
6015        }
6016        if w_dims.len() != 4 {
6017            return Err(fuel_ir::Error::Msg(format!(
6018                "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
6019            )).bt());
6020        }
6021        let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
6022        let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
6023        if cin != cin_w {
6024            return Err(fuel_ir::Error::Msg(format!(
6025                "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
6026            ))
6027            .bt());
6028        }
6029        if cin % groups != 0 {
6030            return Err(fuel_ir::Error::Msg(format!(
6031                "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
6032            ))
6033            .bt());
6034        }
6035        let (stride_h, stride_w) = stride;
6036        let (pad_h, pad_w) = padding;
6037        let (out_pad_h, out_pad_w) = output_padding;
6038        let (dil_h, dil_w) = dilation;
6039        if stride_h < 1 || stride_w < 1 {
6040            return Err(fuel_ir::Error::Msg(format!(
6041                "conv_transpose2d: stride must be >= 1, got ({stride_h}, {stride_w})",
6042            ))
6043            .bt());
6044        }
6045        if dil_h < 1 || dil_w < 1 {
6046            return Err(fuel_ir::Error::Msg(format!(
6047                "conv_transpose2d: dilation must be >= 1, got ({dil_h}, {dil_w})",
6048            ))
6049            .bt());
6050        }
6051        let h_out = h_in.saturating_sub(1) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
6052        let w_out = w_in.saturating_sub(1) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
6053        if h_out <= 2 * pad_h || w_out <= 2 * pad_w {
6054            return Err(fuel_ir::Error::Msg(format!(
6055                "conv_transpose2d: padding ({pad_h}x{pad_w}) is larger than the produced output dims ({h_out}x{w_out})",
6056            )).bt());
6057        }
6058        let _ = cout_per_g;
6059        Ok(Self {
6060            inner: self.inner.conv_transpose2d(
6061                &weight.inner,
6062                stride,
6063                padding,
6064                output_padding,
6065                dilation,
6066                groups,
6067            ),
6068        })
6069    }
6070
6071    /// Append a transposed 1D convolution. `self` is
6072    /// `[N, Cin, Lin]`; `weight` is `[Cin, Cout/groups, K]`
6073    /// (PyTorch channel order). Returns `[N, Cout, Lout]`.
6074    ///
6075    /// Internally lifts to rank-4 and dispatches through
6076    /// `conv_transpose2d` — there is no separate 1D op in the
6077    /// IR; the lift is transparent to the executor (which sees
6078    /// the same `Op::Fused(CONV_TRANSPOSE2D, _)` it already
6079    /// dispatches CPU kernels for).
6080    ///
6081    /// Unblocks audio codec decoders (DAC, EnCodec, SNAC, Mimi,
6082    /// Parler-TTS, MetaVoice, CSM) which all upsample quantized
6083    /// latents to waveform via strided transposed convs.
6084    pub fn conv_transpose1d(
6085        &self,
6086        weight: &Self,
6087        stride: usize,
6088        padding: usize,
6089        output_padding: usize,
6090        dilation: usize,
6091        groups: usize,
6092    ) -> std::result::Result<Self, fuel_ir::Error> {
6093        if groups < 1 {
6094            return Err(fuel_ir::Error::Msg(format!(
6095                "conv_transpose1d: groups must be >= 1, got {groups}",
6096            ))
6097            .bt());
6098        }
6099        let x_shape = self.inner.shape();
6100        let x_dims = x_shape.dims();
6101        let w_shape = weight.inner.shape();
6102        let w_dims = w_shape.dims();
6103        if x_dims.len() != 3 {
6104            return Err(fuel_ir::Error::Msg(format!(
6105                "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
6106            ))
6107            .bt());
6108        }
6109        if w_dims.len() != 3 {
6110            return Err(fuel_ir::Error::Msg(format!(
6111                "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
6112            ))
6113            .bt());
6114        }
6115        if stride < 1 {
6116            return Err(fuel_ir::Error::Msg(format!(
6117                "conv_transpose1d: stride must be >= 1, got {stride}",
6118            ))
6119            .bt());
6120        }
6121        if dilation < 1 {
6122            return Err(fuel_ir::Error::Msg(format!(
6123                "conv_transpose1d: dilation must be >= 1, got {dilation}",
6124            ))
6125            .bt());
6126        }
6127        let cin = x_dims[1];
6128        let cin_w = w_dims[0];
6129        if cin != cin_w {
6130            return Err(fuel_ir::Error::Msg(format!(
6131                "conv_transpose1d: x has {cin} in-channels but weight has {cin_w}",
6132            ))
6133            .bt());
6134        }
6135        if !cin.is_multiple_of(groups) {
6136            return Err(fuel_ir::Error::Msg(format!(
6137                "conv_transpose1d: Cin={cin} must be divisible by groups={groups}",
6138            ))
6139            .bt());
6140        }
6141        Ok(Self {
6142            inner: self.inner.conv_transpose1d(
6143                &weight.inner,
6144                stride,
6145                padding,
6146                output_padding,
6147                dilation,
6148                groups,
6149            ),
6150        })
6151    }
6152}
6153
6154// ============================================================================
6155// Phase A.1 — wrapper additions (eager-`Tensor` retirement program).
6156//
6157// Methods on `fuel_graph::NodeHandle` that weren't previously surfaced through
6158// `Tensor`. Pure delegation; no new graph ops. See
6159// `docs/session-prompts/eager-tensor-retirement-master-plan.md`.
6160// ============================================================================
6161
6162impl Tensor {
6163    // ---- shape ops: unsqueeze (Result + Dim) + Result-returning siblings ----
6164
6165    /// Append a size-1 dimension at position `dim`. Inverse of
6166    /// [`Self::squeeze`]. Accepts any [`Dim`] (`usize`, `D::Minus1`,
6167    /// etc.). Bad `dim` surfaces as a typed error at build time.
6168    pub fn unsqueeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6169        let shape = self.inner.shape();
6170        let dim = dim.to_index_plus_one(&shape, "unsqueeze")?;
6171        Ok(Self {
6172            inner: self.inner.try_unsqueeze(dim)?,
6173        })
6174    }
6175
6176    // ---- triangular masking (canonical attention masks) ----
6177
6178    /// Upper-triangular mask along the last two dims. `diagonal = 0`
6179    /// keeps the main diagonal and above; positive shifts higher.
6180    pub fn triu(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6181        Ok(Self {
6182            inner: self.inner.triu(diagonal)?,
6183        })
6184    }
6185
6186    /// Lower-triangular mask along the last two dims. `tril(0)` is the
6187    /// canonical causal-attention mask.
6188    pub fn tril(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6189        Ok(Self {
6190            inner: self.inner.tril(diagonal)?,
6191        })
6192    }
6193
6194    // ---- additional reductions / activations ----
6195
6196    /// `log(softmax(self))` along the last dim, fused into one op.
6197    pub fn log_softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
6198        Ok(Self {
6199            inner: self.inner.log_softmax_last_dim()?,
6200        })
6201    }
6202
6203    /// Numerically-stable softmax along an arbitrary axis. Accepts any
6204    /// [`Dim`]. Decomposes into `max_keepdim` / `broadcast_sub` / `exp` /
6205    /// `sum_keepdim` / `broadcast_div`, all of which already accept
6206    /// `D: Dim`, so this is a pure composition with no new graph op.
6207    ///
6208    /// When `dim` resolves to the last axis, prefer
6209    /// [`Self::softmax_last_dim`], which dispatches to the fused
6210    /// `SoftmaxLastDim` op (single kernel rather than five graph nodes).
6211    pub fn softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6212        let shape = self.inner.shape();
6213        // Resolve once to a concrete `usize` so we can pass it to each
6214        // composed call (the `Dim` trait doesn't require `Copy`, so we
6215        // can't reuse the generic `D` across multiple calls).
6216        let axis: usize = dim.to_index(&shape, "softmax")?;
6217        let m = self.max_keepdim(axis)?;
6218        let shifted = self.broadcast_sub(&m)?;
6219        let e = shifted.exp();
6220        let s = e.sum_keepdim(axis)?;
6221        e.broadcast_div(&s)
6222    }
6223
6224    /// Numerically-stable `log(softmax(self))` along an arbitrary axis.
6225    /// Accepts any [`Dim`]. Computes `x - max - log(sum(exp(x - max)))`
6226    /// — the standard log-sum-exp form, which avoids the explicit
6227    /// `softmax`-then-`log` underflow path. Pure composition over
6228    /// existing primitives.
6229    ///
6230    /// When `dim` resolves to the last axis, prefer
6231    /// [`Self::log_softmax_last_dim`], which dispatches to the fused
6232    /// `LogSoftmaxLastDim` op.
6233    pub fn log_softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6234        let shape = self.inner.shape();
6235        let axis: usize = dim.to_index(&shape, "log_softmax")?;
6236        let m = self.max_keepdim(axis)?;
6237        let shifted = self.broadcast_sub(&m)?;
6238        let lse = shifted.exp().sum_keepdim(axis)?.log();
6239        shifted.broadcast_sub(&lse)
6240    }
6241
6242    /// Argmin along `dim`, returning a U32 tensor with the reduced dim
6243    /// removed. Non-differentiable. Bad `dim` surfaces as a typed
6244    /// error at build time. Accepts any [`Dim`].
6245    pub fn argmin_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6246        let shape = self.inner.shape();
6247        let dim = dim.to_index(&shape, "argmin_dim")?;
6248        Ok(Self {
6249            inner: self.inner.argmin_dim(dim),
6250        })
6251    }
6252
6253    // ---- masking / scatter ----
6254
6255    /// Fill every position where `mask != 0` with `value`; pass `self`
6256    /// through everywhere `mask == 0`. `mask` must be U8 with the same
6257    /// shape as `self`; `value`'s dtype must match `self`.
6258    pub fn masked_fill(
6259        &self,
6260        mask: &Self,
6261        value: fuel_ir::Scalar,
6262    ) -> std::result::Result<Self, fuel_ir::Error> {
6263        Ok(Self {
6264            inner: self.inner.masked_fill(&mask.inner, value)?,
6265        })
6266    }
6267
6268    /// `self + scatter(indices, src, dim=dim)` — accumulate `src` rows
6269    /// at positions named by `indices` along `dim`. `indices` is rank-1
6270    /// U32 with length equal to `src.dims()[dim]`. Accepts any [`Dim`].
6271    /// Dim bounds / index dtype / shape / dtype-parity mismatches
6272    /// surface as typed errors at build time.
6273    pub fn index_add<D: Dim>(
6274        &self,
6275        dim: D,
6276        indices: &Self,
6277        src: &Self,
6278    ) -> std::result::Result<Self, fuel_ir::Error> {
6279        let shape = self.inner.shape();
6280        let dim = dim.to_index(&shape, "index_add")?;
6281        if indices.inner.dtype() != fuel_ir::DType::U32 {
6282            return Err(fuel_ir::Error::Msg(format!(
6283                "index_add: index must be U32, got {:?}",
6284                indices.inner.dtype(),
6285            ))
6286            .bt());
6287        }
6288        if self.inner.dtype() != src.inner.dtype() {
6289            return Err(fuel_ir::Error::Msg(format!(
6290                "index_add: base and src dtypes must match, got {:?} vs {:?}",
6291                self.inner.dtype(),
6292                src.inner.dtype(),
6293            ))
6294            .bt());
6295        }
6296        let base_dims = shape.dims();
6297        let src_shape = src.inner.shape();
6298        let src_dims = src_shape.dims();
6299        if base_dims.len() != src_dims.len() {
6300            return Err(fuel_ir::Error::Msg(format!(
6301                "index_add: base and src must have the same rank, got {} vs {}",
6302                base_dims.len(),
6303                src_dims.len(),
6304            ))
6305            .bt());
6306        }
6307        let idx_shape = indices.inner.shape();
6308        let idx_dims = idx_shape.dims();
6309        if idx_dims.len() != 1 {
6310            return Err(fuel_ir::Error::Msg(format!(
6311                "index_add: index must be rank 1, got {idx_dims:?}",
6312            ))
6313            .bt());
6314        }
6315        if src_dims[dim] != idx_dims[0] {
6316            return Err(fuel_ir::Error::Msg(format!(
6317                "index_add: src dim {dim} ({}) must match index length ({})",
6318                src_dims[dim], idx_dims[0],
6319            ))
6320            .bt());
6321        }
6322        Ok(Self {
6323            inner: self.inner.index_add(dim, &indices.inner, &src.inner),
6324        })
6325    }
6326
6327    /// Functional inverse of [`Self::gather`]. Accumulates `src` into
6328    /// `self` at positions given by `indices` (substituted at `dim`).
6329    /// Accepts any [`Dim`]. Dim bounds / index dtype / shape / dtype-
6330    /// parity mismatches surface as typed errors at build time.
6331    pub fn scatter_add<D: Dim>(
6332        &self,
6333        dim: D,
6334        indices: &Self,
6335        src: &Self,
6336    ) -> std::result::Result<Self, fuel_ir::Error> {
6337        let shape = self.inner.shape();
6338        let dim = dim.to_index(&shape, "scatter_add")?;
6339        if indices.inner.dtype() != fuel_ir::DType::U32 {
6340            return Err(fuel_ir::Error::Msg(format!(
6341                "scatter_add: index must be U32, got {:?}",
6342                indices.inner.dtype(),
6343            ))
6344            .bt());
6345        }
6346        if self.inner.dtype() != src.inner.dtype() {
6347            return Err(fuel_ir::Error::Msg(format!(
6348                "scatter_add: base and src dtypes must match, got {:?} vs {:?}",
6349                self.inner.dtype(),
6350                src.inner.dtype(),
6351            ))
6352            .bt());
6353        }
6354        let idx_shape = indices.inner.shape();
6355        let src_shape = src.inner.shape();
6356        if idx_shape.dims() != src_shape.dims() {
6357            return Err(fuel_ir::Error::Msg(format!(
6358                "scatter_add: index and src must have the same shape, got {:?} vs {:?}",
6359                idx_shape.dims(),
6360                src_shape.dims(),
6361            ))
6362            .bt());
6363        }
6364        Ok(Self {
6365            inner: self.inner.scatter_add(dim, &indices.inner, &src.inner),
6366        })
6367    }
6368
6369    // ---- in-place activations (Phase 4-5 infrastructure, now surfaced) ----
6370    //
6371    // These mutate `self`'s storage in place. Safe to call on
6372    // tape-tracked tensors after Phase 4's view-aware ordering pass and
6373    // Phase 5's auto-copy pass. See `project_inplace_ops_complete`
6374    // memory entry.
6375
6376    /// In-place `max(0, self)`. See [`Self::relu`] for the functional
6377    /// variant.
6378    pub fn relu_inplace(&self) -> Self {
6379        Self {
6380            inner: self.inner.relu_inplace(),
6381        }
6382    }
6383
6384    /// In-place `self * sigmoid(self)`. See [`Self::silu`] for the
6385    /// functional variant.
6386    pub fn silu_inplace(&self) -> Self {
6387        Self {
6388            inner: self.inner.silu_inplace(),
6389        }
6390    }
6391
6392    /// In-place tanh-approximation GELU. See [`Self::gelu_tanh`] for the
6393    /// functional variant.
6394    pub fn gelu_tanh_inplace(&self) -> Self {
6395        Self {
6396            inner: self.inner.gelu_tanh_inplace(),
6397        }
6398    }
6399
6400    /// In-place `tanh(self)`. See [`Self::tanh`] for the functional
6401    /// variant.
6402    pub fn tanh_inplace(&self) -> Self {
6403        Self {
6404            inner: self.inner.tanh_inplace(),
6405        }
6406    }
6407
6408    /// In-place `sigmoid(self)`. See [`Self::sigmoid`] for the
6409    /// functional variant.
6410    pub fn sigmoid_inplace(&self) -> Self {
6411        Self {
6412            inner: self.inner.sigmoid_inplace(),
6413        }
6414    }
6415
6416    /// In-place `self = mul · self + add`. Single fused-op equivalent
6417    /// of `self.mul_scalar(mul).add_scalar(add)` plus reassignment.
6418    pub fn affine_inplace(&self, mul: f64, add: f64) -> Self {
6419        Self {
6420            inner: self.inner.affine_inplace(mul, add),
6421        }
6422    }
6423
6424    // ---- additional const_*_like factories ----
6425
6426    /// Build a sibling F64 `Const` on the same graph as `self`.
6427    pub fn const_f64_like(
6428        &self,
6429        data: impl Into<Arc<[f64]>>,
6430        shape: impl Into<Shape>,
6431    ) -> std::result::Result<Self, fuel_ir::Error> {
6432        Ok(Self {
6433            inner: self.inner.const_f64_like(data, shape)?,
6434        })
6435    }
6436
6437    /// Build a sibling I64 `Const` on the same graph. Used by integer-
6438    /// target ops (e.g. cross-entropy with PyTorch-convention class
6439    /// indices).
6440    pub fn const_i64_like(
6441        &self,
6442        data: impl Into<Arc<[i64]>>,
6443        shape: impl Into<Shape>,
6444    ) -> std::result::Result<Self, fuel_ir::Error> {
6445        Ok(Self {
6446            inner: self.inner.const_i64_like(data, shape)?,
6447        })
6448    }
6449
6450    // ---- device residency control ----
6451
6452    /// Pin this tensor's realized storage to `device`. Consumes `self`
6453    /// because the placement is a graph-level annotation tied to the
6454    /// node id rather than a side-effecting operation.
6455    pub fn on_device(self, device: &Device) -> Self {
6456        Self {
6457            inner: self.inner.on_device(device.location()),
6458        }
6459    }
6460
6461    /// Append an `Op::Release` node — explicitly drop this tensor's
6462    /// device-resident storage once the ordering pass has scheduled
6463    /// every reader before it.
6464    pub fn release(&self) -> Self {
6465        Self {
6466            inner: self.inner.release(),
6467        }
6468    }
6469
6470    /// Move bytes to `device`, destroying the source. Use when the
6471    /// source is genuinely dead after the transfer.
6472    pub fn move_to_device(&self, device: &Device) -> Self {
6473        Self {
6474            inner: self.inner.move_to_device(device.location()),
6475        }
6476    }
6477
6478    /// Copy bytes to `device`, leaving the source resident. Use when
6479    /// other ops still need the source.
6480    pub fn copy_to_device(&self, device: &Device) -> Self {
6481        Self {
6482            inner: self.inner.copy_to_device(device.location()),
6483        }
6484    }
6485
6486    // ---- autograd ----
6487
6488    /// Run reverse-mode autograd from this tensor as the loss, returning
6489    /// a [`fuel_graph::GradMap`] keyed by every input tensor reached.
6490    /// The gradient nodes extend the same graph; realizing a gradient
6491    /// re-executes the forward dependencies.
6492    pub fn backward(&self) -> fuel_graph::GradMap {
6493        self.inner.backward()
6494    }
6495}
6496
6497// ============================================================================
6498// Phase A.2 — composite primitives expressible from existing ops.
6499//
6500// Each method here is implemented in terms of `Tensor`'s existing
6501// surface (reshape, permute, concat, unsqueeze, etc.). No new graph ops.
6502// ============================================================================
6503
6504impl Tensor {
6505    /// Transpose the last two dims as a Result-returning convenience —
6506    /// rank < 2 surfaces as an error rather than the panic the
6507    /// no-arg [`Self::transpose`] would produce. Alias for the eager
6508    /// `transpose_last_two`.
6509    pub fn transpose_last_two(&self) -> std::result::Result<Self, fuel_ir::Error> {
6510        self.transpose()
6511    }
6512
6513    /// Eager-API alias of [`Self::transpose_last_two`]. Matches PyTorch's
6514    /// `.t()` short form and the existing eager [`Tensor::t`] method.
6515    pub fn t(&self) -> std::result::Result<Self, fuel_ir::Error> {
6516        self.transpose()
6517    }
6518
6519    /// Two-argument transpose: swap dims `dim1` and `dim2`, leaving the
6520    /// rest in place. Implemented via [`fuel_graph::NodeHandle::try_permute`]; matches the
6521    /// eager `transpose(d1, d2)` two-arg form. Accepts any [`Dim`]
6522    /// (`usize`, `D::Minus1`, etc.).
6523    pub fn transpose_dims<D1: Dim, D2: Dim>(
6524        &self,
6525        dim1: D1,
6526        dim2: D2,
6527    ) -> std::result::Result<Self, fuel_ir::Error> {
6528        let shape = self.shape();
6529        let dim1 = dim1.to_index(&shape, "transpose_dims")?;
6530        let dim2 = dim2.to_index(&shape, "transpose_dims")?;
6531        if dim1 == dim2 {
6532            return Ok(self.clone());
6533        }
6534        let rank = shape.dims().len();
6535        let mut axes: Vec<usize> = (0..rank).collect();
6536        axes.swap(dim1, dim2);
6537        self.permute(axes.as_slice())
6538    }
6539
6540    /// Collapse dims `[start_dim, end_dim]` (inclusive) into a single
6541    /// dimension. Returns `Result` so out-of-bounds surfaces as a typed
6542    /// error rather than a panic. Accepts any [`Dim`] for either arg
6543    /// (`D::Minus1` for the last axis works).
6544    pub fn flatten<D1: Dim, D2: Dim>(
6545        &self,
6546        start_dim: D1,
6547        end_dim: D2,
6548    ) -> std::result::Result<Self, fuel_ir::Error> {
6549        let shape = self.shape();
6550        let rank = shape.dims().len();
6551        if rank == 0 {
6552            return Ok(self.clone());
6553        }
6554        let start_dim = start_dim.to_index(&shape, "flatten")?;
6555        let end_dim = end_dim.to_index(&shape, "flatten")?;
6556        if start_dim > end_dim {
6557            return Err(fuel_ir::Error::Msg(format!(
6558                "flatten: start_dim={start_dim} > end_dim={end_dim}",
6559            ))
6560            .bt());
6561        }
6562        let dims = shape.dims();
6563        let merged: usize = dims[start_dim..=end_dim].iter().product();
6564        let mut new_dims: Vec<usize> = Vec::with_capacity(rank - (end_dim - start_dim));
6565        new_dims.extend_from_slice(&dims[..start_dim]);
6566        new_dims.push(merged);
6567        new_dims.extend_from_slice(&dims[end_dim + 1..]);
6568        self.reshape(new_dims)
6569    }
6570
6571    /// Flatten dims `[0, end_dim]` (inclusive) into one.
6572    pub fn flatten_to<D: Dim>(&self, end_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6573        self.flatten(0_usize, end_dim)
6574    }
6575
6576    /// Flatten dims `[start_dim, rank-1]` into one.
6577    pub fn flatten_from<D: Dim>(&self, start_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6578        let rank = self.shape().dims().len();
6579        if rank == 0 {
6580            return Ok(self.clone());
6581        }
6582        self.flatten(start_dim, rank - 1)
6583    }
6584
6585    /// Flatten the tensor to rank-1 (single dim containing every element).
6586    pub fn flatten_all(&self) -> std::result::Result<Self, fuel_ir::Error> {
6587        let rank = self.shape().dims().len();
6588        if rank == 0 {
6589            return Ok(self.clone());
6590        }
6591        self.flatten(0, rank - 1)
6592    }
6593
6594    /// Stack tensors along a new dim at position `dim`. Each input is
6595    /// `unsqueeze`d at `dim` then concatenated. All inputs must have
6596    /// identical shape; `dim` may equal `rank` (append a new trailing
6597    /// dim). Accepts any [`Dim`].
6598    pub fn stack<D: Dim>(args: &[&Self], dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6599        if args.is_empty() {
6600            return Err(fuel_ir::Error::Msg("stack: requires at least one tensor".into()).bt());
6601        }
6602        let reference_shape = args[0].shape();
6603        let reference_dims = reference_shape.dims().to_vec();
6604        let dim = dim.to_index_plus_one(&reference_shape, "stack")?;
6605        for (idx, t) in args.iter().enumerate().skip(1) {
6606            if t.shape().dims() != reference_dims.as_slice() {
6607                return Err(fuel_ir::Error::Msg(format!(
6608                    "stack: tensor {idx} shape {:?} != reference shape {:?}",
6609                    t.shape().dims(),
6610                    reference_dims,
6611                ))
6612                .bt());
6613            }
6614        }
6615        // unsqueeze every input at the new dim, then concat.
6616        let mut iter = args.iter();
6617        let first = iter.next().unwrap().unsqueeze(dim)?;
6618        let mut acc = first;
6619        for t in iter {
6620            let u = t.unsqueeze(dim)?;
6621            acc = acc.concat(&u, dim)?;
6622        }
6623        Ok(acc)
6624    }
6625
6626    // ---- keepdim reductions ----
6627    //
6628    // Each keepdim variant is the squeezed reduction post-composed with
6629    // `unsqueeze` at the same dim. The graph optimizer can fuse these
6630    // back into a single op when it's profitable; until then, the cost
6631    // is one extra view-only node.
6632
6633    /// Sum along `dim`, keeping the reduced dim as size 1. Accepts any
6634    /// [`Dim`]. Returns Result because of the cascade from [`Self::unsqueeze`].
6635    pub fn sum_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6636        let shape = self.shape();
6637        let dim = dim.to_index(&shape, "sum_keepdim")?;
6638        self.sum_dim(dim).unwrap().unsqueeze(dim)
6639    }
6640
6641    /// Mean along `dim`, keeping the reduced dim as size 1.
6642    pub fn mean_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6643        let shape = self.shape();
6644        let dim = dim.to_index(&shape, "mean_keepdim")?;
6645        self.mean_dim(dim).unwrap().unsqueeze(dim)
6646    }
6647
6648    /// Max along `dim`, keeping the reduced dim as size 1.
6649    pub fn max_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6650        let shape = self.shape();
6651        let dim = dim.to_index(&shape, "max_keepdim")?;
6652        self.max_dim(dim).unwrap().unsqueeze(dim)
6653    }
6654
6655    /// Min along `dim`, keeping the reduced dim as size 1.
6656    pub fn min_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6657        let shape = self.shape();
6658        let dim = dim.to_index(&shape, "min_keepdim")?;
6659        // sum_dim/mean_dim/max_dim/min_dim return Self today (A.8b.9 will
6660        // flip them to Result); chain through `.unsqueeze(dim)?` which now
6661        // owns the build-time dim validation.
6662        self.min_dim(dim).unwrap().unsqueeze(dim)
6663    }
6664
6665    /// Variance along `dim`, keeping the reduced dim as size 1. Divides
6666    /// squared deviations by `n - correction` (numpy/PyTorch-2.x
6667    /// `correction` convention: `0.0` is the **population** variance
6668    /// — KISS-Ops §6.13's default, and numpy's own default — `1.0` is
6669    /// Bessel's (sample/unbiased) correction, matching PyTorch's *older*
6670    /// default and the eager [`Tensor::var_keepdim`]'s prior behavior.
6671    ///
6672    /// **Not a default-argument convenience**: KISS-Ops §6.13 requires
6673    /// Bessel's correction to be an EXPLICIT attribute, not an implicit
6674    /// torch-style default silently baked into the divisor — this
6675    /// parameter exists so a caller cannot get Bessel's correction by
6676    /// omission. The divisor is clamped at zero, `max(0, n - correction)`
6677    /// (the torch rule), so the result is never negative and never a panic:
6678    /// `correction == n` is `0/0 = NaN`; `correction > n` is `x/0 = inf`
6679    /// (`NaN` if the sum of squared deviations is 0, e.g. a single element).
6680    /// Before 2026-11-25 only `correction == n` was non-finite and
6681    /// `correction > n` returned a finite, possibly NEGATIVE variance.
6682    pub fn var_keepdim<D: Dim>(
6683        &self,
6684        dim: D,
6685        correction: f64,
6686    ) -> std::result::Result<Self, fuel_ir::Error> {
6687        // A NaN correction is a caller error: `f64::max` returns the non-NaN operand, so it would otherwise be
6688        // clamped to a zero divisor and silently turn a NaN result into `inf` (PIP #715 L2).
6689        if correction.is_nan() {
6690            return Err(fuel_ir::Error::Msg(
6691                "var_keepdim: correction must not be NaN".to_string(),
6692            ));
6693        }
6694        let shape = self.shape();
6695        let dim = dim.to_index(&shape, "var_keepdim")?;
6696        let dims = shape.dims();
6697        let n = dims[dim];
6698        let mean = self.mean_keepdim(dim)?;
6699        let deviation = self.broadcast_sub(&mean).unwrap();
6700        let squares = deviation.sqr();
6701        // sum_keepdim then divide by (n - correction); leaves the reduced dim as 1.
6702        let summed = squares.sum_keepdim(dim)?;
6703        let divisor = (n as f64 - correction).max(0.0);
6704        Ok(summed.mul_scalar(1.0 / divisor))
6705    }
6706
6707    /// Variance along `dim`, squeezing the reduced dim. See
6708    /// [`Self::var_keepdim`] for the `correction` parameter's meaning.
6709    pub fn var<D: Dim>(
6710        &self,
6711        dim: D,
6712        correction: f64,
6713    ) -> std::result::Result<Self, fuel_ir::Error> {
6714        let shape = self.shape();
6715        let dim = dim.to_index(&shape, "var")?;
6716        self.var_keepdim(dim, correction)?.squeeze(dim)
6717    }
6718
6719    // ---- composite scalar / binary ops (Phase A.4) ----
6720
6721    /// `y = mul * self + add` element-wise. Two-op composite of
6722    /// [`Self::mul_scalar`] then [`Self::add_scalar`]; a fused `Op::Affine`
6723    /// can collapse this into a single op later (see the in-place
6724    /// counterpart [`Self::affine_inplace`]).
6725    pub fn affine(&self, mul: f64, add: f64) -> Self {
6726        self.mul_scalar(mul).add_scalar(add)
6727    }
6728
6729    /// `y = scale * self + shift`. Alias of [`Self::affine`] with
6730    /// descriptive parameter names; matches eager's
6731    /// `Tensor::scale_and_shift`.
6732    pub fn scale_and_shift(&self, scale: f64, shift: f64) -> Self {
6733        self.affine(scale, shift)
6734    }
6735
6736    /// Exponential Linear Unit: `self` where `self > 0`,
6737    /// `alpha * (exp(self) - 1)` otherwise. Composite of `where_cond`,
6738    /// `gt`, `exp`, `affine`.
6739    pub fn elu(&self, alpha: f64) -> Self {
6740        // Negative-branch value: alpha * (exp(self) - 1) = alpha * exp(self) - alpha
6741        let neg_branch = self.exp().affine(alpha, -alpha);
6742        // Mask: self > 0. Build a zero on the same graph.
6743        // GAP-003 carve-out. THE PROOF IS LOCAL AND ON THIS LINE: the buffer is
6744        // `vec![0.0; self.elem_count()]` and the shape is `self.shape()`, whose
6745        // elem_count IS that number. Both from `self`; no caller supplies either.
6746        let zero = self
6747            .const_f32_like(vec![0.0; self.elem_count()], self.shape())
6748            .expect("elu: vec![_; self.elem_count()] against self.shape() -- same source");
6749        let mask = self.gt(&zero).unwrap();
6750        mask.where_cond(self, &neg_branch).unwrap()
6751    }
6752
6753    /// Inner product of two rank-1 tensors. Composite of `mul` +
6754    /// `sum_all`; matches eager's [`Tensor::dot`].
6755    pub fn dot(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6756        let a = self.shape().dims().to_vec();
6757        let b = rhs.shape().dims().to_vec();
6758        if a.len() != 1 || b.len() != 1 {
6759            return Err(fuel_ir::Error::Msg(format!(
6760                "dot: requires rank-1 inputs, got lhs={a:?} rhs={b:?}",
6761            ))
6762            .bt());
6763        }
6764        if a[0] != b[0] {
6765            return Err(fuel_ir::Error::Msg(format!(
6766                "dot: length mismatch lhs={} rhs={}",
6767                a[0], b[0],
6768            ))
6769            .bt());
6770        }
6771        Ok(self.mul(rhs).unwrap().sum_all())
6772    }
6773
6774    /// Matrix × vector: `[m, n] · [n] -> [m]`. No broadcasting. Composite
6775    /// of `unsqueeze` + `matmul` + `squeeze`. Matches eager's
6776    /// [`Tensor::mv`].
6777    pub fn mv(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6778        let a = self.shape().dims().to_vec();
6779        let b = rhs.shape().dims().to_vec();
6780        if a.len() != 2 || b.len() != 1 || a[1] != b[0] {
6781            return Err(fuel_ir::Error::Msg(format!(
6782                "mv: shape mismatch lhs={a:?} rhs={b:?} (need [m,n] · [n])",
6783            ))
6784            .bt());
6785        }
6786        // unsqueeze rhs to [n,1], matmul -> [m,1], squeeze trailing dim.
6787        let rhs_col = rhs.unsqueeze(1_usize)?;
6788        let prod = self.matmul(&rhs_col).unwrap();
6789        prod.squeeze(1_usize)
6790    }
6791
6792    /// Alias of [`Self::mv`] with a more descriptive name. Matches
6793    /// eager's [`Tensor::matvec`].
6794    pub fn matvec(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6795        self.mv(rhs)
6796    }
6797
6798    /// Broadcast-aware matmul. Lazy's [`Self::matmul`] already accepts
6799    /// broadcast-compatible operands; this method is exposed for
6800    /// signature compatibility with eager's `Tensor::broadcast_matmul`.
6801    pub fn broadcast_matmul(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6802        self.matmul(rhs)
6803    }
6804
6805    // ---- Phase A.5 factory family ----
6806    //
6807    // Instance methods derive shape + dtype from `self` and place the new
6808    // tensor on the same graph via `const_*_like`. Static methods build
6809    // a fresh graph anchored on a host-allocated buffer.
6810
6811    /// New tensor with the same shape, dtype, and graph as `self`, filled
6812    /// with ones. Returns Err for unsupported dtypes (anything outside
6813    /// F32/F64/BF16/F16/U32/I64) — matches eager `Tensor::ones_like` parity.
6814    pub fn ones_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6815        let n = self.elem_count();
6816        let shape = self.shape();
6817        match self.dtype() {
6818            DType::F32 => self.const_f32_like(vec![1.0_f32; n], shape),
6819            DType::F64 => self.const_f64_like(vec![1.0_f64; n], shape),
6820            DType::BF16 => self.const_bf16_like(vec![half::bf16::ONE; n], shape),
6821            DType::F16 => self.const_f16_like(vec![half::f16::ONE; n], shape),
6822            DType::U32 => self.const_u32_like(vec![1_u32; n], shape),
6823            DType::I64 => self.const_i64_like(vec![1_i64; n], shape),
6824            other => {
6825                Err(fuel_ir::Error::Msg(format!("ones_like: unsupported dtype {other:?}",)).bt())
6826            }
6827        }
6828    }
6829
6830    /// New tensor with the same shape, dtype, and graph as `self`, filled
6831    /// with zeros. Returns Err for unsupported dtypes (anything outside
6832    /// F32/F64/BF16/F16/U32/I64) — matches eager `Tensor::zeros_like` parity.
6833    pub fn zeros_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6834        let n = self.elem_count();
6835        let shape = self.shape();
6836        match self.dtype() {
6837            DType::F32 => self.const_f32_like(vec![0.0_f32; n], shape),
6838            DType::F64 => self.const_f64_like(vec![0.0_f64; n], shape),
6839            DType::BF16 => self.const_bf16_like(vec![half::bf16::ZERO; n], shape),
6840            DType::F16 => self.const_f16_like(vec![half::f16::ZERO; n], shape),
6841            DType::U32 => self.const_u32_like(vec![0_u32; n], shape),
6842            DType::I64 => self.const_i64_like(vec![0_i64; n], shape),
6843            other => {
6844                Err(fuel_ir::Error::Msg(format!("zeros_like: unsupported dtype {other:?}",)).bt())
6845            }
6846        }
6847    }
6848
6849    /// New tensor with `shape`/`dtype`/`device`, every element set to `1`.
6850    /// Static factory equivalent of eager's `Tensor::ones`. Returns Err for
6851    /// dtypes outside F32/F64/BF16/F16/U32.
6852    pub fn ones(
6853        shape: impl Into<Shape>,
6854        dtype: DType,
6855        device: &Device,
6856    ) -> std::result::Result<Self, fuel_ir::Error> {
6857        let shape = shape.into();
6858        let n = shape.elem_count();
6859        match dtype {
6860            DType::F32 => Self::from_f32(vec![1.0_f32; n], shape, device),
6861            DType::F64 => Self::from_f64(vec![1.0_f64; n], shape, device),
6862            DType::BF16 => Self::from_bf16(vec![half::bf16::ONE; n], shape, device),
6863            DType::F16 => Self::from_f16(vec![half::f16::ONE; n], shape, device),
6864            DType::U32 => Self::from_u32(vec![1_u32; n], shape, device),
6865            other => Err(fuel_ir::Error::Msg(format!("ones: unsupported dtype {other:?}",)).bt()),
6866        }
6867    }
6868
6869    /// New tensor with `shape`/`dtype`/`device`, every element set to `0`.
6870    /// Static factory equivalent of eager's `Tensor::zeros`. Returns Err for
6871    /// dtypes outside F32/F64/BF16/F16/U32.
6872    ///
6873    /// **Mints a NEW graph** — it delegates to the `from_*` constructors, so
6874    /// the tensor it returns cannot be combined with one built elsewhere. To
6875    /// add a zero tensor to an existing graph, use
6876    /// [`zeros_like`](Self::zeros_like) or a `const_*_like` builder. See
6877    /// [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
6878    pub fn zeros(
6879        shape: impl Into<Shape>,
6880        dtype: DType,
6881        device: &Device,
6882    ) -> std::result::Result<Self, fuel_ir::Error> {
6883        let shape = shape.into();
6884        let n = shape.elem_count();
6885        match dtype {
6886            DType::F32 => Self::from_f32(vec![0.0_f32; n], shape, device),
6887            DType::F64 => Self::from_f64(vec![0.0_f64; n], shape, device),
6888            DType::BF16 => Self::from_bf16(vec![half::bf16::ZERO; n], shape, device),
6889            DType::F16 => Self::from_f16(vec![half::f16::ZERO; n], shape, device),
6890            DType::U32 => Self::from_u32(vec![0_u32; n], shape, device),
6891            other => Err(fuel_ir::Error::Msg(format!("zeros: unsupported dtype {other:?}",)).bt()),
6892        }
6893    }
6894
6895    /// New tensor of `shape`/`device` filled with `value`. The scalar's
6896    /// dtype determines the tensor's dtype. Returns Err for scalar dtypes
6897    /// outside F32/F64/BF16/F16/U32.
6898    ///
6899    /// **Mints a NEW graph** — it delegates to the `from_*` constructors, so
6900    /// the tensor it returns cannot be combined with one built elsewhere. To
6901    /// add a filled tensor to an existing graph, use a `const_*_like` builder.
6902    /// See [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
6903    pub fn full(
6904        shape: impl Into<Shape>,
6905        value: fuel_ir::Scalar,
6906        device: &Device,
6907    ) -> std::result::Result<Self, fuel_ir::Error> {
6908        let shape = shape.into();
6909        let n = shape.elem_count();
6910        match value {
6911            fuel_ir::Scalar::F32(v) => Self::from_f32(vec![v; n], shape, device),
6912            fuel_ir::Scalar::F64(v) => Self::from_f64(vec![v; n], shape, device),
6913            fuel_ir::Scalar::BF16(v) => Self::from_bf16(vec![v; n], shape, device),
6914            fuel_ir::Scalar::F16(v) => Self::from_f16(vec![v; n], shape, device),
6915            fuel_ir::Scalar::U32(v) => Self::from_u32(vec![v; n], shape, device),
6916            other => Err(fuel_ir::Error::Msg(format!(
6917                "full: unsupported scalar dtype {:?}",
6918                other.dtype(),
6919            ))
6920            .bt()),
6921        }
6922    }
6923
6924    /// Identity matrix `[n, n]` with the given dtype on the given device.
6925    /// Built host-side as a flat Vec; no graph-layer arange dependency.
6926    pub fn eye(n: usize, dtype: DType, device: &Device) -> Self {
6927        let mut data = vec![0.0_f32; n * n];
6928        for i in 0..n {
6929            data[i * n + i] = 1.0;
6930        }
6931        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
6932        // saying it CAN would be a false claim in the signature -- `eye` would
6933        // return a `Result` that is never `Err`, and every caller would write a
6934        // `?` for an error that does not exist.
6935        //
6936        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
6937        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
6938        // in this function; no caller supplies either, so they cannot disagree.
6939        let base = Self::from_f32(data, vec![n, n], device).expect(
6940            "eye: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n             both computed from `n` in this function -- lengths cannot disagree",
6941        );
6942        if dtype == DType::F32 {
6943            base
6944        } else {
6945            base.to_dtype(dtype).unwrap()
6946        }
6947    }
6948
6949    /// Split a `(B, N, num_heads * head_dim)` projection into the
6950    /// multi-head attention layout `(B, num_heads, N, head_dim)`.
6951    /// Equivalent to `reshape(B, N, num_heads, head_dim).permute([0, 2, 1, 3])`
6952    /// — promoted to a method to retire the per-port reimplementations
6953    /// of this same composite.
6954    pub fn split_heads(
6955        &self,
6956        num_heads: usize,
6957        head_dim: usize,
6958    ) -> std::result::Result<Self, fuel_ir::Error> {
6959        let dims = self.inner.shape().dims().to_vec();
6960        debug_assert_eq!(
6961            dims.len(),
6962            3,
6963            "split_heads: input must be rank 3 (B, N, embed), got {dims:?}"
6964        );
6965        debug_assert_eq!(
6966            dims[2],
6967            num_heads * head_dim,
6968            "split_heads: trailing dim ({}) != num_heads * head_dim ({} * {} = {})",
6969            dims[2],
6970            num_heads,
6971            head_dim,
6972            num_heads * head_dim
6973        );
6974        let b = dims[0];
6975        let n = dims[1];
6976        self.reshape(Shape::from_dims(&[b, n, num_heads, head_dim]))?
6977            .permute([0, 2, 1, 3_usize])
6978    }
6979
6980    /// Merge a `(B, num_heads, N, head_dim)` attention result back
6981    /// into the projection layout `(B, N, num_heads * head_dim)`.
6982    /// Inverse of [`Self::split_heads`].
6983    pub fn merge_heads(&self) -> std::result::Result<Self, fuel_ir::Error> {
6984        let dims = self.inner.shape().dims().to_vec();
6985        debug_assert_eq!(
6986            dims.len(),
6987            4,
6988            "merge_heads: input must be rank 4 (B, heads, N, head_dim), got {dims:?}"
6989        );
6990        let b = dims[0];
6991        let num_heads = dims[1];
6992        let n = dims[2];
6993        let head_dim = dims[3];
6994        self.permute([0, 2, 1, 3_usize])?
6995            .reshape(Shape::from_dims(&[b, n, num_heads * head_dim]))
6996    }
6997
6998    /// Add a length-`bias.len()` bias vector to the trailing dim
6999    /// of `self`, broadcasting across all leading dims. The bias
7000    /// is materialized fresh on `self`'s graph from the supplied
7001    /// `Arc<[f32]>`.
7002    ///
7003    /// Common pattern after `WeightStorage::apply_linear` when the
7004    /// linear has a bias term but the activation tensor is on a
7005    /// different anchor than where the bias was originally
7006    /// allocated. Several lazy ports inlined this same 3-line
7007    /// helper as `bias_add` — promoted here to a method.
7008    pub fn add_trailing_bias(
7009        &self,
7010        bias: std::sync::Arc<[f32]>,
7011    ) -> std::result::Result<Self, fuel_ir::Error> {
7012        let n = bias.len();
7013        // Build the bias const in `self`'s dtype rather than hardcoding
7014        // f32: under BF16-throughout decode (Phase D increment A) the
7015        // activation stream is BF16 and `broadcast_add` asserts dtype
7016        // equality, so an f32 bias would panic. No-op for f32 activations
7017        // (every other caller today).
7018        let bias_t = self.const_like_dtype(&bias, Shape::from_dims(&[n]), self.dtype())?;
7019        self.broadcast_add(&bias_t)
7020    }
7021
7022    /// Embed `tokens` against an `[vocab_size, hidden]` embedding
7023    /// table held as `Arc<[f32]>`. Returns `(1, seq, hidden)`
7024    /// rank-3 hidden states ready to feed into a decoder backbone.
7025    ///
7026    /// Bootstraps a fresh graph anchored on a new const-f32 node.
7027    /// For composition with an already-built tensor (e.g.,
7028    /// multimodal models that need text embeddings on the audio
7029    /// graph), use [`Self::embed_tokens_anchored`] instead.
7030    ///
7031    /// Retires the 7-line `from_f32 + const_u32_like + index_select
7032    /// + reshape` ceremony every LLM port carried.
7033    pub fn embed_tokens(
7034        embed_table: std::sync::Arc<[f32]>,
7035        vocab_size: usize,
7036        hidden: usize,
7037        tokens: &[u32],
7038        device: &crate::Device,
7039    ) -> std::result::Result<Self, fuel_ir::Error> {
7040        let seq = tokens.len();
7041        if seq == 0 {
7042            return Err(fuel_ir::Error::Msg("embed_tokens: tokens must be non-empty".into()).bt());
7043        }
7044        let embed = Self::from_f32(embed_table, Shape::from_dims(&[vocab_size, hidden]), device)?;
7045        let token_ids = embed.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7046        embed
7047            .index_select(0_usize, &token_ids)?
7048            .reshape(Shape::from_dims(&[1, seq, hidden]))
7049    }
7050
7051    /// Variant of [`Self::embed_tokens`] that anchors the embedding
7052    /// table and token-id constants on the receiver's graph, so the
7053    /// resulting embeddings can compose with `self` and other
7054    /// tensors already on that graph. Used by multimodal models
7055    /// (vision + text, audio + text) where the text embeddings must
7056    /// live on the modality encoder's graph for cross-substitution
7057    /// to work.
7058    pub fn embed_tokens_anchored(
7059        &self,
7060        embed_table: std::sync::Arc<[f32]>,
7061        vocab_size: usize,
7062        hidden: usize,
7063        tokens: &[u32],
7064    ) -> std::result::Result<Self, fuel_ir::Error> {
7065        let seq = tokens.len();
7066        if seq == 0 {
7067            return Err(fuel_ir::Error::Msg(
7068                "embed_tokens_anchored: tokens must be non-empty".into(),
7069            )
7070            .bt());
7071        }
7072        let embed = self.const_f32_like(embed_table, Shape::from_dims(&[vocab_size, hidden]))?;
7073        let token_ids = self.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7074        embed
7075            .index_select(0_usize, &token_ids)?
7076            .reshape(Shape::from_dims(&[1, seq, hidden]))
7077    }
7078
7079    /// Build the standard (non-interleaved) RoPE cos/sin tables for
7080    /// `seq` positions starting at `start_pos`, anchored on the
7081    /// receiver's graph. Returns `(cos, sin)`, each with shape
7082    /// `[seq, head_dim]`.
7083    ///
7084    /// Delegates the actual `(theta, position) → (cos, sin)` host
7085    /// computation to [`fuel_graph::build_rope_tables`] (the canonical
7086    /// reference); only the const-tensor materialization is folded
7087    /// into one method to retire the per-port 4-line ceremony every
7088    /// LLM port did before calling `rope_with_tables`.
7089    pub fn rope_tables_const(
7090        &self,
7091        theta: f64,
7092        start_pos: usize,
7093        seq: usize,
7094        head_dim: usize,
7095    ) -> (Self, Self) {
7096        let (cos_data, sin_data) = fuel_graph::build_rope_tables(theta, start_pos, seq, head_dim);
7097        let rope_shape = Shape::from_dims(&[seq, head_dim]);
7098        // ⚠️ GAP-003 category 2: the proof EXISTS but is NOT LOCAL --
7099        // `build_rope_tables` owns the length and its `-> (Vec<f32>, Vec<f32>)`
7100        // signature does not carry it. The message names WHERE the guarantee
7101        // lives rather than claiming one. `-> (Self, Self)` has no error channel;
7102        // giving it one is a signature change, a different obligation. See #157.
7103        let rope_cos = self
7104            .const_f32_like(cos_data, rope_shape.clone())
7105            .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7106        let rope_sin = self
7107            .const_f32_like(sin_data, rope_shape)
7108            .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7109        (rope_cos, rope_sin)
7110    }
7111
7112    /// Constant-position RoPE cos/sin tables `[rows, head_dim]` where EVERY row
7113    /// is the *same* θ·`delta` rotation — the rung-2 delta-rotation tables. A
7114    /// cached prefix's keys, already rotated for their original positions, are
7115    /// shifted to `+delta` by applying this uniform rotation (RoPE composes
7116    /// additively per pair: `R(delta)·R(p) = R(p+delta)`).
7117    ///
7118    /// This is the position-`delta` row repeated `rows` times — NOT
7119    /// `rope_tables_const(theta, delta, rows, head_dim)`, which would give the
7120    /// *incrementing* progression `delta, delta+1, …` (the standard RoPE sweep).
7121    /// Routed through the canonical `fuel_graph::build_rope_tables` so it inherits
7122    /// the model's inv-freq/scaling exactly.
7123    pub fn rope_delta_tables_const(
7124        &self,
7125        theta: f64,
7126        delta: usize,
7127        rows: usize,
7128        head_dim: usize,
7129    ) -> (Self, Self) {
7130        let (c1, s1) = fuel_graph::build_rope_tables(theta, delta, 1, head_dim);
7131        let mut cos = Vec::with_capacity(rows * head_dim);
7132        let mut sin = Vec::with_capacity(rows * head_dim);
7133        for _ in 0..rows {
7134            cos.extend_from_slice(&c1);
7135            sin.extend_from_slice(&s1);
7136        }
7137        let shape = Shape::from_dims(&[rows, head_dim]);
7138        // ⚠️ GAP-003, HALF LOCAL. LOCAL: the loop appends `c1` exactly `rows`
7139        // times against a `[rows, head_dim]` shape. NOT LOCAL: that `c1` has
7140        // `head_dim` elements comes from `build_rope_tables`. Stated as both.
7141        (
7142            self.const_f32_like(cos, shape.clone()).expect(
7143                "rope tables: rows appends of c1 (local); c1 has head_dim elements (not local)",
7144            ),
7145            self.const_f32_like(sin, shape).expect(
7146                "rope tables: rows appends of s1 (local); s1 has head_dim elements (not local)",
7147            ),
7148        )
7149    }
7150
7151    /// Uniformly delta-rotate one cached (post-RoPE) K block by θ·`delta`,
7152    /// returning the shifted block in the SAME pool layout. Reuses the model's
7153    /// exact `rope_with_tables_decomposed` (rotate-half) rather than a hand-rolled
7154    /// rotation, so it inherits the model's RoPE convention + scaling and stays
7155    /// byte-exact with a direct rope-at-shifted-position. A single uniform
7156    /// rotation is correct for the whole block even though it holds `block_size`
7157    /// distinct original positions — the delta is the same for every position.
7158    ///
7159    /// `k_block` is the pool block layout, row-major `[block_size, n_kv_heads,
7160    /// head_dim]` (positions-major, as `DeviceKvPool::read_block` returns). RoPE
7161    /// wants `(position, dim)` as the last two axes, so heads are brought forward
7162    /// to the `project_qkv_roped` layout `[1, n_kv_heads, block_size, head_dim]`,
7163    /// rotated, and returned to `[block_size, n_kv_heads, head_dim]`. The rung-2
7164    /// numeric core, realized on `dev`.
7165    pub fn rope_delta_rotate_block_f32(
7166        dev: &crate::Device,
7167        k_block: &[f32],
7168        theta: f64,
7169        delta: usize,
7170        block_size: usize,
7171        n_kv_heads: usize,
7172        head_dim: usize,
7173    ) -> Vec<f32> {
7174        let pool_shape = Shape::from_dims(&[block_size, n_kv_heads, head_dim]);
7175        // ⚠️ GAP-003: NOT a carve-out and NOT a propagation, and the reason is
7176        // this function's SIGNATURE rather than anything about the operands.
7177        // `k_block` and the pool dims are BOTH caller-supplied, so there is no
7178        // local proof and the message below deliberately does not claim one.
7179        // `-> Vec<f32>` has no error channel, and the two `.expect`s already on
7180        // this same expression (permute, reshape) are the same pre-existing
7181        // condition -- converting one of three would be less honest, not more.
7182        //
7183        // The fix is this function returning `Result`, which is a DIFFERENT
7184        // obligation from the constructor-family ruling and is not in its scope.
7185        let k = Tensor::from_f32(k_block.to_vec(), pool_shape, dev).expect(
7186            "rope_delta_rotate_block_f32: k_block length must equal              block_size*n_kv_heads*head_dim -- both caller-supplied, so this              function cannot prove it; the -> Vec<f32> signature has no error              channel (see the sibling permute/reshape expects)",
7187        );
7188        let k4 = k
7189            .permute([1, 0, 2])
7190            .expect("rope_delta_rotate_block_f32: permute [bs,Hkv,D]->[Hkv,bs,D]")
7191            .reshape(Shape::from_dims(&[1, n_kv_heads, block_size, head_dim]))
7192            .expect("rope_delta_rotate_block_f32: reshape to [1,Hkv,bs,D]");
7193        let (cos, sin) = k4.rope_delta_tables_const(theta, delta, block_size, head_dim);
7194        k4.rope_with_tables_decomposed(&cos, &sin)
7195            .expect("rope_delta_rotate_block_f32: rope_with_tables_decomposed")
7196            .reshape(Shape::from_dims(&[n_kv_heads, block_size, head_dim]))
7197            .expect("rope_delta_rotate_block_f32: reshape back to [Hkv,bs,D]")
7198            .permute([1, 0, 2])
7199            .expect("rope_delta_rotate_block_f32: permute [Hkv,bs,D]->[bs,Hkv,D]")
7200            .realize_f32()
7201    }
7202
7203    /// `[B, 1, 1, head_dim]` RoPE cos/sin tables, row `b` at absolute position
7204    /// `positions[b]` — the per-row generalization of [`Self::rope_tables_const`]
7205    /// (which carries one shared position). Built as a **single** const from `B`
7206    /// calls to `fuel_graph::build_rope_tables` (the canonical `(theta, position)
7207    /// → (cos, sin)` math), concatenated host-side — no `Op::Concat` chain. At
7208    /// `B == 1` the emitted data is bit-identical to `rope_tables_const`'s
7209    /// `[1, head_dim]` const (same builder call), so
7210    /// [`Self::rope_batched`] reduces to the single-position decomposed RoPE.
7211    ///
7212    /// This is the mechanism that lets a decode batch carry sessions at
7213    /// *different* positions (continuous batching) rather than requiring
7214    /// equal-length rows. `anchor` (`self`) supplies the graph.
7215    pub fn rope_tables_const_batched(
7216        &self,
7217        theta: f64,
7218        positions: &[usize],
7219        head_dim: usize,
7220    ) -> (Self, Self) {
7221        let b = positions.len();
7222        let mut cos_data = Vec::with_capacity(b * head_dim);
7223        let mut sin_data = Vec::with_capacity(b * head_dim);
7224        for &pos in positions {
7225            let (c, s) = fuel_graph::build_rope_tables(theta, pos, 1, head_dim);
7226            cos_data.extend_from_slice(&c);
7227            sin_data.extend_from_slice(&s);
7228        }
7229        let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7230        // ⚠️ GAP-003, and the proof is HALF local -- worth stating as such rather
7231        // than rounding to either category. LOCAL: `b` IS `positions.len()` (six
7232        // lines up) and the loop appends once per position, so the buffer has
7233        // `positions.len() * head_dim` elements against a `[b, 1, 1, head_dim]`
7234        // shape. NOT LOCAL: that each `build_rope_tables(_, _, 1, head_dim)` call
7235        // yields exactly `head_dim` elements lives in that function.
7236        let rope_cos = self
7237            .const_f32_like(cos_data, shape.clone())
7238            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7239        let rope_sin = self
7240            .const_f32_like(sin_data, shape)
7241            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7242        (rope_cos, rope_sin)
7243    }
7244
7245    /// [`Self::rope_tables_const`] with caller-supplied inverse frequencies
7246    /// (`inv_freq.len() == head_dim / 2`) in place of the ones derived from
7247    /// `theta` -- the scaled-RoPE (llama3 / yarn / linear) entry. Delegates the
7248    /// host math to [`fuel_graph::build_rope_tables_with_inv_freq`].
7249    pub fn rope_tables_const_with_inv_freq(
7250        &self,
7251        inv_freq: &[f64],
7252        start_pos: usize,
7253        seq: usize,
7254        head_dim: usize,
7255    ) -> (Self, Self) {
7256        let (cos_data, sin_data) =
7257            fuel_graph::build_rope_tables_with_inv_freq(inv_freq, start_pos, seq, head_dim);
7258        let rope_shape = Shape::from_dims(&[seq, head_dim]);
7259        // GAP-003: same non-local proof as `rope_tables_const` -- the length
7260        // lives in `build_rope_tables_with_inv_freq`, which has no error channel.
7261        let rope_cos = self.const_f32_like(cos_data, rope_shape.clone()).expect(
7262            "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7263        );
7264        let rope_sin = self.const_f32_like(sin_data, rope_shape).expect(
7265            "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7266        );
7267        (rope_cos, rope_sin)
7268    }
7269
7270    /// [`Self::rope_tables_const_batched`] with caller-supplied inverse
7271    /// frequencies (`inv_freq.len() == head_dim / 2`).
7272    pub fn rope_tables_const_batched_with_inv_freq(
7273        &self,
7274        inv_freq: &[f64],
7275        positions: &[usize],
7276        head_dim: usize,
7277    ) -> (Self, Self) {
7278        let b = positions.len();
7279        let mut cos_data = Vec::with_capacity(b * head_dim);
7280        let mut sin_data = Vec::with_capacity(b * head_dim);
7281        for &pos in positions {
7282            let (c, s) = fuel_graph::build_rope_tables_with_inv_freq(inv_freq, pos, 1, head_dim);
7283            cos_data.extend_from_slice(&c);
7284            sin_data.extend_from_slice(&s);
7285        }
7286        let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7287        // GAP-003: `b` IS `positions.len()` (local); the per-position length
7288        // lives in `build_rope_tables_with_inv_freq` (not local).
7289        let rope_cos = self
7290            .const_f32_like(cos_data, shape.clone())
7291            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7292        let rope_sin = self
7293            .const_f32_like(sin_data, shape)
7294            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7295        (rope_cos, rope_sin)
7296    }
7297
7298    /// Rotary position embedding with **per-batch-row** tables.
7299    ///
7300    /// `self` is `[B, H, 1, D]`; `cos`/`sin` are `[B, 1, 1, D]` (row `b` holds the
7301    /// table for sequence `b`'s own position — see [`Self::rope_tables_const_batched`]).
7302    /// Broadcasting the `[B, 1, 1, D]` tables over the head axis is what lets one
7303    /// table row serve all of that sequence's heads.
7304    ///
7305    /// This is `fuel_graph::NodeHandle::rope_with_tables_decomposed`'s body
7306    /// (`fuel-graph/src/lib.rs` ~6931-6954) with the table shape generalized from
7307    /// one shared position to one-per-row — **same ops, same order, same
7308    /// associativity** (`y = x·cos + concat(-x[…,D/2..], x[…,..D/2])·sin`), so at
7309    /// `B == 1` it is bit-identical to `rope_with_tables_decomposed`. Built on the
7310    /// public `Tensor` surface (not a new `fuel-graph` op) deliberately: the
7311    /// single-position [`Self::rope_with_tables_decomposed`] hard-requires
7312    /// `cos.dims() == [seq, d]`, so it cannot carry per-row tables, and rebuilding
7313    /// the lowering here avoids re-entering the `fuel-graph` rope op.
7314    ///
7315    /// (Adopted from the Lightbulb consumer's verified `rope_batched`; the
7316    /// mechanism belongs in Fuel, not the consumer.)
7317    pub fn rope_batched(
7318        &self,
7319        cos: &Self,
7320        sin: &Self,
7321    ) -> std::result::Result<Self, fuel_ir::Error> {
7322        let dims: Vec<usize> = self.inner.shape().dims().to_vec();
7323        let rank = dims.len();
7324        if rank < 2 {
7325            return Err(fuel_ir::Error::Msg(format!(
7326                "rope_batched: expected rank >= 2, got {dims:?}",
7327            ))
7328            .bt());
7329        }
7330        let d = dims[rank - 1];
7331        if !d.is_multiple_of(2) {
7332            return Err(
7333                fuel_ir::Error::Msg(format!("rope_batched: head_dim {d} must be even",)).bt(),
7334            );
7335        }
7336        let half = d / 2;
7337        let target = Shape::from_dims(&dims);
7338
7339        let cos_b = cos.broadcast_to(target.clone())?;
7340        let sin_b = sin.broadcast_to(target)?;
7341
7342        let first = self.slice(rank - 1, 0, half)?;
7343        let second = self.slice(rank - 1, half, half)?;
7344        let rotated = second.neg().concat(&first, rank - 1)?;
7345
7346        let left = self.mul(&cos_b)?;
7347        let right = rotated.mul(&sin_b)?;
7348        left.add(&right)
7349    }
7350
7351    /// Apply RoPE to the first `rope_dim` entries of each head and
7352    /// pass the remaining `head_dim - rope_dim` features through
7353    /// unchanged. `head_dim` is derived from the receiver's last-dim
7354    /// size. When `rope_dim == head_dim` this reduces to
7355    /// [`Self::rope_with_tables`].
7356    ///
7357    /// Implements the partial-rotary convention used by StableLM,
7358    /// Phi, Persimmon, MixFormer, RecurrentGemma, and Gemma-4 text —
7359    /// all the ports that carried an identical 5-line `slice + rope +
7360    /// concat` helper before this method.
7361    pub fn rope_partial(
7362        &self,
7363        rope_cos: &Self,
7364        rope_sin: &Self,
7365        rope_dim: usize,
7366    ) -> std::result::Result<Self, fuel_ir::Error> {
7367        let dims = self.inner.shape();
7368        let dims = dims.dims();
7369        let head_dim = *dims.last().ok_or_else(|| {
7370            fuel_ir::Error::Msg("rope_partial: receiver must have at least one dimension".into())
7371                .bt()
7372        })?;
7373        if rope_dim == head_dim {
7374            return self.rope_with_tables(rope_cos, rope_sin);
7375        }
7376        if rope_dim > head_dim {
7377            return Err(fuel_ir::Error::Msg(format!(
7378                "rope_partial: rope_dim={rope_dim} exceeds head_dim={head_dim}",
7379            ))
7380            .bt());
7381        }
7382        let last = dims.len() - 1;
7383        let pass_dim = head_dim - rope_dim;
7384        let rot = self.slice(last, 0, rope_dim)?;
7385        let pass = self.slice(last, rope_dim, pass_dim)?;
7386        let rot_rotated = rot.rope_with_tables(rope_cos, rope_sin)?;
7387        rot_rotated.concat(&pass, last)
7388    }
7389
7390    /// `Option<Arc<[f32]>>` variant of [`Self::add_trailing_bias`]: if
7391    /// `bias.is_none()`, return `self` unchanged; else apply
7392    /// `add_trailing_bias`. Models the `linear_b` / `linear_no_bias`
7393    /// branch every per-port `optional_bias` / `opt_bias` helper does.
7394    pub fn add_optional_trailing_bias(
7395        &self,
7396        bias: Option<&std::sync::Arc<[f32]>>,
7397    ) -> std::result::Result<Self, fuel_ir::Error> {
7398        match bias {
7399            None => Ok(self.clone()),
7400            Some(b) => self.add_trailing_bias(std::sync::Arc::clone(b)),
7401        }
7402    }
7403
7404    /// Logit-softcap: `cap · tanh(self / cap)`. Used by the Gemma-2 /
7405    /// Gemma-3 attention-logit and final-logit softcap branches. The
7406    /// math is identical regardless of where the cap is applied;
7407    /// retired the two per-port `softcap` / `apply_softcap` helpers in
7408    /// favor of this method.
7409    pub fn softcap(&self, cap: f64) -> Self {
7410        self.mul_scalar(1.0 / cap).tanh().mul_scalar(cap)
7411    }
7412
7413    /// `Option<f64>` variant of [`Self::softcap`]: when `cap.is_none()`
7414    /// or `cap <= 0.0`, return `self` unchanged; else apply
7415    /// [`Self::softcap`]. Mirrors the optional-bias pattern.
7416    pub fn softcap_optional(&self, cap: Option<f64>) -> Self {
7417        match cap {
7418            Some(c) if c > 0.0 => self.softcap(c),
7419            _ => self.clone(),
7420        }
7421    }
7422
7423    /// Apply RMSNorm along the last dim with `(gain + offset) · x`.
7424    /// Equivalent to [`Self::rms_norm_affine`] after adding a scalar
7425    /// to every gain element — used by Gemma-family ports where
7426    /// the stored gain represents `gain - 1` and the runtime path
7427    /// must reconstruct `gain + 1`.
7428    ///
7429    /// Materializes the shifted gain on the receiver's graph; one
7430    /// allocation per call.
7431    pub fn rms_norm_affine_with_offset(
7432        &self,
7433        gain: &[f32],
7434        offset: f32,
7435        eps: f64,
7436    ) -> std::result::Result<Self, fuel_ir::Error> {
7437        let shifted: std::sync::Arc<[f32]> =
7438            std::sync::Arc::from(gain.iter().map(|g| *g + offset).collect::<Vec<_>>());
7439        self.rms_norm_affine(shifted, eps)
7440    }
7441
7442    /// Apply RMSNorm along the last dim with an affine `gain · x`
7443    /// post-step (no bias — RMSNorm has no β term). `gain` is a
7444    /// length-`gain.len()` vector materialized fresh on the
7445    /// receiver's graph and broadcast across all leading dims.
7446    pub fn rms_norm_affine(
7447        &self,
7448        gain: std::sync::Arc<[f32]>,
7449        eps: f64,
7450    ) -> std::result::Result<Self, fuel_ir::Error> {
7451        let hidden = gain.len();
7452        let normed = self.rms_norm_last_dim(eps)?;
7453        let gain_t = self.const_f32_like(gain, Shape::from_dims(&[hidden]))?;
7454        normed.broadcast_mul(&gain_t)
7455    }
7456
7457    /// Global average pool over the spatial dims of a rank-4
7458    /// `(B, C, H, W)` tensor: reduces dims 2 and 3, returning
7459    /// `(B, C)`. For the keepdim variant (`(B, C, 1, 1)`, used by
7460    /// SE blocks), follow with `.reshape(Shape::from_dims(&[B, C, 1, 1]))`.
7461    ///
7462    /// Backs the classification heads of every conv vision port
7463    /// (ResNet, EfficientNet, ConvMixer, FastViT, MobileNetV4,
7464    /// MobileOne, RepVGG, ConvNeXt, EfficientViT, etc.) plus the
7465    /// pre-projection pool inside each squeeze-excite block.
7466    pub fn global_avg_pool_2d(&self) -> std::result::Result<Self, fuel_ir::Error> {
7467        let dims = self.inner.shape().dims().to_vec();
7468        debug_assert_eq!(
7469            dims.len(),
7470            4,
7471            "global_avg_pool_2d: input must be rank 4 (B, C, H, W), got {dims:?}"
7472        );
7473        // Reduce W first (dim 3), then H (dim 2 of the H-reduced (B, C, H) tensor).
7474        self.mean_dim(3_usize)?.mean_dim(2_usize)
7475    }
7476
7477    /// Apply a per-channel affine `gain · x + bias` to a rank-4
7478    /// `(B, C, H, W)` tensor. Both `gain` and `bias` are length-`C`
7479    /// vectors materialized fresh on the receiver's graph and
7480    /// broadcast across the spatial axes.
7481    ///
7482    /// Equivalent to fused-affine BatchNorm at inference time:
7483    /// the running mean / running var / eps are absorbed at load
7484    /// time into `gain = γ / sqrt(var + eps)` and
7485    /// `bias = β - μ · γ / sqrt(var + eps)`, so the runtime forward
7486    /// is just this multiply-add. Used by inference-only conv
7487    /// vision ports (ResNet, EfficientNet, FastViT, etc.).
7488    pub fn channel_affine_4d(
7489        &self,
7490        gain: std::sync::Arc<[f32]>,
7491        bias: std::sync::Arc<[f32]>,
7492    ) -> std::result::Result<Self, fuel_ir::Error> {
7493        let dims = self.inner.shape().dims().to_vec();
7494        debug_assert_eq!(
7495            dims.len(),
7496            4,
7497            "channel_affine_4d: input must be rank 4 (B, C, H, W), got {dims:?}"
7498        );
7499        let channels = dims[1];
7500        debug_assert_eq!(
7501            gain.len(),
7502            channels,
7503            "channel_affine_4d: gain len ({}) != C ({})",
7504            gain.len(),
7505            channels
7506        );
7507        debug_assert_eq!(
7508            bias.len(),
7509            channels,
7510            "channel_affine_4d: bias len ({}) != C ({})",
7511            bias.len(),
7512            channels
7513        );
7514        let w_t = self
7515            .const_f32_like(gain, Shape::from_dims(&[channels]))?
7516            .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7517        let b_t = self
7518            .const_f32_like(bias, Shape::from_dims(&[channels]))?
7519            .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7520        self.broadcast_mul(&w_t)?.broadcast_add(&b_t)
7521    }
7522
7523    /// Build the strict additive causal mask `(seq_len, seq_len)`
7524    /// anchored on `anchor`'s graph: 0 on and below the diagonal,
7525    /// `f32::NEG_INFINITY` above it. Add to attention scores before
7526    /// softmax to enforce strict causality (position `i` cannot
7527    /// attend to position `j > i`).
7528    ///
7529    /// Equivalent to the `(T, T)` mask several ports build inline
7530    /// — promoted here so call sites stop drifting.
7531    pub fn additive_causal_mask_like(anchor: &Tensor, seq_len: usize) -> Self {
7532        let mut data = vec![0.0_f32; seq_len * seq_len];
7533        for i in 0..seq_len {
7534            for j in (i + 1)..seq_len {
7535                data[i * seq_len + j] = f32::NEG_INFINITY;
7536            }
7537        }
7538        // GAP-003 carve-out, PROOF LOCAL: `data` is `vec![_; seq_len * seq_len]`
7539        // six lines up and the loop only writes IN PLACE -- it cannot change the
7540        // length -- against a `[seq_len, seq_len]` shape. Both from `seq_len`.
7541        anchor
7542            .const_f32_like(
7543                std::sync::Arc::from(data),
7544                Shape::from_dims(&[seq_len, seq_len]),
7545            )
7546            .expect(
7547                "additive_causal_mask_like: vec![_; seq_len*seq_len] against [seq_len, seq_len]",
7548            )
7549    }
7550
7551    /// Lower-triangular ones matrix `[n, n]`. `tril2(n).to_dtype(dtype)` is
7552    /// the causal-attention-mask building block.
7553    pub fn tril2(n: usize, dtype: DType, device: &Device) -> Self {
7554        let mut data = vec![0.0_f32; n * n];
7555        for i in 0..n {
7556            for j in 0..=i {
7557                data[i * n + j] = 1.0;
7558            }
7559        }
7560        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
7561        // saying it CAN would be a false claim in the signature -- `tril2` would
7562        // return a `Result` that is never `Err`, and every caller would write a
7563        // `?` for an error that does not exist.
7564        //
7565        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
7566        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
7567        // in this function; no caller supplies either, so they cannot disagree.
7568        let base = Self::from_f32(data, vec![n, n], device).expect(
7569            "tril2: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n             both computed from `n` in this function -- lengths cannot disagree",
7570        );
7571        if dtype == DType::F32 {
7572            base
7573        } else {
7574            base.to_dtype(dtype).unwrap()
7575        }
7576    }
7577
7578    /// Upper-triangular ones matrix `[n, n]`.
7579    pub fn triu2(n: usize, dtype: DType, device: &Device) -> Self {
7580        let mut data = vec![0.0_f32; n * n];
7581        for i in 0..n {
7582            for j in i..n {
7583                data[i * n + j] = 1.0;
7584            }
7585        }
7586        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
7587        // saying it CAN would be a false claim in the signature -- `triu2` would
7588        // return a `Result` that is never `Err`, and every caller would write a
7589        // `?` for an error that does not exist.
7590        //
7591        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
7592        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
7593        // in this function; no caller supplies either, so they cannot disagree.
7594        let base = Self::from_f32(data, vec![n, n], device).expect(
7595            "triu2: data is vec![_; n*n] and shape is [n, n] (elem_count n*n), \n             both computed from `n` in this function -- lengths cannot disagree",
7596        );
7597        if dtype == DType::F32 {
7598            base
7599        } else {
7600            base.to_dtype(dtype).unwrap()
7601        }
7602    }
7603
7604    // ---- additional deferred-Phase-A items: indexing / multi-dim / RNG ----
7605
7606    /// Eager-API alias of [`Self::slice`] (PyTorch / Candle naming).
7607    /// `narrow(dim, start, len)` is `slice(dim, start, len)` —
7608    /// produces a view of `[start, start+len)` along `dim`. Bad input
7609    /// surfaces as a typed error at build time. Accepts any [`Dim`].
7610    pub fn narrow<D: Dim>(
7611        &self,
7612        dim: D,
7613        start: usize,
7614        len: usize,
7615    ) -> std::result::Result<Self, fuel_ir::Error> {
7616        self.slice(dim, start, len)
7617    }
7618
7619    /// Split into `chunks` views along `dim`. The split distributes the
7620    /// `chunk_size = ceil(dim_size / chunks)` extra slot to the leading
7621    /// chunks so every chunk's size differs by at most 1. If `dim_size
7622    /// < chunks`, returns `dim_size` singleton chunks instead of
7623    /// `chunks` chunks (matches eager / PyTorch). Accepts any [`Dim`].
7624    pub fn chunk<D: Dim>(
7625        &self,
7626        chunks: usize,
7627        dim: D,
7628    ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
7629        let shape = self.shape();
7630        let dim = dim.to_index(&shape, "chunk")?;
7631        if chunks == 0 {
7632            return Err(fuel_ir::Error::Msg("chunk: chunks must be > 0".into()).bt());
7633        }
7634        let dims = shape.dims();
7635        let size = dims[dim];
7636        if size < chunks {
7637            return Ok((0..size).map(|i| self.slice(dim, i, 1).unwrap()).collect());
7638        }
7639        let base = size / chunks;
7640        let extra = size % chunks;
7641        let mut out = Vec::with_capacity(chunks);
7642        let mut start = 0;
7643        for i in 0..chunks {
7644            let len = if i < extra { base + 1 } else { base };
7645            out.push(self.slice(dim, start, len).unwrap());
7646            start += len;
7647        }
7648        Ok(out)
7649    }
7650
7651    /// Sub-tensor at index `i` along dim 0. Equivalent to
7652    /// `self.slice(0, i, 1).unwrap().squeeze(0)`. Matches eager's `crate::Tensor::get`.
7653    pub fn get(&self, i: usize) -> std::result::Result<Self, fuel_ir::Error> {
7654        let dims = self.shape().dims().to_vec();
7655        if dims.is_empty() {
7656            return Ok(self.clone());
7657        }
7658        self.slice(0, i, 1).unwrap().squeeze(0)
7659    }
7660
7661    /// Sub-tensor at index along an arbitrary dim. Equivalent to
7662    /// `self.slice(dim, index, 1).unwrap().squeeze(dim)`. Matches eager's
7663    /// `crate::Tensor::get_on_dim`. Accepts any [`Dim`].
7664    pub fn get_on_dim<D: Dim>(
7665        &self,
7666        dim: D,
7667        index: usize,
7668    ) -> std::result::Result<Self, fuel_ir::Error> {
7669        let shape = self.shape();
7670        let dim = dim.to_index(&shape, "get_on_dim")?;
7671        self.slice(dim, index, 1).unwrap().squeeze(dim)
7672    }
7673
7674    /// Multi-dim sum: reduce over every dim in `dims`, squeezing each.
7675    /// Reduces from the highest dim down so the lower dim indices stay
7676    /// valid throughout the reduction.
7677    pub fn sum_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7678        let shape = self.shape();
7679        let mut sorted = dims.to_indexes(&shape, "sum_dims")?;
7680        sorted.sort_by(|a, b| b.cmp(a));
7681        sorted.dedup();
7682        let mut acc = self.clone();
7683        for d in sorted {
7684            acc = acc.sum_dim(d)?;
7685        }
7686        Ok(acc)
7687    }
7688
7689    /// Multi-dim mean: reduce over every dim in `dims`, squeezing each.
7690    /// Reduces from the highest dim down. Accepts any [`Dims`].
7691    pub fn mean_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7692        let shape = self.shape();
7693        let mut sorted = dims.to_indexes(&shape, "mean_dims")?;
7694        sorted.sort_by(|a, b| b.cmp(a));
7695        sorted.dedup();
7696        let mut acc = self.clone();
7697        for d in sorted {
7698            acc = acc.mean_dim(d)?;
7699        }
7700        Ok(acc)
7701    }
7702
7703    /// Multi-dim sum with keepdim: every named dim becomes size 1
7704    /// instead of being squeezed out. Reduce-order-invariant (every
7705    /// keepdim preserves indices). Returns Result because of cascade
7706    /// from [`Self::sum_keepdim`].
7707    pub fn sum_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7708        let mut sorted: Vec<usize> = dims.to_vec();
7709        sorted.sort();
7710        sorted.dedup();
7711        let mut acc = self.clone();
7712        for d in sorted {
7713            acc = acc.sum_keepdim(d)?;
7714        }
7715        Ok(acc)
7716    }
7717
7718    /// Multi-dim mean with keepdim.
7719    pub fn mean_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7720        let mut sorted: Vec<usize> = dims.to_vec();
7721        sorted.sort();
7722        sorted.dedup();
7723        let mut acc = self.clone();
7724        for d in sorted {
7725            acc = acc.mean_keepdim(d)?;
7726        }
7727        Ok(acc)
7728    }
7729
7730    /// Uniform random tensor in `[lo, up)` with shape/dtype/device matching `self`.
7731    /// Backed by [`rand::rng`]. Returns Err for unsupported dtypes.
7732    pub fn rand_like(&self, lo: f64, up: f64) -> std::result::Result<Self, fuel_ir::Error> {
7733        Self::rand(self.shape(), lo, up, self.dtype(), &Device::cpu())
7734    }
7735
7736    /// Normal random tensor with shape/dtype/device matching `self`.
7737    /// Returns Err for unsupported dtypes or invalid stdev.
7738    pub fn randn_like(&self, mean: f64, stdev: f64) -> std::result::Result<Self, fuel_ir::Error> {
7739        Self::randn(self.shape(), mean, stdev, self.dtype(), &Device::cpu())
7740    }
7741
7742    /// Uniform random tensor in `[lo, up)`. Static factory.
7743    /// Supported dtypes: F32, F64, BF16, F16. F32 is the typical
7744    /// initialization target. Returns Err for any other dtype.
7745    pub fn rand(
7746        shape: impl Into<Shape>,
7747        lo: f64,
7748        up: f64,
7749        dtype: DType,
7750        device: &Device,
7751    ) -> std::result::Result<Self, fuel_ir::Error> {
7752        use rand::RngExt;
7753        let shape = shape.into();
7754        let n = shape.elem_count();
7755        let mut rng = rand::rng();
7756        match dtype {
7757            DType::F32 => {
7758                let data: Vec<f32> = (0..n).map(|_| rng.random_range(lo..up) as f32).collect();
7759                Self::from_f32(data, shape, device)
7760            }
7761            DType::F64 => {
7762                let data: Vec<f64> = (0..n).map(|_| rng.random_range(lo..up)).collect();
7763                Self::from_f64(data, shape, device)
7764            }
7765            DType::BF16 => {
7766                let data: Vec<half::bf16> = (0..n)
7767                    .map(|_| fuel_ir::round::bf16_from_f64(rng.random_range(lo..up)))
7768                    .collect();
7769                Self::from_bf16(data, shape, device)
7770            }
7771            DType::F16 => {
7772                let data: Vec<half::f16> = (0..n)
7773                    .map(|_| fuel_ir::round::f16_from_f64(rng.random_range(lo..up)))
7774                    .collect();
7775                Self::from_f16(data, shape, device)
7776            }
7777            other => {
7778                Err(fuel_ir::Error::Msg(format!("Tensor::rand: unsupported dtype {other:?}",)).bt())
7779            }
7780        }
7781    }
7782
7783    /// Normal random tensor with given `mean` and `stdev`. Static factory.
7784    /// Supported dtypes: F32, F64, BF16, F16. Returns Err on any other
7785    /// dtype, or if `stdev` is not finite / not positive.
7786    pub fn randn(
7787        shape: impl Into<Shape>,
7788        mean: f64,
7789        stdev: f64,
7790        dtype: DType,
7791        device: &Device,
7792    ) -> std::result::Result<Self, fuel_ir::Error> {
7793        use rand_distr::{Distribution, Normal};
7794        let shape = shape.into();
7795        let n = shape.elem_count();
7796        let normal = Normal::new(mean, stdev).map_err(|e| {
7797            fuel_ir::Error::Msg(format!("Tensor::randn: invalid stdev={stdev}: {e}",)).bt()
7798        })?;
7799        let mut rng = rand::rng();
7800        match dtype {
7801            DType::F32 => {
7802                let data: Vec<f32> = (0..n).map(|_| normal.sample(&mut rng) as f32).collect();
7803                Self::from_f32(data, shape, device)
7804            }
7805            DType::F64 => {
7806                let data: Vec<f64> = (0..n).map(|_| normal.sample(&mut rng)).collect();
7807                Self::from_f64(data, shape, device)
7808            }
7809            DType::BF16 => {
7810                let data: Vec<half::bf16> = (0..n)
7811                    .map(|_| fuel_ir::round::bf16_from_f64(normal.sample(&mut rng)))
7812                    .collect();
7813                Self::from_bf16(data, shape, device)
7814            }
7815            DType::F16 => {
7816                let data: Vec<half::f16> = (0..n)
7817                    .map(|_| fuel_ir::round::f16_from_f64(normal.sample(&mut rng)))
7818                    .collect();
7819                Self::from_f16(data, shape, device)
7820            }
7821            other => Err(fuel_ir::Error::Msg(format!(
7822                "Tensor::randn: unsupported dtype {other:?}",
7823            ))
7824            .bt()),
7825        }
7826    }
7827
7828    /// `arange(start, end, device)`: a rank-1 tensor of `[start, end)` in
7829    /// step 1, dtype F32. Matches NumPy / PyTorch convention.
7830    pub fn arange(start: f32, end: f32, device: &Device) -> Self {
7831        Self::arange_step(start, end, 1.0, device)
7832    }
7833
7834    /// `arange_step(start, end, step, device)`: a rank-1 tensor of
7835    /// `[start, end)` with constant step. F32 only for the static
7836    /// factory; cast for other dtypes. Errors at runtime if `step ==
7837    /// 0`.
7838    pub fn arange_step(start: f32, end: f32, step: f32, device: &Device) -> Self {
7839        assert!(step != 0.0, "arange_step: step must be non-zero");
7840        let mut data = Vec::new();
7841        let mut current = start;
7842        if step > 0.0 {
7843            while current < end {
7844                data.push(current);
7845                current += step;
7846            }
7847        } else {
7848            while current > end {
7849                data.push(current);
7850                current += step;
7851            }
7852        }
7853        let n = data.len();
7854        // GAP-003 carve-out. `.expect`, NOT `?`: this cannot fail, and a `Result`
7855        // here would be one that is never `Err` -- a false claim in the signature
7856        // that every caller would then write a `?` for.
7857        //
7858        // THE PROOF IS LOCAL AND ONE LINE UP: `n` IS `data.len()`, and the shape
7859        // is `[n]`. The shape is derived FROM the buffer, so they cannot disagree.
7860        Self::from_f32(data, vec![n], device).expect(
7861            "arange_step: shape is [n] where n IS data.len(), computed one line              above from that same buffer -- the lengths cannot disagree",
7862        )
7863    }
7864
7865    /// Linearly-spaced 1D tensor with `n` points from `start` to `end`
7866    /// (inclusive on both ends). Matches NumPy's `linspace`.
7867    pub fn linspace(start: f32, end: f32, n: usize, device: &Device) -> Self {
7868        assert!(n >= 1, "linspace: n must be >= 1");
7869        if n == 1 {
7870            // GAP-003 carve-out: a one-element vec with shape [1], on one line.
7871            return Self::from_f32(vec![start], vec![1], device)
7872                .expect("linspace: vec![start] has exactly 1 element and the shape is [1]");
7873        }
7874        let step = (end - start) / ((n - 1) as f32);
7875        let data: Vec<f32> = (0..n).map(|i| start + step * (i as f32)).collect();
7876        // GAP-003 carve-out: `data` is a `(0..n)` map -- exactly `n` elements --
7877        // and the shape is `[n]`. Both from the same `n`, two lines apart.
7878        Self::from_f32(data, vec![n], device).expect(
7879            "linspace: data is (0..n).map(..).collect() so it has exactly n              elements, and the shape is [n] -- both from the same `n`",
7880        )
7881    }
7882
7883    /// Frobenius norm: `sqrt(sum(self * self))`. Returns a scalar tensor.
7884    pub fn norm(&self) -> Self {
7885        self.sqr().sum_all().sqrt()
7886    }
7887
7888    /// General 1-D cross-correlation. Shapes:
7889    /// - `self`: `[N, Cin, T]`
7890    /// - `weight`: `[Cout, Cin/groups, K]`
7891    /// - `bias` (optional): `[Cout]`
7892    /// - returns: `[N, Cout, Tout]` where `Tout = (T + 2·padding - K) /
7893    ///   stride + 1`
7894    ///
7895    /// Implemented as a composite via Conv2D: unsqueeze the spatial dim
7896    /// to make a unit `H = 1`, run `Conv2D` with `Kh = 1, stride.0 = 1,
7897    /// padding.0 = 0`, then squeeze the dim back out. Works through
7898    /// every backend's Conv2D dispatch (CPU, CUDA via baracuda,
7899    /// Vulkan, AOCL, MKL). The future fused `Op::Conv1D` will collapse
7900    /// the unsqueeze/squeeze pair when a high-volume Conv1D consumer
7901    /// materializes.
7902    pub fn conv1d(
7903        &self,
7904        weight: &Self,
7905        bias: Option<&Self>,
7906        stride: usize,
7907        padding: usize,
7908        groups: usize,
7909    ) -> std::result::Result<Self, fuel_ir::Error> {
7910        let x_dims = self.shape().dims().to_vec();
7911        let w_dims = weight.shape().dims().to_vec();
7912        if x_dims.len() != 3 {
7913            return Err(fuel_ir::Error::Msg(format!(
7914                "conv1d: x must be rank 3 [N, Cin, T], got {x_dims:?}",
7915            ))
7916            .bt());
7917        }
7918        if w_dims.len() != 3 {
7919            return Err(fuel_ir::Error::Msg(format!(
7920                "conv1d: weight must be rank 3 [Cout, Cin/groups, K], got {w_dims:?}",
7921            ))
7922            .bt());
7923        }
7924        if groups < 1 {
7925            return Err(fuel_ir::Error::Msg("conv1d: groups must be ≥ 1".into()).bt());
7926        }
7927        if stride < 1 {
7928            return Err(fuel_ir::Error::Msg("conv1d: stride must be ≥ 1".into()).bt());
7929        }
7930        // Add a unit H dim at index 2 → [N, Cin, 1, T] and [Cout, Cin/g, 1, K].
7931        let x_4d = self.unsqueeze(2_usize)?;
7932        let w_4d = weight.unsqueeze(2_usize)?;
7933        let out_4d = x_4d.conv2d(&w_4d, bias, (1, stride), (0, padding), groups)?;
7934        out_4d.squeeze(2)
7935    }
7936
7937    /// Eager-API parity for `conv1d_with_algo`. The `_algo` selector is
7938    /// ignored on the lazy path — algorithm selection happens at
7939    /// backend dispatch time, not at graph construction. Reduces to
7940    /// [`Self::conv1d`].
7941    pub fn conv1d_with_algo<A>(
7942        &self,
7943        weight: &Self,
7944        bias: Option<&Self>,
7945        stride: usize,
7946        padding: usize,
7947        groups: usize,
7948        _algo: A,
7949    ) -> std::result::Result<Self, fuel_ir::Error> {
7950        self.conv1d(weight, bias, stride, padding, groups)
7951    }
7952
7953    /// 2-D average pooling. Input `[N, C, H, W]`, output
7954    /// `[N, C, H_out, W_out]` where
7955    /// `H_out = (H + 2·padding.0 - kernel.0) / stride.0 + 1`.
7956    ///
7957    /// Implemented as a **depthwise Conv2D** with a constant
7958    /// `1/(kh·kw)` kernel: one graph node + the kernel const. Works
7959    /// through every backend's Conv2D dispatch and inherits Conv2D's
7960    /// gradient. Composite supports arbitrary kernel / stride /
7961    /// padding.
7962    pub fn avg_pool2d(
7963        &self,
7964        kernel: (usize, usize),
7965        stride: (usize, usize),
7966        padding: (usize, usize),
7967        count_include_pad: bool,
7968    ) -> std::result::Result<Self, fuel_ir::Error> {
7969        let dims = self.shape().dims().to_vec();
7970        if dims.len() != 4 {
7971            return Err(fuel_ir::Error::Msg(format!(
7972                "avg_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
7973            ))
7974            .bt());
7975        }
7976        let (c, h, w) = (dims[1], dims[2], dims[3]);
7977        let (kh, kw) = kernel;
7978        if kh == 0 || kw == 0 {
7979            return Err(
7980                fuel_ir::Error::Msg("avg_pool2d: kernel sizes must be positive".into()).bt(),
7981            );
7982        }
7983
7984        // KISS-Ops §6.13: count_include_pad must be an EXPLICIT choice, not
7985        // an implicit torch-style default silently baked into the divisor.
7986        // With no padding the two modes coincide (every window is full),
7987        // so the uniform-divisor path below is exact either way.
7988        if count_include_pad || padding == (0, 0) {
7989            let inv = 1.0_f32 / ((kh * kw) as f32);
7990            // Depthwise kernel: one filter per input channel, each filter
7991            // is a constant 1/(kh·kw). Shape [C, 1, kh, kw] with groups=C
7992            // makes Conv2D compute one independent kernel per channel.
7993            let weight =
7994                self.const_f32_like(vec![inv; c * kh * kw], Shape::from_dims(&[c, 1, kh, kw]))?;
7995            return self.conv2d(&weight, None, stride, padding, c);
7996        }
7997
7998        // count_include_pad = false with real padding: a uniform divisor is
7999        // WRONG at every border window (it silently averages in the padded
8000        // zeros as if they were real taps, undercounting the true mean by
8001        // exactly the fraction of the window that's padding). The correct
8002        // divisor is the per-position COUNT of valid (non-padded) taps, which
8003        // varies by output position — sum-pool (an all-ones depthwise kernel)
8004        // then divide by that count map instead of a constant.
8005        //
8006        // A window can have ZERO valid taps (e.g. a 1x1 input with padding
8007        // >= kernel size): every tap it covers is padding. The count map
8008        // would then be zero at that position and `broadcast_div` would
8009        // silently emit NaN/inf instead of a defined average. Refuse up
8010        // front rather than let that propagate -- computed host-side from
8011        // (H, W, kernel, stride, padding) alone, no graph ops needed.
8012        if let Some((axis, out_idx)) = first_zero_tap_output_index(h, kh, stride.0, padding.0)
8013            .map(|i| ("H", i))
8014            .or_else(|| first_zero_tap_output_index(w, kw, stride.1, padding.1).map(|i| ("W", i)))
8015        {
8016            return Err(fuel_ir::Error::Msg(format!(
8017                "avg_pool2d: count_include_pad=false has no valid (non-padded) \
8018                 taps for output position {out_idx} on the {axis} axis \
8019                 (kernel={kernel:?}, stride={stride:?}, padding={padding:?}, \
8020                 input H×W={h}×{w}) — the average would divide by zero",
8021            ))
8022            .bt());
8023        }
8024
8025        let sum_weight = self.const_f32_like(
8026            vec![1.0_f32; c * kh * kw],
8027            Shape::from_dims(&[c, 1, kh, kw]),
8028        )?;
8029        let summed = self.conv2d(&sum_weight, None, stride, padding, c)?;
8030
8031        // The valid-tap count depends only on (H, W, kernel, stride,
8032        // padding) -- not on N or C -- so it's computed once at minimal
8033        // [1, 1, H, W] size and broadcast-divided into every (n, c) plane.
8034        let ones_hw = self.const_f32_like(vec![1.0_f32; h * w], Shape::from_dims(&[1, 1, h, w]))?;
8035        let count_weight =
8036            self.const_f32_like(vec![1.0_f32; kh * kw], Shape::from_dims(&[1, 1, kh, kw]))?;
8037        let count = ones_hw.conv2d(&count_weight, None, stride, padding, 1)?;
8038
8039        summed.broadcast_div(&count)
8040    }
8041
8042    /// Eager-API parity for `avg_pool2d_with_stride`. Same shape as
8043    /// [`Self::avg_pool2d`] but the stride is passed explicitly rather
8044    /// than inferred from kernel.
8045    pub fn avg_pool2d_with_stride(
8046        &self,
8047        kernel: (usize, usize),
8048        stride: (usize, usize),
8049    ) -> std::result::Result<Self, fuel_ir::Error> {
8050        // No padding, so count_include_pad is a don't-care (both modes
8051        // coincide — see avg_pool2d's own short-circuit for this case).
8052        self.avg_pool2d(kernel, stride, (0, 0), true)
8053    }
8054
8055    /// 2-D max pooling. Input `[N, C, H, W]`, output
8056    /// `[N, C, H_out, W_out]` where
8057    /// `H_out = (H + 2·padding.0 - kernel.0) / stride.0 + 1`.
8058    ///
8059    /// Composite via slice + maximum: pad the input, then for every
8060    /// `(ky, kx)` in `[0..kh, 0..kw]` slice the strided grid of taps
8061    /// (one tap per output position) and take the elementwise max.
8062    /// Produces `kh·kw` nodes per call plus padding — cheap for the
8063    /// common 2×2 / 3×3 cases.
8064    ///
8065    /// Strided-slice trick: for stride `sh`, reshape the padded H from
8066    /// `(H_out · sh)` to `(H_out, sh)`, then slice the inner `sh`-dim
8067    /// at the tap index. Requires `H_padded == H_out · sh` exactly.
8068    /// Inputs that don't divide cleanly will be padded so they do.
8069    pub fn max_pool2d(
8070        &self,
8071        kernel: (usize, usize),
8072        stride: (usize, usize),
8073        padding: (usize, usize),
8074    ) -> std::result::Result<Self, fuel_ir::Error> {
8075        // KISS-Ops §6.13 / PyTorch-correct semantics: a padded slot must
8076        // never win the max — zero padding silently wins every all-negative
8077        // window (e.g. post-activation feature maps dominated by negative
8078        // values at the border), which is a real correctness bug, not a
8079        // style choice. `f32::NEG_INFINITY` padding is the fix; use
8080        // [`Self::max_pool2d_with_pad_value`] directly for any OTHER pad
8081        // value (there is no implicit torch-style default here anymore).
8082        self.max_pool2d_with_pad_value(kernel, stride, padding, f32::NEG_INFINITY)
8083    }
8084
8085    /// `max_pool2d` variant where the boundary padding is filled with an
8086    /// explicit `pad_value` instead of `0.0`. Pass `f32::NEG_INFINITY`
8087    /// for PyTorch-correct semantics (padded slots can never win the
8088    /// max). All other constraints match [`Self::max_pool2d`]; the only
8089    /// difference is the constant value the implicit boundary pad uses.
8090    pub fn max_pool2d_with_pad_value(
8091        &self,
8092        kernel: (usize, usize),
8093        stride: (usize, usize),
8094        padding: (usize, usize),
8095        pad_value: f32,
8096    ) -> std::result::Result<Self, fuel_ir::Error> {
8097        let dims = self.shape().dims().to_vec();
8098        if dims.len() != 4 {
8099            return Err(fuel_ir::Error::Msg(format!(
8100                "max_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8101            ))
8102            .bt());
8103        }
8104        let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8105        let (kh, kw) = kernel;
8106        let (sh, sw) = stride;
8107        let (ph, pw) = padding;
8108        if kh == 0 || kw == 0 {
8109            return Err(
8110                fuel_ir::Error::Msg("max_pool2d: kernel sizes must be positive".into()).bt(),
8111            );
8112        }
8113        if sh == 0 || sw == 0 {
8114            return Err(fuel_ir::Error::Msg("max_pool2d: strides must be positive".into()).bt());
8115        }
8116        let h_padded_min = h + 2 * ph;
8117        let w_padded_min = w + 2 * pw;
8118        if h_padded_min < kh || w_padded_min < kw {
8119            return Err(fuel_ir::Error::Msg(format!(
8120                "max_pool2d: padded input ({h_padded_min}×{w_padded_min}) smaller than kernel ({kh}×{kw})",
8121            )).bt());
8122        }
8123        let h_out = (h_padded_min - kh) / sh + 1;
8124        let w_out = (w_padded_min - kw) / sw + 1;
8125        // Pad H/W to be exactly (h_out · sh + (kh - sh)) and (w_out · sw + (kw - sw)),
8126        // i.e., enough to contain every (ky, kx) tap for every output.
8127        let h_total = h_out * sh + (kh - 1);
8128        let w_total = w_out * sw + (kw - 1);
8129        let extra_h = h_total.saturating_sub(h_padded_min);
8130        let extra_w = w_total.saturating_sub(w_padded_min);
8131        let padded = self
8132            .pad_with_value(2, ph, ph + extra_h, pad_value)?
8133            .pad_with_value(3, pw, pw + extra_w, pad_value)?;
8134        // For each (ky, kx) collect the strided tap.
8135        let mut acc: Option<Tensor> = None;
8136        for ky in 0..kh {
8137            // Slice H starting at ky, length h_out · sh, then reshape
8138            // to [N, C, h_out, sh, w_total] and slice the sh-dim at 0
8139            // (we'll handle stride > 1 by reshape).
8140            let row_slice = padded.slice(2, ky, h_out * sh).unwrap();
8141            // Reshape H dim of length `h_out · sh` into (h_out, sh),
8142            // then take dim 3 at offset 0 (the tap on the sh axis).
8143            let row_reshaped = row_slice.reshape(vec![n, c, h_out, sh, w_total])?;
8144            let row_tap = row_reshaped.slice(3, 0, 1).unwrap().squeeze(3)?;
8145            for kx in 0..kw {
8146                let col_slice = row_tap.slice(3, kx, w_out * sw).unwrap();
8147                let col_reshaped = col_slice.reshape(vec![n, c, h_out, w_out, sw])?;
8148                let win = col_reshaped.slice(4, 0, 1).unwrap().squeeze(4)?;
8149                acc = Some(match acc {
8150                    None => win,
8151                    Some(a) => a.maximum(&win).unwrap(),
8152                });
8153            }
8154        }
8155        acc.ok_or_else(|| fuel_ir::Error::Msg("max_pool2d: empty kernel".into()).bt())
8156    }
8157
8158    /// Eager-API parity for `max_pool2d_with_stride`.
8159    pub fn max_pool2d_with_stride(
8160        &self,
8161        kernel: (usize, usize),
8162        stride: (usize, usize),
8163    ) -> std::result::Result<Self, fuel_ir::Error> {
8164        self.max_pool2d(kernel, stride, (0, 0))
8165    }
8166
8167    /// Nearest-neighbor upsample by integer factor `scale` along the
8168    /// last two spatial dims. Input `[N, C, H, W]` → output
8169    /// `[N, C, H·scale, W·scale]`.
8170    ///
8171    /// Composite via reshape + concat + reshape: insert a unit dim
8172    /// after each spatial dim, concat `scale` copies of the tensor on
8173    /// each new dim, then collapse the inflated dims back. Same shape
8174    /// as the `upsample_nearest_2x` helper in `fuel_transformers::models::lazy_yolov8`
8175    /// and `fuel_transformers::models::lazy_sd_unet`, generalized to arbitrary scale.
8176    pub fn upsample_nearest2d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8177        if scale == 0 {
8178            return Err(
8179                fuel_ir::Error::Msg("upsample_nearest2d: scale must be positive".into()).bt(),
8180            );
8181        }
8182        let dims = self.shape().dims().to_vec();
8183        if dims.len() != 4 {
8184            return Err(fuel_ir::Error::Msg(format!(
8185                "upsample_nearest2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8186            ))
8187            .bt());
8188        }
8189        if scale == 1 {
8190            return Ok(self.clone());
8191        }
8192        let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8193        // [N, C, H, 1, W, 1]
8194        let expanded = self.reshape(vec![n, c, h, 1, w, 1])?;
8195        // Replicate along the new unit dims by concatenating scale copies.
8196        let h_expanded = (0..scale)
8197            .fold(None, |acc: Option<Tensor>, _| {
8198                Some(match acc {
8199                    None => expanded.clone(),
8200                    Some(a) => a.concat(&expanded, 3).unwrap(),
8201                })
8202            })
8203            .unwrap();
8204        let h_then_w = (0..scale)
8205            .fold(None, |acc: Option<Tensor>, _| {
8206                Some(match acc {
8207                    None => h_expanded.clone(),
8208                    Some(a) => a.concat(&h_expanded, 5).unwrap(),
8209                })
8210            })
8211            .unwrap();
8212        h_then_w.reshape(vec![n, c, h * scale, w * scale])
8213    }
8214
8215    /// Nearest-neighbor upsample for 1-D signals `[N, C, T]` by integer
8216    /// `scale`. Reshape to insert a unit dim, concat scale copies,
8217    /// reshape back.
8218    pub fn upsample_nearest1d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8219        if scale == 0 {
8220            return Err(
8221                fuel_ir::Error::Msg("upsample_nearest1d: scale must be positive".into()).bt(),
8222            );
8223        }
8224        let dims = self.shape().dims().to_vec();
8225        if dims.len() != 3 {
8226            return Err(fuel_ir::Error::Msg(format!(
8227                "upsample_nearest1d: input must be rank 3 [N, C, T], got {dims:?}",
8228            ))
8229            .bt());
8230        }
8231        if scale == 1 {
8232            return Ok(self.clone());
8233        }
8234        let (n, c, t) = (dims[0], dims[1], dims[2]);
8235        let expanded = self.reshape(vec![n, c, t, 1])?;
8236        let replicated = (0..scale)
8237            .fold(None, |acc: Option<Tensor>, _| {
8238                Some(match acc {
8239                    None => expanded.clone(),
8240                    Some(a) => a.concat(&expanded, 3).unwrap(),
8241                })
8242            })
8243            .unwrap();
8244        replicated.reshape(vec![n, c, t * scale])
8245    }
8246
8247    /// 2-D nearest interpolation to an explicit target size.
8248    /// Arbitrary ratios (non-integer, non-uniform between H and
8249    /// W) supported via an `index_select`-based composite. The
8250    /// indexing convention matches PyTorch / the eager kernel:
8251    /// `src_h[oi] = min(H - 1, floor(oi * H / H_out))`.
8252    ///
8253    /// Used by DepthAnythingV2's DPT head and similar dense
8254    /// prediction heads that resize feature maps to arbitrary
8255    /// targets.
8256    pub fn interpolate2d(
8257        &self,
8258        target_h: usize,
8259        target_w: usize,
8260    ) -> std::result::Result<Self, fuel_ir::Error> {
8261        let dims = self.shape().dims().to_vec();
8262        if dims.len() != 4 {
8263            return Err(fuel_ir::Error::Msg(format!(
8264                "interpolate2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8265            ))
8266            .bt());
8267        }
8268        let h = dims[2];
8269        let w = dims[3];
8270        if h == 0 || w == 0 || target_h == 0 || target_w == 0 {
8271            return Err(fuel_ir::Error::Msg(
8272                "interpolate2d: input + target spatial dims must be positive".into(),
8273            )
8274            .bt());
8275        }
8276        // Fast-path: identity.
8277        if target_h == h && target_w == w {
8278            return Ok(self.clone());
8279        }
8280        // Fast-path: integer-multiple uniform scale → existing
8281        // `upsample_nearest2d` (more cache-friendly than the
8282        // index_select composite for the common 2× / 4× case).
8283        if target_h.is_multiple_of(h) && target_w.is_multiple_of(w) && target_h / h == target_w / w
8284        {
8285            return self.upsample_nearest2d(target_h / h);
8286        }
8287        // General case: build per-axis source-index tensors and
8288        // index_select. Matches the eager UpsampleNearest2D
8289        // kernel's convention: src_idx = min(src - 1, floor(out * src / target)).
8290        let h_idx: Vec<u32> = (0..target_h)
8291            .map(|oi| ((oi * h) / target_h).min(h - 1) as u32)
8292            .collect();
8293        let w_idx: Vec<u32> = (0..target_w)
8294            .map(|oj| ((oj * w) / target_w).min(w - 1) as u32)
8295            .collect();
8296        let h_idx_tensor = self.const_u32_like(h_idx, fuel_ir::Shape::from_dims(&[target_h]))?;
8297        let w_idx_tensor = self.const_u32_like(w_idx, fuel_ir::Shape::from_dims(&[target_w]))?;
8298        let after_h = self.index_select(2_usize, &h_idx_tensor)?;
8299        after_h.index_select(3_usize, &w_idx_tensor)
8300    }
8301
8302    /// 1-D nearest interpolation to an explicit target size. Same
8303    /// constraints as [`Self::interpolate2d`]: integer-multiple targets
8304    /// only.
8305    pub fn interpolate1d(&self, target_t: usize) -> std::result::Result<Self, fuel_ir::Error> {
8306        let dims = self.shape().dims().to_vec();
8307        if dims.len() != 3 {
8308            return Err(fuel_ir::Error::Msg(format!(
8309                "interpolate1d: input must be rank 3 [N, C, T], got {dims:?}",
8310            ))
8311            .bt());
8312        }
8313        let t = dims[2];
8314        if t == 0 {
8315            return Err(
8316                fuel_ir::Error::Msg("interpolate1d: input length must be positive".into()).bt(),
8317            );
8318        }
8319        if !target_t.is_multiple_of(t) {
8320            return Err(fuel_ir::Error::Msg(format!(
8321                "interpolate1d: target {target_t} must be integer multiple of input {t}; non-integer ratios are future work",
8322            )).bt());
8323        }
8324        self.upsample_nearest1d(target_t / t)
8325    }
8326
8327    /// Pad with zeros along `dim`: `left` zeros before, `right` zeros
8328    /// after. Thin wrapper over [`Self::pad_with_value`] with `value = 0.0`.
8329    /// Composite — no new graph op. Accepts any [`Dim`].
8330    pub fn pad_with_zeros<D: Dim>(
8331        &self,
8332        dim: D,
8333        left: usize,
8334        right: usize,
8335    ) -> std::result::Result<Self, fuel_ir::Error> {
8336        self.pad_with_value(dim, left, right, 0.0)
8337    }
8338
8339    /// Pad with a constant `value` along `dim`: `before` slots before,
8340    /// `after` slots after. Wraps [`Self::pad`] with `PadMode::Constant`
8341    /// for the named dim (other dims get `(0, 0)`); the `f32` value is
8342    /// widened to the graph op's `f64` param. Useful for `-inf` padding
8343    /// around max-reductions (e.g. PyTorch-style `max_pool2d`, where
8344    /// padded positions must never win the max). Accepts any [`Dim`].
8345    pub fn pad_with_value<D: Dim>(
8346        &self,
8347        dim: D,
8348        before: usize,
8349        after: usize,
8350        value: f32,
8351    ) -> std::result::Result<Self, fuel_ir::Error> {
8352        let shape = self.shape();
8353        let dim = dim.to_index(&shape, "pad_with_value")?;
8354        let rank = shape.dims().len();
8355        if before == 0 && after == 0 {
8356            return Ok(self.clone());
8357        }
8358        let mut padding: Vec<(usize, usize)> = vec![(0, 0); rank];
8359        padding[dim] = (before, after);
8360        self.pad(padding, fuel_graph::PadMode::Constant, value as f64)
8361    }
8362
8363    /// Coordinate grids from rank-1 inputs. Matches PyTorch's
8364    /// `torch.meshgrid` and eager's `crate::Tensor::meshgrid`:
8365    ///
8366    /// - `xy_indexing = true` (Cartesian, NumPy default): the first
8367    ///   two inputs are swapped before broadcasting and the resulting
8368    ///   grids reversed back, so for `(x, y)` the grids carry shape
8369    ///   `[len(y), len(x)]` (image-coordinate convention).
8370    /// - `xy_indexing = false` (matrix / ij): grids carry the input
8371    ///   cardinalities in input order.
8372    ///
8373    /// Implemented as `reshape` + `repeat`. All inputs must share the
8374    /// same dtype and live on the same graph.
8375    pub fn meshgrid(
8376        args: &[&Self],
8377        xy_indexing: bool,
8378    ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
8379        if args.len() < 2 {
8380            return Err(fuel_ir::Error::Msg(
8381                "meshgrid: requires at least two rank-1 tensors".into(),
8382            )
8383            .bt());
8384        }
8385        let ordered: Vec<&Self> = if xy_indexing {
8386            args.iter().rev().copied().collect()
8387        } else {
8388            args.to_vec()
8389        };
8390        let mut lens = Vec::with_capacity(ordered.len());
8391        for (i, t) in ordered.iter().enumerate() {
8392            let dims = t.shape().dims().to_vec();
8393            if dims.len() != 1 {
8394                return Err(fuel_ir::Error::Msg(format!(
8395                    "meshgrid: input {i} must be rank 1, got shape {dims:?}",
8396                ))
8397                .bt());
8398            }
8399            lens.push(dims[0]);
8400        }
8401        let mut grids = Vec::with_capacity(ordered.len());
8402        for (idx, t) in ordered.iter().enumerate() {
8403            let mut shape = vec![1_usize; ordered.len()];
8404            shape[idx] = lens[idx];
8405            let placed = t.reshape(shape)?;
8406            let mut repeats = lens.clone();
8407            repeats[idx] = 1;
8408            let grid = placed.repeat(repeats)?;
8409            grids.push(grid);
8410        }
8411        if xy_indexing {
8412            grids.reverse();
8413        }
8414        Ok(grids)
8415    }
8416
8417    /// Repeat the tensor along each dim `repeats[i]` times. If `repeats`
8418    /// has more dims than `self`, `self` is implicitly left-padded with
8419    /// size-1 dims to match. Matches PyTorch's `Tensor.repeat`.
8420    pub fn repeat(&self, repeats: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
8421        let repeats = repeats.into();
8422        let repeats: Vec<usize> = repeats.dims().to_vec();
8423        let self_rank = self.shape().dims().len();
8424        let target_rank = repeats.len();
8425        let mut work = if self_rank < target_rank {
8426            let pad_count = target_rank - self_rank;
8427            let mut new_shape: Vec<usize> = vec![1; pad_count];
8428            new_shape.extend_from_slice(self.shape().dims());
8429            self.reshape(new_shape)?
8430        } else if self_rank > target_rank {
8431            return Err(fuel_ir::Error::Msg(format!(
8432                "repeat: repeats rank {target_rank} smaller than tensor rank {self_rank}",
8433            ))
8434            .bt());
8435        } else {
8436            self.clone()
8437        };
8438        for (axis, &n) in repeats.iter().enumerate() {
8439            if n == 0 {
8440                return Err(fuel_ir::Error::Msg(format!(
8441                    "repeat: zero repeat count at axis {axis} not supported",
8442                ))
8443                .bt());
8444            }
8445            if n == 1 {
8446                continue;
8447            }
8448            // n copies concatenated along `axis`.
8449            let base = work.clone();
8450            for _ in 1..n {
8451                work = work.concat(&base, axis)?;
8452            }
8453        }
8454        Ok(work)
8455    }
8456}
8457
8458/// For a single pooling axis, the first output index (if any) whose window
8459/// has zero valid (non-padded) taps — every tap it covers lies outside
8460/// `[0, dim)`. Used by [`Tensor::avg_pool2d`]'s `count_include_pad = false`
8461/// path to refuse a divide-by-zero divisor instead of emitting NaN/inf.
8462///
8463/// Pure host-side arithmetic over the pooling shape parameters; computes no
8464/// tensor, builds no graph. `out_dim` matches the formula in
8465/// [`Tensor::avg_pool2d`]'s doc comment: `(dim + 2*pad - kernel) / stride + 1`.
8466fn first_zero_tap_output_index(
8467    dim: usize,
8468    kernel: usize,
8469    stride: usize,
8470    pad: usize,
8471) -> Option<usize> {
8472    let out_dim = (dim + 2 * pad).saturating_sub(kernel) / stride + 1;
8473    (0..out_dim).find(|&o| {
8474        let start = o as isize * stride as isize - pad as isize;
8475        let end = start + kernel as isize;
8476        let valid_start = start.max(0);
8477        let valid_end = end.min(dim as isize);
8478        valid_end <= valid_start
8479    })
8480}
8481
8482// ---- safetensors integration -----------------------------------------------
8483
8484impl Tensor {
8485    /// Build a `Tensor` from raw little-endian bytes as they appear
8486    /// in a safetensors file, plus a dtype and shape. Row-major layout
8487    /// is assumed. The byte count must match `shape.elem_count() *
8488    /// dtype_bytes`.
8489    ///
8490    /// This is the low-level loader. Prefer [`Self::from_safetensors_view`]
8491    /// if you already have a `safetensors::TensorView` in hand.
8492    ///
8493    /// Supported dtypes today: `F32`, `F64`, `BF16`, `F16`, `U32`.
8494    /// Integer types other than `U32` are rejected to keep the
8495    /// surface small; add them when a real model needs them.
8496    pub fn from_safetensors_bytes(
8497        bytes: &[u8],
8498        dtype: safetensors::Dtype,
8499        shape: &[usize],
8500        device: &Device,
8501    ) -> crate::Result<Self> {
8502        use safetensors::Dtype;
8503        let shape_obj = Shape::from_dims(shape);
8504        let elem_count = shape_obj.elem_count();
8505
8506        let check_len = |expected: usize| -> crate::Result<()> {
8507            if bytes.len() != expected {
8508                crate::bail!(
8509                    "from_safetensors_bytes: expected {expected} bytes for dtype {dtype:?} \
8510                     and shape {shape:?}, got {}",
8511                    bytes.len(),
8512                );
8513            }
8514            Ok(())
8515        };
8516
8517        match dtype {
8518            Dtype::F32 => {
8519                check_len(elem_count * 4)?;
8520                let mut data = Vec::with_capacity(elem_count);
8521                for chunk in bytes.as_chunks::<4>().0.iter() {
8522                    data.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8523                }
8524                Self::from_f32(data, shape_obj, device)
8525            }
8526            Dtype::F64 => {
8527                check_len(elem_count * 8)?;
8528                let mut data = Vec::with_capacity(elem_count);
8529                for chunk in bytes.as_chunks::<8>().0.iter() {
8530                    let arr: [u8; 8] = *chunk;
8531                    data.push(f64::from_le_bytes(arr));
8532                }
8533                Self::from_f64(data, shape_obj, device)
8534            }
8535            Dtype::BF16 => {
8536                check_len(elem_count * 2)?;
8537                let mut data = Vec::with_capacity(elem_count);
8538                for chunk in bytes.as_chunks::<2>().0.iter() {
8539                    let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8540                    data.push(half::bf16::from_bits(raw));
8541                }
8542                Self::from_bf16(data, shape_obj, device)
8543            }
8544            Dtype::F16 => {
8545                check_len(elem_count * 2)?;
8546                let mut data = Vec::with_capacity(elem_count);
8547                for chunk in bytes.as_chunks::<2>().0.iter() {
8548                    let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8549                    data.push(half::f16::from_bits(raw));
8550                }
8551                Self::from_f16(data, shape_obj, device)
8552            }
8553            Dtype::U32 => {
8554                check_len(elem_count * 4)?;
8555                let mut data = Vec::with_capacity(elem_count);
8556                for chunk in bytes.as_chunks::<4>().0.iter() {
8557                    data.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8558                }
8559                Self::from_u32(data, shape_obj, device)
8560            }
8561            other => crate::bail!(
8562                "from_safetensors_bytes: unsupported dtype {other:?} — extend Tensor's \
8563                 safetensors loader to handle it",
8564            ),
8565        }
8566    }
8567
8568    /// Build a `Tensor` from a `safetensors::TensorView`. This is
8569    /// the most natural entry point when iterating over a
8570    /// [`fuel_formats::safetensors::MmapedSafetensors`] or similar.
8571    pub fn from_safetensors_view(
8572        view: &safetensors::tensor::TensorView<'_>,
8573        device: &Device,
8574    ) -> crate::Result<Self> {
8575        Self::from_safetensors_bytes(view.data(), view.dtype(), view.shape(), device)
8576    }
8577}
8578
8579/// A LayerNorm's learned `(gain, bias)`, both length `[dim]`. Wrapped in
8580/// `Option` at sites where the norm is conditional — present only on layer 0
8581/// (RWKV `pre_ln`), or only when a config flag is set (Persimmon QK-LN).
8582pub type LayerNormPair = (Arc<[f32]>, Arc<[f32]>);
8583
8584/// A convolution's `(weight, bias)`: the flattened `[out, in, kh, kw]` kernel
8585/// and its `[out]` bias. Distinct from [`LayerNormPair`] despite the identical
8586/// shape — the two are not interchangeable and naming them apart is the point.
8587pub type ConvWeightBias = (Arc<[f32]>, Arc<[f32]>);
8588
8589/// Weight tensor storage that preserves source precision.
8590///
8591/// Projection weights (Q/K/V/O for attention, gate/up/down for FFN,
8592/// and the output `lm_head` matrix) stay in whatever dtype the
8593/// source checkpoint used — f32 when that's how it was saved, bf16
8594/// for modern HF checkpoints that ship bf16 to halve weight memory.
8595/// Activations are usually f32, but LlamaModel's cached decode path
8596/// (Phase D increment A, "BF16-throughout decode") threads the KV
8597/// cache's dtype through the whole activation stream — when that's
8598/// BF16, weights must ALSO be BF16 (`matmul`'s dtype gate only allows
8599/// same-dtype homogeneous or `(lhs=F32, rhs=BF16)`; a BF16-activation ×
8600/// F32-weight matmul is rejected, the opposite direction from the
8601/// classic f32-activation-over-bf16-weight quantized-serving case).
8602/// F32 activations still route the mixed `(A:F32, B:BF16) → F32`
8603/// precision via `VulkanBackend::matmul` unchanged.
8604///
8605/// Norm gains and biases are NOT covered by this enum — they're
8606/// small and precision-sensitive, so they stay `Arc<[f32]>`.
8607///
8608/// Cloning is cheap (Arc bump) for both variants. Use
8609/// [`WeightStorage::const_like`] to emit a [`Tensor`] `Const`
8610/// node with the right dtype.
8611#[derive(Debug, Clone)]
8612pub enum WeightStorage {
8613    F32(Arc<[f32]>),
8614    BF16(Arc<[half::bf16]>),
8615    /// IEEE half precision, e.g. the linear weights of an F16 GGUF. The f32
8616    /// activation multiplies it through the mixed `[F32, F16, F32]` matmul.
8617    /// Tested on the CPU only.
8618    F16(Arc<[half::f16]>),
8619    /// GGML Q4_0 blocks (raw byte stream), laid out as `[out_features,
8620    /// in_features / 32]` blocks (18 bytes each, llama.cpp convention).
8621    /// Stored as `Arc<[u32]>` — the byte stream reinterpreted as u32
8622    /// words so subsequent forward passes just Arc-clone (cheap) rather
8623    /// than recopying the bytes. The graph sees this directly as a U32
8624    /// tensor; matmul dispatch goes through `Op::QMatMul`.
8625    ///
8626    /// `bytes_len` is the original byte count (u32_len * 4) so the
8627    /// const_like shape computation doesn't accidentally round up.
8628    Q4_0 {
8629        words: Arc<[u32]>,
8630        bytes_len: usize,
8631        in_features: usize,
8632        out_features: usize,
8633    },
8634    /// Any other GGML block format that `Op::QMatMul` has a kernel for (Q8_0, Q4_K, Q6_K, ...),
8635    /// kept in its on-disk block layout `[out_features, in_features / block]` so a GGUF tensor
8636    /// stays quantized from load to the matmul (ROADMAP row 124). Same representation as
8637    /// [`Self::Q4_0`] (the byte stream as `u32` words, a 1-D `U32` const in the graph, applied
8638    /// through `qmatmul`), plus the block format.
8639    Ggml {
8640        qtype: fuel_graph::QuantType,
8641        words: Arc<[u32]>,
8642        bytes_len: usize,
8643        in_features: usize,
8644        out_features: usize,
8645    },
8646    /// An AWQ 4-bit linear (HuggingFace `*-AWQ`, GEMM version) in the
8647    /// `AWQ_MATMUL` kernel layout, as graph-independent host buffers. The
8648    /// graph sees it through `NodeHandle::awq_matmul` operands
8649    /// built in `apply_linear`; it has no plain `const_like` form.
8650    Awq(Arc<crate::awq::AwqHostWeight>),
8651    /// Base weight wrapped with a trainable LoRA (Low-Rank Adaptation)
8652    /// update: effective weight `W_eff = base + (alpha / rank) · A · B`
8653    /// where `A` has shape `[in_features, rank]` and `B` has shape
8654    /// `[rank, out_features]` (both stored in the same layout
8655    /// convention as F32 weights — `[in, out]`).
8656    ///
8657    /// Used for PEFT-style inference with frozen base weights (which
8658    /// can be F32, BF16, or Q4_0) plus small trainable adapter matrices.
8659    /// The adapter is cheap to apply — for a 2560×2560 projection at
8660    /// rank 8 the LoRA path is ~0.5% of the base matmul cost.
8661    WithLoRA {
8662        base: Box<WeightStorage>,
8663        /// `[in_features, rank]` adapter A (HF's `lora_A` transposed).
8664        lora_a: Arc<[f32]>,
8665        /// `[rank, out_features]` adapter B (HF's `lora_B` transposed).
8666        lora_b: Arc<[f32]>,
8667        rank: usize,
8668        /// LoRA scaling factor; effective scale is `alpha / rank`.
8669        alpha: f32,
8670        in_features: usize,
8671        out_features: usize,
8672    },
8673}
8674
8675impl WeightStorage {
8676    /// Keep a GGUF weight tensor quantized (ROADMAP row 124): `bytes` is the tensor's block
8677    /// stream in GGUF's native `[out_features, in_features]` order. Returns `None` when the
8678    /// tensor must take the dequantize-to-f32 path instead: the format has no `QMatMul` kernel
8679    /// here (Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL, IQ4_XS and IQ3_S are admitted; `Q4_0` has its
8680    /// own variant; every other `GgmlDType` is declined BY NAME in the match below, so a new dtype is a
8681    /// compile error until someone decides), or
8682    /// `in_features` is not a whole number of blocks (32 for Q8_0, 256 for the K-quants), or the
8683    /// byte count is not `out_features * in_features / block * bytes_per_block`. A caller that
8684    /// gets `None` for a quantized dtype is taking the f32 path (4x the bytes for Q8_0, 5.8x to 9.3x for Q5_K down to Q3_K) and should say so.
8685    ///
8686    ///
8687    /// Every admitted type has a `QMatMul` arm on CPU and on Vulkan (ROADMAP row 119 wired Q3_K, Q5_K,
8688    /// IQ4_NL, IQ4_XS and IQ3_S there); the test `ggml_kept_types_are_wired` fails if a kept type is not
8689    /// listed by `fuel_vulkan_dispatch::vulkan_dispatch::qmatmul::qmatmul_wired`.
8690    pub fn from_ggml_bytes(
8691        dtype: fuel_ir::quantized::GgmlDType,
8692        bytes: &[u8],
8693        in_features: usize,
8694        out_features: usize,
8695    ) -> Option<Self> {
8696        use fuel_ir::quantized::GgmlDType;
8697        let qtype = match dtype {
8698            GgmlDType::Q8_0 => fuel_graph::QuantType::Q8_0,
8699            GgmlDType::Q4K => fuel_graph::QuantType::Q4_K_M,
8700            GgmlDType::Q6K => fuel_graph::QuantType::Q6K,
8701            GgmlDType::Q3K => fuel_graph::QuantType::Q3K,
8702            GgmlDType::Q5K => fuel_graph::QuantType::Q5K,
8703            GgmlDType::Iq4Nl => fuel_graph::QuantType::Iq4Nl,
8704            GgmlDType::Iq4Xs => fuel_graph::QuantType::Iq4Xs,
8705            GgmlDType::Iq3S => fuel_graph::QuantType::Iq3S,
8706            // Declined, each by name: no `QMatMul` kernel on any backend, or (Q4_0) a variant of its own.
8707            // No wildcard: a new `GgmlDType` must be admitted or declined here before this compiles.
8708            GgmlDType::F32
8709            | GgmlDType::F16
8710            | GgmlDType::BF16
8711            | GgmlDType::Q4_0
8712            | GgmlDType::Q4_1
8713            | GgmlDType::Q5_0
8714            | GgmlDType::Q5_1
8715            | GgmlDType::Q8_1
8716            | GgmlDType::Q2K
8717            | GgmlDType::Q8K
8718            | GgmlDType::Iq2Xxs
8719            | GgmlDType::Iq2Xs
8720            | GgmlDType::Iq3Xxs
8721            | GgmlDType::Iq1S
8722            | GgmlDType::Iq2S
8723            | GgmlDType::Iq1M
8724            | GgmlDType::Tq1_0
8725            | GgmlDType::Tq2_0
8726            | GgmlDType::Mxfp4
8727            | GgmlDType::Nvfp4 => return None,
8728        };
8729        let block = qtype.elements_per_block();
8730        if in_features == 0 || !in_features.is_multiple_of(block) {
8731            return None;
8732        }
8733        if bytes.len() != out_features * (in_features / block) * qtype.bytes_per_block() {
8734            return None;
8735        }
8736        // The graph const is U32 words; pad the tail to a whole word.
8737        let mut padded = bytes.to_vec();
8738        padded.resize(bytes.len().div_ceil(4) * 4, 0);
8739        let words: Vec<u32> = padded
8740            .as_chunks::<4>()
8741            .0
8742            .iter()
8743            .map(|c| u32::from_le_bytes(*c))
8744            .collect();
8745        Some(Self::Ggml {
8746            qtype,
8747            words: Arc::from(words),
8748            bytes_len: bytes.len(),
8749            in_features,
8750            out_features,
8751        })
8752    }
8753
8754    /// Bytes this weight holds in host memory (the adapter of a `WithLoRA` included). The
8755    /// instrument for "did this tensor stay quantized": a Q4_K weight is `n*k/256*144` bytes,
8756    /// the same tensor dequantized to `F32` is `n*k*4`.
8757    pub fn resident_bytes(&self) -> usize {
8758        match self {
8759            Self::F32(a) => a.len() * std::mem::size_of::<f32>(),
8760            Self::BF16(a) => a.len() * std::mem::size_of::<half::bf16>(),
8761            Self::F16(a) => a.len() * std::mem::size_of::<half::f16>(),
8762            Self::Q4_0 { bytes_len, .. } | Self::Ggml { bytes_len, .. } => *bytes_len,
8763            Self::Awq(w) => {
8764                w.weight.len() * std::mem::size_of::<u32>()
8765                    + w.zeros.len() * std::mem::size_of::<u32>()
8766                    + w.scales.len() * std::mem::size_of::<half::f16>()
8767            }
8768            Self::WithLoRA {
8769                base,
8770                lora_a,
8771                lora_b,
8772                ..
8773            } => base.resident_bytes() + (lora_a.len() + lora_b.len()) * std::mem::size_of::<f32>(),
8774        }
8775    }
8776
8777    pub fn elem_count(&self) -> usize {
8778        match self {
8779            Self::F32(a) => a.len(),
8780            Self::BF16(a) => a.len(),
8781            Self::F16(a) => a.len(),
8782            // Logical element count for a Q4_0 weight matrix is n*k.
8783            Self::Q4_0 {
8784                in_features,
8785                out_features,
8786                ..
8787            }
8788            | Self::Ggml {
8789                in_features,
8790                out_features,
8791                ..
8792            } => *in_features * *out_features,
8793            Self::Awq(w) => w.ic * w.oc,
8794            Self::WithLoRA {
8795                in_features,
8796                out_features,
8797                ..
8798            } => *in_features * *out_features,
8799        }
8800    }
8801
8802    pub fn dtype(&self) -> fuel_ir::DType {
8803        match self {
8804            Self::F32(_) => fuel_ir::DType::F32,
8805            Self::BF16(_) => fuel_ir::DType::BF16,
8806            Self::F16(_) => fuel_ir::DType::F16,
8807            // Q4_0 surfaces as U32 at the graph level (raw bytes
8808            // reinterpreted). Callers that care about the "actual"
8809            // quantization type should match on the variant directly.
8810            Self::Q4_0 { .. } | Self::Ggml { .. } => fuel_ir::DType::U32,
8811            // AWQ surfaces as U32 for the same reason (packed nibbles).
8812            Self::Awq(_) => fuel_ir::DType::U32,
8813            // WithLoRA exposes the base's dtype (the LoRA adapter is
8814            // always F32 but activations are typed by the base weight).
8815            Self::WithLoRA { base, .. } => base.dtype(),
8816        }
8817    }
8818
8819    /// Emit a `Const` node on `anchor`'s graph matching this
8820    /// storage's dtype. Used everywhere the forward pass wraps a
8821    /// weight into a `Tensor`.
8822    ///
8823    /// For `Q4_0`, the emitted tensor is a 1-D `U32` const of length
8824    /// `bytes.len() / 4` holding the raw block byte stream. Callers
8825    /// must pair this with `Tensor::qmatmul` rather than `matmul`.
8826    ///
8827    /// Returns Err for `WithLoRA` — the base + LoRA update can only be
8828    /// applied via `apply_linear` so the right graph structure is built.
8829    pub fn const_like(
8830        &self,
8831        anchor: &Tensor,
8832        shape: Shape,
8833    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8834        match self {
8835            Self::F32(a) => anchor.const_f32_like(a.clone(), shape),
8836            Self::BF16(a) => anchor.const_bf16_like(a.clone(), shape),
8837            Self::F16(a) => anchor.const_f16_like(a.clone(), shape),
8838            Self::Q4_0 { words, .. } | Self::Ggml { words, .. } => {
8839                let _ = shape; // shape arg unused — Q4_0 const is 1-D U32
8840                // Arc-clone the precomputed u32 view; no byte copy.
8841                anchor.const_u32_like(Arc::clone(words), Shape::from_dims(&[words.len()]))
8842            }
8843            Self::Awq(_) => Err(fuel_ir::Error::Msg(
8844                "WeightStorage::Awq::const_like is not supported — an AWQ weight is three operands \
8845                 (weight, zeros, scales), applied via apply_linear."
8846                    .into(),
8847            )
8848            .bt()),
8849            Self::WithLoRA { .. } => Err(fuel_ir::Error::Msg(
8850                "WeightStorage::WithLoRA::const_like is not supported \
8851                 — the base + LoRA update must be applied via \
8852                 apply_linear to produce the right graph structure."
8853                    .into(),
8854            )
8855            .bt()),
8856        }
8857    }
8858
8859    /// Produce `X @ W + bias` for this weight storage. Bias is a
8860    /// length-`out_features` Arc<[f32]> materialized fresh on the
8861    /// receiver's graph and broadcast across the leading dims of
8862    /// the output.
8863    ///
8864    /// Equivalent to the per-port `apply_linear_with_bias` helpers
8865    /// that several ports inlined — promoted here so call sites
8866    /// stop drifting.
8867    pub fn apply_linear_with_bias(
8868        &self,
8869        x: &Tensor,
8870        in_features: usize,
8871        out_features: usize,
8872        bias: std::sync::Arc<[f32]>,
8873    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8874        if bias.len() != out_features {
8875            // Was a `debug_assert_eq!` — i.e. compiled OUT of release builds,
8876            // so a release binary silently built a broadcast against a
8877            // wrong-length bias. A length mismatch is a checkpoint condition;
8878            // it errors in every profile now.
8879            return Err(fuel_ir::Error::Msg(format!(
8880                "apply_linear_with_bias: bias len ({}) != out_features ({out_features})",
8881                bias.len(),
8882            ))
8883            .bt());
8884        }
8885        let projected = self.apply_linear(x, in_features, out_features)?;
8886        let bias_t = projected.const_f32_like(bias, Shape::from_dims(&[out_features]))?;
8887        projected.broadcast_add(&bias_t)
8888    }
8889
8890    /// Produce `X @ W` (with optional bias) for this weight storage.
8891    /// Dispatches to `matmul` for F32/BF16 weights and to `qmatmul`
8892    /// for Q4_0. `x`'s dtype must be compatible with this weight's
8893    /// dtype per `matmul`'s gate: same-dtype homogeneous (e.g. BF16
8894    /// activations × BF16 weights — LlamaModel's BF16-throughout
8895    /// decode path, Phase D increment A) or `(x=F32, weight=BF16)`
8896    /// (f32-activation quantized-weight serving). `(x=BF16,
8897    /// weight=F32)` is NOT supported — cast the weight or the
8898    /// activation to match before calling.
8899    /// # Errors
8900    ///
8901    /// Returns a typed error rather than panicking on a dimension or dtype
8902    /// mismatch. This used to `.unwrap()` the inner `matmul`/`qmatmul` and
8903    /// `assert_eq!` the stored-vs-requested dimensions, which made a
8904    /// **production** path panic — a mismatched checkpoint (a GGUF whose
8905    /// stored shape disagrees with the model config) is a data condition, not
8906    /// a programming invariant, so it must surface as `Err`.
8907    pub fn apply_linear(
8908        &self,
8909        x: &Tensor,
8910        in_features: usize,
8911        out_features: usize,
8912    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8913        // Build-time contract check, shared by every arm: a "linear with
8914        // `in_features`" requires x's trailing dim to BE `in_features`.
8915        // Checked here rather than at the ~620 call sites, and phrased so the
8916        // message names the projection instead of surfacing a bare matmul
8917        // shape error two layers down.
8918        let x_dims = x.shape().dims().to_vec();
8919        match x_dims.last() {
8920            Some(&k) if k == in_features => {}
8921            _ => {
8922                return Err(fuel_ir::Error::Msg(format!(
8923                    "apply_linear({in_features} -> {out_features}): input shape {x_dims:?} \
8924                     must have trailing dim {in_features}",
8925                ))
8926                .bt());
8927            }
8928        }
8929        match self {
8930            Self::F32(_) | Self::BF16(_) | Self::F16(_) => {
8931                let w = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8932                x.matmul(&w)
8933            }
8934            Self::Q4_0 {
8935                in_features: expected_in,
8936                out_features: expected_out,
8937                ..
8938            } => {
8939                if *expected_in != in_features || *expected_out != out_features {
8940                    return Err(fuel_ir::Error::Msg(format!(
8941                        "WeightStorage::Q4_0 shape mismatch: stored \
8942                         [{expected_in}, {expected_out}], requested \
8943                         [{in_features}, {out_features}]",
8944                    ))
8945                    .bt());
8946                }
8947                let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8948                x.qmatmul(
8949                    &w_bytes,
8950                    fuel_graph::QuantType::Q4_0,
8951                    in_features,
8952                    out_features,
8953                )
8954            }
8955            Self::Ggml {
8956                qtype,
8957                in_features: expected_in,
8958                out_features: expected_out,
8959                ..
8960            } => {
8961                if *expected_in != in_features || *expected_out != out_features {
8962                    return Err(fuel_ir::Error::Msg(format!(
8963                        "WeightStorage::Ggml({qtype:?}) shape mismatch: stored                          [{expected_in}, {expected_out}], requested                          [{in_features}, {out_features}]",
8964                    ))
8965                    .bt());
8966                }
8967                let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8968                x.qmatmul(&w_bytes, *qtype, in_features, out_features)
8969            }
8970            Self::Awq(w) => {
8971                if w.ic != in_features || w.oc != out_features {
8972                    return Err(fuel_ir::Error::Msg(format!(
8973                        "WeightStorage::Awq shape mismatch: stored [{}, {}], requested [{in_features}, {out_features}]",
8974                        w.ic, w.oc,
8975                    ))
8976                    .bt());
8977                }
8978                // 8 is AutoAWQ's default launch tuning; the decompose path
8979                // ignores it.
8980                w.matmul(x, 8)
8981            }
8982            Self::WithLoRA {
8983                base,
8984                lora_a,
8985                lora_b,
8986                rank,
8987                alpha,
8988                in_features: expected_in,
8989                out_features: expected_out,
8990            } => {
8991                if *expected_in != in_features || *expected_out != out_features {
8992                    return Err(fuel_ir::Error::Msg(format!(
8993                        "WeightStorage::WithLoRA shape mismatch: stored \
8994                         [{expected_in}, {expected_out}], requested \
8995                         [{in_features}, {out_features}]",
8996                    ))
8997                    .bt());
8998                }
8999                // Base forward (F32, BF16, or Q4_0).
9000                let base_out = base.apply_linear(x, in_features, out_features)?;
9001                // Low-rank update: y += (alpha/rank) · x @ A @ B.
9002                let a_t =
9003                    x.const_f32_like(Arc::clone(lora_a), Shape::from_dims(&[in_features, *rank]))?;
9004                let b_t =
9005                    x.const_f32_like(Arc::clone(lora_b), Shape::from_dims(&[*rank, out_features]))?;
9006                let scale = *alpha as f64 / *rank as f64;
9007                // x: [*, in] → @A [*, rank] → @B [*, out] → scale → add base.
9008                let lora_path = Tensor {
9009                    inner: x.matmul(&a_t)?.matmul(&b_t)?.inner.mul_scalar(scale),
9010                };
9011                base_out.add(&lora_path)
9012            }
9013        }
9014    }
9015
9016    /// Data-determined-M variant of [`Self::apply_linear`]: computes only
9017    /// `row_count` rows of the capacity-buffer projection `x @ W`, the rest
9018    /// left zeroed — the per-expert sparse-MoE FFN path. `x` is a
9019    /// `[capacity, in_features]` buffer whose first `row_count` rows are the
9020    /// routed tokens; the returned `[capacity, out_features]` buffer's tail
9021    /// (rows `row_count..capacity`) stays exactly zero (see
9022    /// [`Tensor::matmul_dyn_m`]).
9023    ///
9024    /// F32-only (mirrors `matmul_dyn_m`); other weight encodings surface a
9025    /// typed build-time error. No bias is applied — a bias would fill the
9026    /// un-computed tail, which the sparse-MoE caller relies on being zero
9027    /// for a correct `index_add` scatter-back.
9028    pub fn apply_linear_dyn_m(
9029        &self,
9030        x: &Tensor,
9031        in_features: usize,
9032        out_features: usize,
9033        row_count: fuel_ir::DynScalar,
9034    ) -> std::result::Result<Tensor, fuel_ir::Error> {
9035        match self {
9036            Self::F32(_) => {
9037                // const_like only errors on WithLoRA; the F32 arm is infallible.
9038                let w = self
9039                    .const_like(x, Shape::from_dims(&[in_features, out_features]))
9040                    .expect("apply_linear_dyn_m F32 arm: const_like cannot fail for F32");
9041                x.matmul_dyn_m(&w, row_count)
9042            }
9043            other => Err(fuel_ir::Error::Msg(format!(
9044                "apply_linear_dyn_m: sparse-MoE dispatch is F32-only today, got {:?} \
9045                 weight (cast the expert weights to F32)",
9046                other.dtype(),
9047            ))
9048            .bt()),
9049        }
9050    }
9051
9052    /// Wrap this weight storage with a LoRA adapter. Asserts that the
9053    /// adapter shapes match `in_features`/`out_features`. Panics if the
9054    /// base is already a `WithLoRA` (nested adapters aren't supported;
9055    /// merge them explicitly if needed).
9056    pub fn with_lora(
9057        self,
9058        lora_a: Arc<[f32]>,
9059        lora_b: Arc<[f32]>,
9060        rank: usize,
9061        alpha: f32,
9062        in_features: usize,
9063        out_features: usize,
9064    ) -> Self {
9065        assert_eq!(
9066            lora_a.len(),
9067            in_features * rank,
9068            "lora_a length {} does not match in_features ({in_features}) × rank ({rank}) = {}",
9069            lora_a.len(),
9070            in_features * rank,
9071        );
9072        assert_eq!(
9073            lora_b.len(),
9074            rank * out_features,
9075            "lora_b length {} does not match rank ({rank}) × out_features ({out_features}) = {}",
9076            lora_b.len(),
9077            rank * out_features,
9078        );
9079        assert!(
9080            !matches!(self, Self::WithLoRA { .. }),
9081            "with_lora: base is already WithLoRA (nested adapters unsupported)",
9082        );
9083        Self::WithLoRA {
9084            base: Box::new(self),
9085            lora_a,
9086            lora_b,
9087            rank,
9088            alpha,
9089            in_features,
9090            out_features,
9091        }
9092    }
9093}
9094
9095// Auto-conversions so code that was storing `Arc<[f32]>` keeps
9096// compiling through the refactor — the LayerWeights field type
9097// widened to WeightStorage but ergonomics don't regress.
9098impl From<Arc<[f32]>> for WeightStorage {
9099    fn from(a: Arc<[f32]>) -> Self {
9100        Self::F32(a)
9101    }
9102}
9103impl From<Vec<f32>> for WeightStorage {
9104    fn from(v: Vec<f32>) -> Self {
9105        Self::F32(Arc::from(v))
9106    }
9107}
9108impl From<Arc<[half::bf16]>> for WeightStorage {
9109    fn from(a: Arc<[half::bf16]>) -> Self {
9110        Self::BF16(a)
9111    }
9112}
9113impl From<Vec<half::bf16>> for WeightStorage {
9114    fn from(v: Vec<half::bf16>) -> Self {
9115        Self::BF16(Arc::from(v))
9116    }
9117}
9118
9119/// Per-layer weights of a LLaMA transformer block. All tensors are
9120/// stored as `Arc<[f32]>` so they can be loaded once and shared across
9121/// every forward pass with zero copy — each call to
9122/// `LlamaModel::forward` clones the `Arc` (a refcount bump) when it
9123/// builds fresh const nodes for this layer.
9124///
9125/// LLaMA proper has no biases anywhere in the attention block, so the
9126/// `*_bias` fields are `None` for LLaMA family models. Qwen2 and a few
9127/// related architectures do add biases on Q/K/V (but not on the output
9128/// projection), so the loader stores them here when the safetensors
9129/// file contains them.
9130#[derive(Debug, Clone)]
9131pub struct LayerWeights {
9132    /// `[dim, dim]` query projection. Supports bf16 or f32.
9133    pub attn_q: WeightStorage,
9134    /// `[dim]` query projection bias (Qwen2-style; LLaMA has none).
9135    pub attn_q_bias: Option<Arc<[f32]>>,
9136    /// `[dim, dim]` key projection.
9137    pub attn_k: WeightStorage,
9138    /// `[kv_dim]` key projection bias.
9139    pub attn_k_bias: Option<Arc<[f32]>>,
9140    /// `[dim, dim]` value projection.
9141    pub attn_v: WeightStorage,
9142    /// `[kv_dim]` value projection bias.
9143    pub attn_v_bias: Option<Arc<[f32]>>,
9144    /// `[dim, dim]` output projection.
9145    pub attn_o: WeightStorage,
9146    /// `[dim, ffn_dim]` gate projection for SwiGLU.
9147    pub ffn_gate: WeightStorage,
9148    /// `[dim, ffn_dim]` up projection for SwiGLU.
9149    pub ffn_up: WeightStorage,
9150    /// `[ffn_dim, dim]` down projection for SwiGLU.
9151    pub ffn_down: WeightStorage,
9152    /// `[dim]` RmsNorm gain for the pre-attention norm. Stays f32
9153    /// — norm gains are small and precision-sensitive.
9154    pub attn_norm_gain: Arc<[f32]>,
9155    /// `[dim]` RmsNorm gain for the pre-FFN norm.
9156    pub ffn_norm_gain: Arc<[f32]>,
9157}
9158
9159pub fn invalidate_decode_pair_if_stale<C>(
9160    session: &mut Option<crate::inference_context::DecodeSession>,
9161    captured: &mut Option<C>,
9162    ctx: &mut InferenceContext,
9163    seq: usize,
9164    max_seq_len: Option<usize>,
9165    cache_dtype: DType,
9166    n_layers: usize,
9167    shape_key: u64,
9168    kv: &dyn crate::inference_context::KvRebindSource,
9169    drop_session: impl FnOnce(
9170        &mut Option<crate::inference_context::DecodeSession>,
9171        &mut InferenceContext,
9172    ),
9173) -> SessionDisposition {
9174    refresh_decode_session(
9175        session,
9176        ctx,
9177        seq,
9178        max_seq_len,
9179        cache_dtype,
9180        n_layers,
9181        shape_key,
9182        kv,
9183        // Reader before owner — see the doc comment above. This fires for a
9184        // re-bind as well as a drop: a capture records FIXED device addresses
9185        // drawn from `base_cache`, and `rebind_kv` replaces some of them.
9186        || *captured = None,
9187        drop_session,
9188    )
9189}
9190
9191/// What [`refresh_decode_session`] did to the held plan.
9192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9193pub enum SessionDisposition {
9194    /// There was no held plan; nothing to do.
9195    Absent,
9196    /// The plan is valid for this step and was left alone.
9197    Kept,
9198    /// The KV allocation changed and the plan was re-bound onto it (GAP-028).
9199    /// Any reader of the plan's device addresses has been retired.
9200    Rebound,
9201    /// The plan was retired. `Some(refusal)` means a re-bind was attempted and
9202    /// declined — carried so a caller (or a test) can distinguish "refused for
9203    /// the right reason" from "refused because nothing was tried".
9204    Dropped(Option<crate::inference_context::RebindRefusal>),
9205}
9206
9207/// **The single decision point for what happens to a held decode plan at the
9208/// top of a decode step.** Every model routes through here, so they cannot
9209/// drift on what "stale" means — the reason this was a shared free function
9210/// before GAP-028, and more so now that the answer has three outcomes.
9211///
9212/// Order of business, and why it is this order:
9213///
9214/// 1. Ask [`crate::inference_context::DecodeSession::validity_for`] — ONE comparison list, so "is it
9215///    valid" and "is only the allocation different" cannot disagree.
9216/// 2. On anything but `Valid`, retire readers FIRST via `on_invalidate`. A
9217///    `CapturedDecodeSession` replays a recorded CUDA graph over FIXED device
9218///    addresses drawn from the session's `base_cache`; both a drop and a
9219///    re-bind make some of those addresses stale, and a replay against stale
9220///    addresses is silently wrong logits at full speed. Retiring before
9221///    touching the owner means no replay can observe a half-updated plan.
9222///    Note this fires *before* the re-bind is attempted, not after it
9223///    succeeds: a capture is worthless either way, and clearing it early keeps
9224///    the ordering true without depending on the outcome.
9225/// 3. Try the guarded re-bind. It may refuse; a refusal is not an error.
9226/// 4. Otherwise drop, so the caller's first-decode-token arm rebuilds.
9227///
9228/// Generic in nothing — the capture rides in the `on_invalidate` closure,
9229/// which is what lets this compile (and therefore be CPU-tested) without the
9230/// `cuda` feature.
9231pub fn refresh_decode_session(
9232    session: &mut Option<crate::inference_context::DecodeSession>,
9233    ctx: &mut InferenceContext,
9234    seq: usize,
9235    max_seq_len: Option<usize>,
9236    cache_dtype: DType,
9237    n_layers: usize,
9238    shape_key: u64,
9239    kv: &dyn crate::inference_context::KvRebindSource,
9240    on_invalidate: impl FnOnce(),
9241    drop_session: impl FnOnce(
9242        &mut Option<crate::inference_context::DecodeSession>,
9243        &mut InferenceContext,
9244    ),
9245) -> SessionDisposition {
9246    use crate::inference_context::PlanValidity;
9247
9248    let verdict = match (session.as_ref(), max_seq_len) {
9249        (None, _) => return SessionDisposition::Absent,
9250        (Some(s), Some(msl)) => {
9251            s.validity_for(seq, msl, n_layers, cache_dtype, shape_key, kv.alloc_id())
9252        }
9253        // A cache with no pre-allocated capacity cannot back a held plan at
9254        // all (the graph bakes `max_seq_len` into its KV Const shapes).
9255        (Some(_), None) => PlanValidity::Stale,
9256    };
9257    if verdict == PlanValidity::Valid {
9258        return SessionDisposition::Kept;
9259    }
9260
9261    on_invalidate();
9262
9263    let refusal = if verdict == PlanValidity::AllocationChanged {
9264        match session.as_mut().map(|s| s.rebind_kv(kv)) {
9265            Some(Ok(())) => return SessionDisposition::Rebound,
9266            Some(Err(r)) => Some(r),
9267            // Unreachable: `verdict` was computed from a `Some` session and
9268            // nothing above takes it. Handled rather than `expect`ed because
9269            // this is a production path.
9270            None => None,
9271        }
9272    } else {
9273        None
9274    };
9275
9276    drop_session(session, ctx);
9277    SessionDisposition::Dropped(refusal)
9278}
9279
9280pub fn build_decode_causal_mask(cached_len: usize, seq: usize, max_seq_len: usize) -> Vec<f32> {
9281    let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9282    for q_idx in 0..seq {
9283        let abs_q = cached_len + q_idx;
9284        for k_idx in (abs_q + 1)..max_seq_len {
9285            mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9286        }
9287    }
9288    mask_data
9289}
9290
9291/// Sliding-window sibling of [`build_decode_causal_mask`] — the decode-time
9292/// mask for a layer that attends only to the most recent `window` positions.
9293///
9294/// # Why this exists (GAP-029 increment 3)
9295///
9296/// The decode path has always built **one** mask per model, because `LlamaModel`
9297/// and `PhiModel` — the only two carriers — have no per-layer mask variation
9298/// (measured: **zero** `sliding_window` hits in this file, against a positive
9299/// control of hits in five sibling model files). **Four of the six families
9300/// GAP-029 increment 3 ports do vary per layer**, three of them via a sliding
9301/// window: `Qwen2` (`lazy_qwen2.rs:249-251`), `Qwen3` (`lazy_qwen3.rs:172`) and
9302/// `Qwen3Moe` (`lazy_qwen3_moe.rs:192`) all select per layer on
9303/// `use_sliding_window && layer_idx < max_window_layers`.
9304///
9305/// # The predicate, and why it is stated against the prefill path
9306///
9307/// The shipped **prefill** mask for these families is `j > i || j + window <= i`
9308/// over absolute positions (`lazy_qwen2.rs:271`). Decode must agree with it
9309/// position-for-position, or a model silently changes behaviour at the
9310/// prefill→decode boundary. Here the query's absolute position is
9311/// `cached_len + q_idx` and the key's is `k_idx`, giving the same two clauses:
9312/// causal (`k_idx > abs_q`) and window (`k_idx + window <= abs_q`).
9313///
9314/// `window >= max_seq_len` makes the window clause unsatisfiable, so the result
9315/// is exactly [`build_decode_causal_mask`] — the property that lets a family
9316/// with the window disabled share the dense path rather than a near-copy of it.
9317///
9318/// # Status: LIVE. `#[allow(dead_code)]` removed 2026-08-13 — this has a caller.
9319///
9320/// It landed ahead of its consumer with its correctness established
9321/// independently (see the born-red record in `decode_mask_tests`), under an
9322/// architect-owned checkpoint: *land family 1 or the function is deleted*.
9323/// GAP-029 increment 3 landed `Qwen2Model`'s decode path, and
9324/// [`crate::persistent_decode::build_decode_mask_variants`] calls this for every
9325/// windowed mask variant — so the attribute is gone rather than renewed.
9326///
9327/// It is now on the live decode path of the three windowed families as they
9328/// arrive (`Qwen2Model` today; `Qwen3Model`, `Qwen3MoeModel` next), reached
9329/// through `MaskPlan::split_window`.
9330pub fn build_decode_causal_mask_windowed(
9331    cached_len: usize,
9332    seq: usize,
9333    max_seq_len: usize,
9334    window: usize,
9335) -> Vec<f32> {
9336    let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9337    for q_idx in 0..seq {
9338        let abs_q = cached_len + q_idx;
9339        for k_idx in 0..max_seq_len {
9340            // Causal: no future keys. Window: nothing older than `window` back.
9341            if k_idx > abs_q || k_idx + window <= abs_q {
9342                mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9343            }
9344        }
9345    }
9346    mask_data
9347}
9348
9349#[cfg(test)]
9350mod decode_mask_tests {
9351    use super::{build_decode_causal_mask, build_decode_causal_mask_windowed};
9352
9353    /// Render a mask row as `1` for attend / `0` for masked, so a failure
9354    /// prints the shape of the disagreement rather than a wall of `-inf`.
9355    fn attendable(row: &[f32]) -> Vec<u8> {
9356        row.iter().map(|&v| u8::from(v == 0.0)).collect()
9357    }
9358
9359    /// **The discriminating test.** Hand-computed ground truth, NOT a
9360    /// re-derivation of the implementation's own formula: at `cached_len = 3`,
9361    /// `seq = 1`, `max_seq_len = 6`, `window = 2` the single query sits at
9362    /// absolute position 3 and may attend to positions `{2, 3}` — 3 itself
9363    /// (causal boundary) and 2 (one step back, inside a window of 2). Positions
9364    /// 0 and 1 fall out of the window; 4 and 5 are the unwritten future tail.
9365    #[test]
9366    fn windowed_mask_excludes_positions_older_than_the_window() {
9367        let m = build_decode_causal_mask_windowed(3, 1, 6, 2);
9368        assert_eq!(
9369            attendable(&m),
9370            vec![0, 0, 1, 1, 0, 0],
9371            "window=2 at absolute position 3 must attend to exactly {{2, 3}}",
9372        );
9373    }
9374
9375    /// Multi-row (prefill-shaped) ground truth, also by hand: `cached_len = 1`,
9376    /// `seq = 2`, `window = 2` puts the queries at absolute positions 1 and 2,
9377    /// attending to `{0, 1}` and `{1, 2}` respectively. Guards the `q_idx`
9378    /// → `abs_q` offset, which a `seq == 1` test cannot see at all.
9379    #[test]
9380    fn windowed_mask_offsets_each_row_by_cached_len() {
9381        let m = build_decode_causal_mask_windowed(1, 2, 5, 2);
9382        assert_eq!(
9383            attendable(&m[0..5]),
9384            vec![1, 1, 0, 0, 0],
9385            "row 0 = abs pos 1"
9386        );
9387        assert_eq!(
9388            attendable(&m[5..10]),
9389            vec![0, 1, 1, 0, 0],
9390            "row 1 = abs pos 2"
9391        );
9392    }
9393
9394    /// **Non-discrimination control, and it is what keeps the two tests above
9395    /// meaningful.** A window at least as wide as the capacity cannot mask
9396    /// anything the causal clause does not already mask, so the windowed builder
9397    /// must reproduce the dense one byte-for-byte. This passes under BOTH a
9398    /// correct implementation and one that ignores `window` entirely — so it
9399    /// certifies that the suite is not simply broken, and it must NOT be read as
9400    /// evidence that the window works. (Same role as the positive control that
9401    /// stayed `ok` in increment 2a's sabotage record.)
9402    #[test]
9403    fn window_wider_than_capacity_is_byte_identical_to_the_dense_mask() {
9404        for (cached_len, seq, max_seq_len) in [(0, 1, 8), (3, 1, 8), (0, 4, 8), (2, 3, 8)] {
9405            let dense = build_decode_causal_mask(cached_len, seq, max_seq_len);
9406            let windowed =
9407                build_decode_causal_mask_windowed(cached_len, seq, max_seq_len, max_seq_len);
9408            assert_eq!(
9409                dense, windowed,
9410                "window == max_seq_len must equal dense at \
9411                 (cached_len={cached_len}, seq={seq}, max_seq_len={max_seq_len})",
9412            );
9413        }
9414    }
9415
9416    /// Decode must agree with the **shipped prefill** mask position-for-position,
9417    /// or a windowed model changes behaviour at the prefill→decode boundary.
9418    /// This replays `lazy_qwen2.rs:265-277`'s predicate over a full prefill of
9419    /// length `n`, then asserts that decoding position `p` with `cached_len = p`
9420    /// reproduces prefill row `p`. The prefill mask is `[seq, seq]` and the
9421    /// decode mask `[1, max_seq_len]`, so only the first `n` keys are comparable
9422    /// — the tail beyond `n` is the unwritten capacity the prefill mask has no
9423    /// opinion about.
9424    #[test]
9425    fn decode_row_matches_the_prefill_mask_row_at_the_same_position() {
9426        let (n, window, max_seq_len) = (6_usize, 3_usize, 10_usize);
9427
9428        // Qwen2's prefill predicate, transcribed from `build_layer_mask`.
9429        let mut prefill = vec![0.0_f32; n * n];
9430        for i in 0..n {
9431            for j in 0..n {
9432                if j > i || j + window <= i {
9433                    prefill[i * n + j] = f32::NEG_INFINITY;
9434                }
9435            }
9436        }
9437
9438        for p in 0..n {
9439            let decode = build_decode_causal_mask_windowed(p, 1, max_seq_len, window);
9440            assert_eq!(
9441                attendable(&decode[0..n]),
9442                attendable(&prefill[p * n..(p + 1) * n]),
9443                "decode at cached_len={p} must match prefill row {p}",
9444            );
9445            assert!(
9446                decode[n..].iter().all(|&v| v == f32::NEG_INFINITY),
9447                "the unwritten tail beyond position {n} must stay masked",
9448            );
9449        }
9450    }
9451
9452    // =======================================================================
9453    // BORN-RED RECORD (2026-08-13, GAP-029 increment 3)
9454    //
9455    // These tests were run FIRST against a deliberately wrong body — the
9456    // "old fabrication in the new shape": `build_decode_causal_mask_windowed`
9457    // returning `build_decode_causal_mask(..)` and ignoring `window`, which is
9458    // precisely what a single-mask decode port computes today. That makes the
9459    // red state prove *windowing vs dense* rather than merely proving the tests
9460    // execute.
9461    //
9462    //   windowed_mask_excludes_positions_older_than_the_window   FAILED
9463    //       left [1, 1, 1, 1, 0, 0]  right [0, 0, 1, 1, 0, 0]
9464    //   windowed_mask_offsets_each_row_by_cached_len             FAILED
9465    //       left [1, 1, 1, 0, 0]     right [0, 1, 1, 0, 0]
9466    //   decode_row_matches_the_prefill_mask_row_at_the_same_position FAILED
9467    //       left [1, 1, 1, 1, 0, 0]  right [0, 1, 1, 1, 0, 0]
9468    //   window_wider_than_capacity_is_byte_identical_to_the_dense_mask  ok
9469    //   test result: FAILED. 1 passed; 3 failed
9470    //
9471    // The `ok` line is load-bearing in BOTH directions and is the reason the
9472    // control exists: it holds under the correct body AND under the dense
9473    // fabrication, so (a) the suite is demonstrably not simply broken, and
9474    // (b) it must never be cited as evidence that windowing works. Only the
9475    // three that moved carry that claim.
9476    //
9477    // After the flip: `4 passed; 0 failed`, on a run reporting a 53.44s
9478    // compile — i.e. a rebuilt binary, not a cached one. A passing run without
9479    // confirmed recompilation would have certified nothing.
9480    //
9481    // WHAT THIS DOES **NOT** ESTABLISH, stated because the next reader will be
9482    // wiring this into a decode path: these are tests of the MASK BYTES ONLY.
9483    // No decode has yet been run with a windowed mask, so "a single-mask decode
9484    // port is silently wrong for Qwen2/Qwen3/Qwen3Moe" remains an INFERENCE
9485    // from the mask's meaning — argued from the fact that one
9486    // `[1, 1, seq, max_seq_len]` Const cannot express two layer groups. The
9487    // logits-level born-red against Qwen2's live mixed config
9488    // (`use_sliding_window: true, max_window_layers: 1` over 2 layers,
9489    // `lazy_qwen2.rs:441-443`) is the measurement that would settle it, and it
9490    // is NOT in this change.
9491    // =======================================================================
9492}
9493
9494/// Build a [`fuel_dispatch::decode_flash::DecodeFlashSpec`] from a decode
9495/// attention region's tensor handles and offer the optimizer-owned CUDA
9496/// flash-decode arm on the shared graph.
9497///
9498/// This is the model-layer WIRING for [`fuel_dispatch::decode_flash::offer_decode_flash_arm`]: it supplies
9499/// the region's tensor handles + the live attended-prefix `k_len` (as
9500/// `Sym(attended_len_sym)`, resolved per-token via the `SymEnv`) — data the
9501/// model alone knows — while every strategic decision (the shape/dtype/config
9502/// gate, the capability gate, the CUDA pin, the `Op::Branch` construction)
9503/// stays in the dispatch layer. The region is always **causal** with no
9504/// window / softcap / ALiBi (the LlamaModel decode shape).
9505///
9506/// - `q` — the RoPE'd query (`[B, Hq, 1, D]` in decode), also the branch
9507///   diverge point;
9508/// - `k` / `v` — the post-`WriteSlice` capacity KV buffers (`[B, Hkv,
9509///   capacity, D]`);
9510/// - `decomposed_out` — the region's attention output (arm 0 / the oracle);
9511/// - `reconverge` — the sole consumer of `decomposed_out` (the merge).
9512///
9513/// Returns `Ok(None)` (graph untouched, byte-identical to today) whenever the
9514/// emitter's gate declines — f32/f64 dtype, `seq_q != 1` (prefill),
9515/// `head_dim > 128`, or a non-CUDA / kernel-absent topology. Never panics.
9516/// Translate a Fuel sliding-window width into the FA-v2 `window_size_*`
9517/// convention the CUDA flash path speaks.
9518///
9519/// Fuel's mask predicate is `j > i || j + window <= i`, i.e. query `i` attends
9520/// keys `j ∈ [i - window + 1, i]` — **`window - 1` positions LEFT and `0`
9521/// RIGHT**. FA-v2 reads `is_causal` as `window_size_right == 0 &&
9522/// window_size_left < 0`, and treats *both* bounds `>= 0` as opting into local
9523/// attention (`fuel-cuda-backend/src/flash_attn.rs::translate_window`).
9524///
9525/// `None` (a dense layer) stays `(None, None)` — plain causal, which is what
9526/// every non-windowed family wants and what the decode kernel implements.
9527///
9528/// The `w - 1` is saturating: a nonsensical `window == 0` yields `Some(0)`,
9529/// which the admissibility gate rejects along with every other window. It never
9530/// silently becomes "no window".
9531pub fn flash_window_bounds(window: Option<usize>) -> (Option<usize>, Option<usize>) {
9532    match window {
9533        None => (None, None),
9534        Some(w) => (Some(w.saturating_sub(1)), Some(0)),
9535    }
9536}
9537
9538// 11 independent graph handles (q/k/v/decomposed/reconverge node ids) plus the
9539// scalar rewrite parameters (scale, attended-len sym, window, softcap, backend
9540// capability) for one flash-decode-arm offer. Each is a distinct graph node or
9541// scalar, not a bundle-able struct. Exceeds even the raised (10) threshold.
9542pub fn offer_flash_decode_arm_for_region(
9543    graph: &fuel_graph::SharedGraph,
9544    q: fuel_graph::NodeId,
9545    k: fuel_graph::NodeId,
9546    v: fuel_graph::NodeId,
9547    decomposed_out: fuel_graph::NodeId,
9548    reconverge: fuel_graph::NodeId,
9549    softmax_scale: f32,
9550    attended_len_sym: fuel_ir::SymId,
9551    attn_window: Option<usize>,
9552    softcap: Option<f32>,
9553    cap: fuel_dispatch::decode_flash::FlashArmCapability,
9554) -> crate::Result<Option<fuel_graph::NodeId>> {
9555    use fuel_dispatch::decode_flash::{DecodeFlashSpec, offer_decode_flash_arm};
9556    let (window_size_left, window_size_right) = flash_window_bounds(attn_window);
9557    let spec = DecodeFlashSpec {
9558        q,
9559        k,
9560        v,
9561        alibi: None,
9562        softmax_scale,
9563        causal: true,
9564        // ⚠️ GAP-194: these three were hardcoded `None`. That is TRUE for
9565        // `LlamaModel` — no window, no softcap — and would be a LIE for a
9566        // windowed or softcapped family, whose arm would then attend the whole
9567        // prefix and skip the cap, silently. A guard must not encode a claim
9568        // that is false: the caller states them, and the admissibility gate
9569        // declines what `flash_decoding` cannot implement.
9570        window_size_left,
9571        window_size_right,
9572        softcap,
9573        k_len: fuel_ir::DynScalar::Sym(attended_len_sym),
9574        decomposed_out,
9575        reconverge,
9576    };
9577    let mut g = graph.write().map_err(|_| {
9578        fuel_ir::Error::Msg("graph lock poisoned during flash-arm offer".into()).bt()
9579    })?;
9580    offer_decode_flash_arm(&mut g, &spec, cap)
9581}
9582
9583pub fn apply_affine_rms_norm(x: &Tensor, gain: &Arc<[f32]>, dim: usize, eps: f64) -> Tensor {
9584    assert_eq!(
9585        gain.len(),
9586        dim,
9587        "apply_affine_rms_norm: gain length must equal dim"
9588    );
9589    let normalized = x.rms_norm_last_dim(eps).unwrap();
9590    // The gain is always stored f32 (norm gains are precision-sensitive —
9591    // see `LayerWeights::attn_norm_gain`'s doc) but must be materialized
9592    // in `x`'s dtype: under BF16-throughout decode (Phase D increment A)
9593    // `x` is BF16 and `broadcast_mul` asserts dtype equality, so an f32
9594    // gain would panic. No-op conversion for f32 activations.
9595    let gain_t = x
9596        .const_like_dtype(gain, Shape::from_dims(&[dim]), x.dtype())
9597        .expect("apply_affine_rms_norm: activation dtype must be F32 or BF16");
9598    normalized.broadcast_mul(&gain_t).unwrap()
9599}
9600
9601// ---- HuggingFace Hub and safetensors weight loading ----------------------
9602
9603/// Load a tensor by name from a `MmapedSafetensors` as a flat
9604/// `Vec<f32>`, converting from whatever dtype the file stores it in.
9605/// Handles `F32`, `F64`, `BF16`, and `F16` — the dtypes real LLaMA
9606/// weights use on disk. Returns an error for unsupported dtypes.
9607pub fn load_tensor_as_f32(
9608    st: &fuel_formats::safetensors::MmapedSafetensors,
9609    name: &str,
9610) -> crate::Result<Vec<f32>> {
9611    use safetensors::Dtype;
9612    let view = st.get(name)?;
9613    let bytes = view.data();
9614    match view.dtype() {
9615        Dtype::F32 => {
9616            let mut out = Vec::with_capacity(bytes.len() / 4);
9617            for chunk in bytes.as_chunks::<4>().0.iter() {
9618                out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
9619            }
9620            Ok(out)
9621        }
9622        Dtype::F64 => {
9623            let mut out = Vec::with_capacity(bytes.len() / 8);
9624            for chunk in bytes.as_chunks::<8>().0.iter() {
9625                let arr: [u8; 8] = *chunk;
9626                out.push(f64::from_le_bytes(arr) as f32);
9627            }
9628            Ok(out)
9629        }
9630        Dtype::BF16 => {
9631            let mut out = Vec::with_capacity(bytes.len() / 2);
9632            for chunk in bytes.as_chunks::<2>().0.iter() {
9633                let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9634                out.push(half::bf16::from_bits(raw).to_f32());
9635            }
9636            Ok(out)
9637        }
9638        Dtype::F16 => {
9639            let mut out = Vec::with_capacity(bytes.len() / 2);
9640            for chunk in bytes.as_chunks::<2>().0.iter() {
9641                let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9642                out.push(half::f16::from_bits(raw).to_f32());
9643            }
9644            Ok(out)
9645        }
9646        other => {
9647            crate::bail!("load_tensor_as_f32: unsupported dtype {other:?} for tensor {name:?}",)
9648        }
9649    }
9650}
9651
9652/// Load a tensor by name and physically transpose it from `[out, in]`
9653/// (HuggingFace layout) to `[in, out]` (fuel-graph's layout for
9654/// `x @ W` where `W` is `[in, out]`). Linear-layer weights in HF
9655/// transformers are stored as `[out_features, in_features]`, so every
9656/// call to this function is effectively "give me that matrix as I'd
9657/// use it in `matmul`."
9658pub fn load_transposed_matrix(
9659    st: &fuel_formats::safetensors::MmapedSafetensors,
9660    name: &str,
9661    out_features: usize,
9662    in_features: usize,
9663) -> crate::Result<Vec<f32>> {
9664    let flat = load_tensor_as_f32(st, name)?;
9665    if flat.len() != out_features * in_features {
9666        crate::bail!(
9667            "load_transposed_matrix: tensor {name:?} has {} elements, expected {} ({out_features} × {in_features})",
9668            flat.len(),
9669            out_features * in_features,
9670        );
9671    }
9672    // HF layout: flat[i * in_features + j] is W[i, j] for (out i, in j).
9673    // Target layout: out[j * out_features + i] so that indexing `[j, i]`
9674    // in row-major gives the same W[i, j] — i.e. out has shape [in, out].
9675    let mut out = vec![0.0_f32; out_features * in_features];
9676    for i in 0..out_features {
9677        for j in 0..in_features {
9678            out[j * out_features + i] = flat[i * in_features + j];
9679        }
9680    }
9681    Ok(out)
9682}
9683
9684/// Transposed-matrix loader that preserves source dtype. For
9685/// safetensors files saved with bf16 weights, returns
9686/// `WeightStorage::BF16` and never materializes an f32 copy — the
9687/// 2× memory saving vs `load_transposed_matrix` comes from here.
9688/// f32 and other source dtypes still go through the f32 upcast path
9689/// for safety; extending this to preserve f16 is a one-line change
9690/// when a consumer wants it.
9691///
9692/// The transpose itself is done in whatever dtype we're keeping:
9693/// read bf16 elements from the file, place them in the transposed
9694/// target buffer, no conversion.
9695pub fn load_transposed_matrix_preserve_dtype(
9696    st: &fuel_formats::safetensors::MmapedSafetensors,
9697    name: &str,
9698    out_features: usize,
9699    in_features: usize,
9700) -> crate::Result<WeightStorage> {
9701    use safetensors::Dtype;
9702    let view = st.get(name)?;
9703    let bytes = view.data();
9704    let expected = out_features * in_features;
9705    match view.dtype() {
9706        Dtype::BF16 => {
9707            if bytes.len() != expected * 2 {
9708                crate::bail!(
9709                    "load_transposed_matrix_preserve_dtype: bf16 tensor {name:?} has {} bytes, expected {}",
9710                    bytes.len(),
9711                    expected * 2,
9712                );
9713            }
9714            // Reinterpret input as [out_features, in_features] of
9715            // bf16; write transposed layout.
9716            let mut out = vec![half::bf16::ZERO; expected];
9717            for i in 0..out_features {
9718                for j in 0..in_features {
9719                    let src_off = (i * in_features + j) * 2;
9720                    let bits = u16::from_le_bytes([bytes[src_off], bytes[src_off + 1]]);
9721                    out[j * out_features + i] = half::bf16::from_bits(bits);
9722                }
9723            }
9724            Ok(WeightStorage::BF16(Arc::from(out)))
9725        }
9726        _ => {
9727            // F32, F64, F16 all fall through to the f32 upcast path.
9728            // Non-f32 source types still benefit from being readable;
9729            // they just lose the "weights stay compact" win.
9730            let flat = load_transposed_matrix(st, name, out_features, in_features)?;
9731            Ok(WeightStorage::F32(Arc::from(flat)))
9732        }
9733    }
9734}
9735
9736/// Sampling strategy for decode loops.
9737#[derive(Debug, Clone, Copy, Default)]
9738pub enum SamplingStrategy {
9739    /// Greedy: always pick the highest-probability token.
9740    #[default]
9741    Greedy,
9742    /// Temperature-scaled sampling with a deterministic seed. `temp`
9743    /// is the softmax temperature (`1.0` is unscaled, `temp <= 0.0` or NaN is
9744    /// greedy, higher values spread probability mass).
9745    /// The seed makes sampling reproducible.
9746    Temperature { temp: f32, seed: u64 },
9747}
9748
9749/// Greedy argmax over a logits row, by the `sample_argmax` contract (ruling 2026-11-25, the same
9750/// rule `fuel-transformers` `generation::sample_argmax` follows): an empty row is an `Err`; a NaN
9751/// ANYWHERE in the row is an `Err` (the model produced NaN: never pick a token from such a row, even
9752/// when the NaN is not at the maximum); ties take the FIRST index (strict `>`; `-0.0 == +0.0`);
9753/// `+inf` and `-inf` are ordinary values here.
9754///
9755/// This replaces `max_by(partial_cmp -> Equal)`, which treated a NaN comparison as a tie, so a NaN
9756/// row returned an arbitrary index, and which returned the LAST of a set of tied maxima.
9757fn argmax_logits(logits: &[f32]) -> fuel_ir::Result<u32> {
9758    if logits.is_empty() {
9759        return Err(fuel_ir::error::Error::Msg(
9760            "sample_logits: empty logits".into(),
9761        ));
9762    }
9763    if let Some(at) = logits.iter().position(|v| v.is_nan()) {
9764        return Err(fuel_ir::error::Error::Msg(format!(
9765            "sample_logits: logit {at} of {} is NaN (the model produced NaN); refusing to pick a token",
9766            logits.len()
9767        )));
9768    }
9769    let mut best = 0usize;
9770    for (i, &v) in logits.iter().enumerate() {
9771        if v > logits[best] {
9772            best = i;
9773        }
9774    }
9775    Ok(best as u32)
9776}
9777
9778/// Pick the next token from a logits vector using the configured
9779/// sampling strategy. Pulled out of `generate` so both the cached and
9780/// future non-cached callers can share it.
9781///
9782/// Errors (never panics): an empty row; a NaN logit anywhere (greedy and temperature paths alike);
9783/// on the temperature path also an infinite logit, as [`crate::sampling::sample_with_params`] does
9784/// (the softmax of an infinity is NaN). Greedy ties take the first index (see `argmax_logits`).
9785pub fn sample_logits(
9786    logits: &[f32],
9787    strategy: SamplingStrategy,
9788    rng_state: &mut u64,
9789) -> fuel_ir::Result<u32> {
9790    match strategy {
9791        SamplingStrategy::Greedy => argmax_logits(logits),
9792        // `temp <= 0.0` (and NaN) is the greedy limit: documented as "effectively greedy". It
9793        // used to scale by 1.0 and sample from the unscaled softmax.
9794        SamplingStrategy::Temperature { temp, .. } if temp.is_nan() || temp <= 0.0 => {
9795            argmax_logits(logits)
9796        }
9797        SamplingStrategy::Temperature { temp, .. } => {
9798            if let Some(at) = logits.iter().position(|v| !v.is_finite()) {
9799                return Err(fuel_ir::error::Error::Msg(format!(
9800                    "sample_logits: logit {at} of {} is not finite; refusing to sample",
9801                    logits.len()
9802                )));
9803            }
9804            if logits.is_empty() {
9805                return Err(fuel_ir::error::Error::Msg(
9806                    "sample_logits: empty logits".into(),
9807                ));
9808            }
9809            // Stable softmax over temperature-scaled logits,
9810            // then a deterministic multinomial draw.
9811            let inv_temp = 1.0 / temp;
9812            let scaled: Vec<f32> = logits.iter().map(|&x| x * inv_temp).collect();
9813            let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9814            let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
9815            let sum: f32 = exp.iter().sum();
9816            let probs: Vec<f32> = exp.iter().map(|&x| x / sum).collect();
9817            Ok(sample_multinomial(&probs, rng_state))
9818        }
9819    }
9820}
9821
9822// ---- Speculative-decoding helpers ---------------------------------------
9823//
9824// Shared by `generate_streaming_spec_with_kv_context`'s draft / accept
9825// phases. All host-side: spec decode's accept rule operates on logits
9826// vectors already downloaded from the device.
9827
9828/// Greedy argmax over a logits row, by the same contract as `sample_logits` (empty or NaN row is an
9829/// `Err`, ties take the first index). It used to index `logits[0]` (a panic on an empty row) and, with
9830/// a NaN at index 0, compare against it for the whole scan (every `v > NaN` is false: index 0 won).
9831pub fn spec_argmax(logits: &[f32]) -> fuel_ir::Result<u32> {
9832    argmax_logits(logits)
9833}
9834
9835/// Temperature-scaled softmax. Returns normalized probabilities.
9836pub fn spec_softmax_temp(logits: &[f32], temp: f32) -> Vec<f32> {
9837    let inv_t = if temp == 0.0 { 1.0 } else { 1.0 / temp };
9838    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9839    let exp: Vec<f32> = logits.iter().map(|&x| ((x - max) * inv_t).exp()).collect();
9840    let sum: f32 = exp.iter().sum();
9841    exp.iter().map(|&x| x / sum).collect()
9842}
9843
9844/// Advance a deterministic LCG and return a u01 uniform.
9845pub fn spec_next_u01(state: &mut u64) -> f32 {
9846    *state = state
9847        .wrapping_mul(6364136223846793005)
9848        .wrapping_add(1442695040888963407);
9849    (*state >> 32) as f32 / u32::MAX as f32
9850}
9851
9852/// Sample a category from a distribution summing to ~1.
9853pub fn spec_sample_cat(probs: &[f32], state: &mut u64) -> u32 {
9854    let u = spec_next_u01(state);
9855    let mut cum = 0.0_f32;
9856    for (i, &p) in probs.iter().enumerate() {
9857        cum += p;
9858        if u <= cum {
9859            return i as u32;
9860        }
9861    }
9862    (probs.len() - 1) as u32
9863}
9864
9865/// Sample a categorical distribution using a small deterministic LCG.
9866/// Takes `probs` (assumed to sum to ~1) and a mutable RNG state,
9867/// returns a sampled index.
9868pub fn sample_multinomial(probs: &[f32], rng_state: &mut u64) -> u32 {
9869    // Advance the LCG and turn it into a u01 uniform.
9870    *rng_state = rng_state
9871        .wrapping_mul(6364136223846793005)
9872        .wrapping_add(1442695040888963407);
9873    let u = (*rng_state >> 32) as f32 / u32::MAX as f32;
9874    let mut cumulative = 0.0_f32;
9875    for (i, &p) in probs.iter().enumerate() {
9876        cumulative += p;
9877        if u <= cumulative {
9878            return i as u32;
9879        }
9880    }
9881    // Floating-point slop: fall through to the last index.
9882    (probs.len() - 1) as u32
9883}
9884
9885#[cfg(test)]
9886mod lora_tests {
9887    use super::*;
9888    use crate::Shape;
9889
9890    #[test]
9891    fn with_lora_matches_manual_base_plus_lora() {
9892        // Anchor graph.
9893        let in_f = 4;
9894        let out_f = 3;
9895        let rank = 2;
9896        let alpha = 8.0_f32;
9897
9898        let anchor =
9899            Tensor::from_f32(vec![0.0_f32; 1], Shape::from_dims(&[1]), &Device::cpu()).unwrap();
9900        // Base weight [in, out].
9901        let base_vec: Vec<f32> = (0..in_f * out_f).map(|i| (i as f32) * 0.1).collect();
9902        let lora_a_vec: Vec<f32> = (0..in_f * rank).map(|i| (i as f32) * 0.05).collect();
9903        let lora_b_vec: Vec<f32> = (0..rank * out_f).map(|i| (i as f32) * 0.02).collect();
9904
9905        let ws = WeightStorage::F32(Arc::from(base_vec.clone())).with_lora(
9906            Arc::from(lora_a_vec.clone()),
9907            Arc::from(lora_b_vec.clone()),
9908            rank,
9909            alpha,
9910            in_f,
9911            out_f,
9912        );
9913
9914        // Activations x [2, in_f].
9915        let batch = 2;
9916        let x_data: Vec<f32> = (0..batch * in_f).map(|i| (i as f32) * 0.1 + 0.5).collect();
9917        let x = anchor
9918            .const_f32_like(x_data.clone(), Shape::from_dims(&[batch, in_f]))
9919            .unwrap();
9920        let y = ws.apply_linear(&x, in_f, out_f).unwrap();
9921        let got = y.realize_f32().to_vec();
9922
9923        // Reference: base + (alpha/rank) * x @ A @ B, all f32, on CPU.
9924        let mut expected = vec![0.0_f32; batch * out_f];
9925        for b in 0..batch {
9926            for j in 0..out_f {
9927                let mut acc = 0.0_f32;
9928                // Base path: sum_k x[b,k] * W[k,j].
9929                for k in 0..in_f {
9930                    acc += x_data[b * in_f + k] * base_vec[k * out_f + j];
9931                }
9932                // LoRA path: sum_r (sum_k x[b,k] * A[k,r]) * B[r,j] * (alpha/rank).
9933                let scale = alpha as f64 / rank as f64;
9934                for r in 0..rank {
9935                    let mut xar = 0.0_f32;
9936                    for k in 0..in_f {
9937                        xar += x_data[b * in_f + k] * lora_a_vec[k * rank + r];
9938                    }
9939                    acc += (xar * lora_b_vec[r * out_f + j]) * scale as f32;
9940                }
9941                expected[b * out_f + j] = acc;
9942            }
9943        }
9944
9945        for (i, (&e, &g)) in expected.iter().zip(got.iter()).enumerate() {
9946            let diff = (e - g).abs();
9947            assert!(
9948                diff <= 1e-4,
9949                "LoRA mismatch at {i}: expected {e}, got {g} (diff {diff})",
9950            );
9951        }
9952    }
9953
9954    #[test]
9955    #[should_panic(expected = "lora_a length")]
9956    fn with_lora_rejects_mismatched_a_shape() {
9957        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
9958        let bad_a = Arc::from(vec![0.0_f32; 3]); // wrong
9959        let b = Arc::from(vec![0.0_f32; 6]); // 2 x 3
9960        let _ = ws.with_lora(bad_a, b, 2, 8.0, 4, 3);
9961    }
9962
9963    // ---- never-panic conversion (`apply_linear` -> `Result`) ----
9964    //
9965    // These three inputs each used to abort the process on a PRODUCTION path:
9966    // a wrong trailing dim reached `x.matmul(&w).unwrap()`, a stored/requested
9967    // shape disagreement hit `assert_eq!`, and a wrong-length bias hit a
9968    // `debug_assert_eq!` that is compiled OUT of release builds — so release
9969    // binaries broadcast a mis-sized bias with no complaint at all. All three
9970    // are checkpoint/data conditions rather than programming invariants (a
9971    // GGUF whose stored shape disagrees with the model config produces exactly
9972    // this), so all three must be `Err`.
9973
9974    #[test]
9975    fn apply_linear_errors_on_trailing_dim_mismatch() {
9976        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
9977        let x = Tensor::from_f32(
9978            vec![0.0_f32; 10],
9979            Shape::from_dims(&[2, 5]), // trailing dim 5 != in_features 4
9980            &Device::cpu(),
9981        )
9982        .unwrap();
9983        let err = ws
9984            .apply_linear(&x, 4, 3)
9985            .expect_err("must not panic, must Err");
9986        let msg = err.to_string();
9987        assert!(
9988            msg.contains("trailing dim 4"),
9989            "error should name the expected trailing dim, got: {msg}",
9990        );
9991    }
9992
9993    #[test]
9994    fn apply_linear_errors_on_q4_0_stored_shape_mismatch() {
9995        // 4 x 4 of Q4_0: one 32-element block needs 18 bytes; keep the word
9996        // count self-consistent since only the shape check is under test.
9997        let ws = WeightStorage::Q4_0 {
9998            words: Arc::from(vec![0_u32; 8]),
9999            bytes_len: 18, // one Q4_0 block: 2-byte scale + 16 packed nibble bytes
10000            in_features: 4,
10001            out_features: 4,
10002        };
10003        let x =
10004            Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
10005        // Trailing dim matches in_features, so this reaches the stored-shape
10006        // check rather than the contract check above.
10007        let err = ws
10008            .apply_linear(&x, 4, 7)
10009            .expect_err("must not panic, must Err");
10010        let msg = err.to_string();
10011        assert!(
10012            msg.contains("Q4_0 shape mismatch"),
10013            "error should name the stored/requested disagreement, got: {msg}",
10014        );
10015    }
10016
10017    #[test]
10018    fn apply_linear_with_bias_errors_on_wrong_bias_length() {
10019        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
10020        let x =
10021            Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
10022        let bias: Arc<[f32]> = Arc::from(vec![0.0_f32; 2]); // wrong: out_features is 3
10023        let err = ws
10024            .apply_linear_with_bias(&x, 4, 3, bias)
10025            .expect_err("wrong-length bias must Err in EVERY profile, not just debug");
10026        assert!(
10027            err.to_string().contains("bias len"),
10028            "error should name the bias length, got: {err}",
10029        );
10030    }
10031}
10032
10033#[cfg(test)]
10034mod safetensors_bridge_tests {
10035    use super::*;
10036
10037    #[test]
10038    fn from_safetensors_bytes_round_trip_f32() {
10039        // Build a tensor, serialize it as little-endian f32 bytes,
10040        // then deserialize via the bridge. Should get back the same
10041        // values.
10042        let original: Vec<f32> = vec![1.0, -2.5, 3.25, 0.0];
10043        let mut bytes = Vec::with_capacity(original.len() * 4);
10044        for &v in &original {
10045            bytes.extend_from_slice(&v.to_le_bytes());
10046        }
10047        let t =
10048            Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::F32, &[4], &Device::cpu())
10049                .unwrap();
10050        assert_eq!(t.shape().dims(), &[4]);
10051        assert_eq!(t.dtype(), DType::F32);
10052        assert_eq!(t.realize_f32(), original);
10053    }
10054
10055    #[test]
10056    fn from_safetensors_bytes_round_trip_bf16() {
10057        let original_f32: Vec<f32> = vec![0.5, -1.0, 2.0, 4.0];
10058        let bf16_vec: Vec<half::bf16> = original_f32
10059            .iter()
10060            .map(|&v| half::bf16::from_f32(v))
10061            .collect();
10062        let mut bytes = Vec::with_capacity(bf16_vec.len() * 2);
10063        for b in &bf16_vec {
10064            bytes.extend_from_slice(&b.to_bits().to_le_bytes());
10065        }
10066        let t =
10067            Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::BF16, &[4], &Device::cpu())
10068                .unwrap();
10069        assert_eq!(t.dtype(), DType::BF16);
10070        // Values that round-trip exactly through bf16 should come back
10071        // unchanged.
10072        let realized = t.realize_bf16();
10073        assert_eq!(realized, bf16_vec);
10074    }
10075
10076    #[test]
10077    fn from_safetensors_bytes_rejects_wrong_byte_count() {
10078        // Shape says 3 elements, but we pass 4 bytes (1 f32 = 4 bytes
10079        // so 3 elements would need 12 bytes).
10080        let bad_bytes = vec![0_u8; 4];
10081        let result = Tensor::from_safetensors_bytes(
10082            &bad_bytes,
10083            safetensors::Dtype::F32,
10084            &[3],
10085            &Device::cpu(),
10086        );
10087        assert!(result.is_err());
10088    }
10089}
10090
10091// ============================================================================
10092// Phase A.1 wrapper smoke tests.
10093//
10094// Pure pass-through tests: realize and assert the returned tensor has the
10095// expected shape / dtype / values. The graph-level ops are tested in
10096// `fuel-graph`; here we only verify that the Tensor wrappers don't
10097// drop information or mis-thread arguments.
10098// ============================================================================
10099#[cfg(test)]
10100mod phase_a1_wrapper_tests {
10101    use super::*;
10102
10103    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10104        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10105    }
10106
10107    #[test]
10108    fn unsqueeze_adds_size_one_dim() {
10109        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10110        let out = t.unsqueeze(0_usize).unwrap();
10111        assert_eq!(out.shape().dims(), &[1, 2, 2]);
10112        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10113    }
10114
10115    #[test]
10116    fn unsqueeze_errors_out_of_bounds() {
10117        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10118        // rank=1, so dim<=1 is valid; dim=2 must error.
10119        assert!(t.unsqueeze(0_usize).is_ok());
10120        assert!(t.unsqueeze(1_usize).is_ok());
10121        assert!(t.unsqueeze(2_usize).is_err());
10122    }
10123
10124    #[test]
10125    fn try_reshape_errors_on_size_mismatch() {
10126        let t = cpu_f32(vec![1.0; 6], &[2, 3]);
10127        assert!(t.reshape(vec![3, 2]).is_ok());
10128        assert!(t.reshape(vec![2, 2]).is_err());
10129    }
10130
10131    #[test]
10132    fn try_permute_validates_axes() {
10133        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10134        // The Dims trait accepts tuples, owned arrays, and slices.
10135        assert!(t.permute((2_usize, 0_usize, 1_usize)).is_ok());
10136        assert!(t.permute([2_usize, 0, 1]).is_ok());
10137        assert!(t.permute([0_usize, 1]).is_err()); // wrong rank
10138        assert!(t.permute([0_usize, 0, 1]).is_err()); // dup axis
10139    }
10140
10141    #[test]
10142    fn try_transpose_requires_rank_two_plus() {
10143        let scalar = cpu_f32(vec![1.0], &[1]);
10144        // rank-1: transpose surfaces a typed error at build time.
10145        let _ = scalar.transpose();
10146    }
10147
10148    #[test]
10149    fn triu_tril_shape_preserved() {
10150        let t = cpu_f32(vec![1.0; 9], &[3, 3]);
10151        let upper = t.triu(0).unwrap();
10152        let lower = t.tril(0).unwrap();
10153        assert_eq!(upper.shape().dims(), &[3, 3]);
10154        assert_eq!(lower.shape().dims(), &[3, 3]);
10155        // tril(0) of all-ones: 1s on/below diagonal, 0s above
10156        assert_eq!(
10157            lower.realize_f32(),
10158            vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
10159        );
10160    }
10161
10162    #[test]
10163    fn triu_rejects_rank_one() {
10164        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10165        assert!(t.triu(0).is_err());
10166    }
10167
10168    #[test]
10169    fn log_softmax_last_dim_shape_preserved() {
10170        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10171        let out = t.log_softmax_last_dim().unwrap();
10172        assert_eq!(out.shape().dims(), &[2, 2]);
10173        // log_softmax values must be <= 0.
10174        for v in out.realize_f32() {
10175            assert!(v <= 0.0 + 1e-6, "log_softmax produced positive value: {v}");
10176        }
10177    }
10178
10179    #[test]
10180    fn softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10181        // shape [2, 3, 2] — softmax along axis=1 (the size-3 axis).
10182        // Layout (row-major): element (b, r, c) lives at b*6 + r*2 + c.
10183        // We hand-pick values so each (b, c) lane's max is exactly 0 to
10184        // make the reference closed-form: probs = exp(x) / sum_r exp(x).
10185        // Lane (b=0, c=0): values [-1, 0, -2]  → exp = [e^-1, 1, e^-2]
10186        // Lane (b=0, c=1): values [ 0,-3, -1]  → exp = [1, e^-3, e^-1]
10187        // Lane (b=1, c=0): values [-2,-1,  0]  → exp = [e^-2, e^-1, 1]
10188        // Lane (b=1, c=1): values [-1,-1,  0]  → exp = [e^-1, e^-1, 1]
10189        let data: Vec<f32> = vec![
10190            // b=0
10191            -1.0, 0.0, // r=0, c=0..1
10192            0.0, -3.0, // r=1
10193            -2.0, -1.0, // r=2
10194            // b=1
10195            -2.0, -1.0, // r=0
10196            -1.0, -1.0, // r=1
10197            0.0, 0.0, // r=2
10198        ];
10199        let t = cpu_f32(data, &[2, 3, 2]);
10200        let out = t.softmax(1_usize).unwrap();
10201        assert_eq!(out.shape().dims(), &[2, 3, 2]);
10202        let v = out.realize_f32();
10203
10204        // Reference: closed-form softmax per (b, c) lane.
10205        let lane_softmax = |xs: [f32; 3]| -> [f32; 3] {
10206            let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10207            let exps = [(xs[0] - m).exp(), (xs[1] - m).exp(), (xs[2] - m).exp()];
10208            let s = exps[0] + exps[1] + exps[2];
10209            [exps[0] / s, exps[1] / s, exps[2] / s]
10210        };
10211        // Re-extract source lanes
10212        let lanes: [[f32; 3]; 4] = [
10213            [-1.0, 0.0, -2.0], // (b=0, c=0)
10214            [0.0, -3.0, -1.0], // (b=0, c=1)
10215            [-2.0, -1.0, 0.0], // (b=1, c=0)
10216            [-1.0, -1.0, 0.0], // (b=1, c=1)
10217        ];
10218        let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_softmax(*l)).collect();
10219
10220        // out[b, r, c] at index b*6 + r*2 + c — verify each (b, c) lane.
10221        for b in 0..2 {
10222            for c in 0..2 {
10223                let lane_ix = b * 2 + c;
10224                for r in 0..3 {
10225                    let got = v[b * 6 + r * 2 + c];
10226                    let want = refs[lane_ix][r];
10227                    assert!(
10228                        (got - want).abs() < 1e-6,
10229                        "softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10230                    );
10231                }
10232                // sanity: lane sums to 1
10233                let sum: f32 = (0..3).map(|r| v[b * 6 + r * 2 + c]).sum();
10234                assert!((sum - 1.0).abs() < 1e-6, "lane (b={b},c={c}) sums to {sum}");
10235            }
10236        }
10237    }
10238
10239    #[test]
10240    fn softmax_last_axis_matches_softmax_last_dim() {
10241        let data: Vec<f32> = vec![
10242            1.0, 2.0, -1.0, 0.5, 0.0, -2.0, 3.0, 1.5, // batch dim 2
10243            4.0, -1.0, 2.0, 0.0, -3.0, 0.25, 0.75, 1.0,
10244        ];
10245        let t = cpu_f32(data, &[2, 2, 4]);
10246        let via_general = t.softmax(2_usize).unwrap();
10247        let via_fused = t.softmax_last_dim().unwrap();
10248        assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10249        let g = via_general.realize_f32();
10250        let f = via_fused.realize_f32();
10251        assert_eq!(g.len(), f.len());
10252        for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10253            assert!(
10254                (a - b).abs() < 1e-6,
10255                "softmax (general axis=2) vs softmax_last_dim diverge at {i}: {a} vs {b}",
10256            );
10257        }
10258    }
10259
10260    #[test]
10261    fn log_softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10262        // Same construction as the softmax test, but compare against
10263        // closed-form log_softmax per (b, c) lane.
10264        let data: Vec<f32> = vec![
10265            -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0,
10266        ];
10267        let t = cpu_f32(data, &[2, 3, 2]);
10268        let out = t.log_softmax(1_usize).unwrap();
10269        assert_eq!(out.shape().dims(), &[2, 3, 2]);
10270        let v = out.realize_f32();
10271
10272        let lane_log_softmax = |xs: [f32; 3]| -> [f32; 3] {
10273            let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10274            let shifted = [xs[0] - m, xs[1] - m, xs[2] - m];
10275            let lse = (shifted[0].exp() + shifted[1].exp() + shifted[2].exp()).ln();
10276            [shifted[0] - lse, shifted[1] - lse, shifted[2] - lse]
10277        };
10278        let lanes: [[f32; 3]; 4] = [
10279            [-1.0, 0.0, -2.0],
10280            [0.0, -3.0, -1.0],
10281            [-2.0, -1.0, 0.0],
10282            [-1.0, -1.0, 0.0],
10283        ];
10284        let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_log_softmax(*l)).collect();
10285
10286        for b in 0..2 {
10287            for c in 0..2 {
10288                let lane_ix = b * 2 + c;
10289                for r in 0..3 {
10290                    let got = v[b * 6 + r * 2 + c];
10291                    let want = refs[lane_ix][r];
10292                    assert!(
10293                        (got - want).abs() < 1e-6,
10294                        "log_softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10295                    );
10296                    // log_softmax values must be <= 0
10297                    assert!(got <= 1e-6, "log_softmax produced positive value: {got}");
10298                }
10299            }
10300        }
10301    }
10302
10303    #[test]
10304    fn log_softmax_last_axis_matches_log_softmax_last_dim() {
10305        let data: Vec<f32> = vec![
10306            1.0, 2.0, -1.0, 0.5, 0.0, -2.0, 3.0, 1.5, 4.0, -1.0, 2.0, 0.0, -3.0, 0.25, 0.75, 1.0,
10307        ];
10308        let t = cpu_f32(data, &[2, 2, 4]);
10309        let via_general = t.log_softmax(2_usize).unwrap();
10310        let via_fused = t.log_softmax_last_dim().unwrap();
10311        assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10312        let g = via_general.realize_f32();
10313        let f = via_fused.realize_f32();
10314        assert_eq!(g.len(), f.len());
10315        for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10316            assert!(
10317                (a - b).abs() < 1e-6,
10318                "log_softmax (general axis=2) vs log_softmax_last_dim diverge at {i}: {a} vs {b}",
10319            );
10320        }
10321    }
10322
10323    #[test]
10324    fn argmin_dim_drops_reduced_axis() {
10325        let t = cpu_f32(vec![3.0, 1.0, 2.0, 0.5, 5.0, 4.0], &[2, 3]);
10326        let out = t.argmin_dim(1_usize).unwrap();
10327        assert_eq!(out.shape().dims(), &[2]);
10328        assert_eq!(out.dtype(), DType::U32);
10329        assert_eq!(out.realize_u32(), vec![1, 0]);
10330    }
10331
10332    #[test]
10333    fn masked_fill_smoke() {
10334        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10335        // Comparison ops produce Bool masks directly (GAP-168(c)) — masked_fill
10336        // now accepts Bool, no F32→mask cast needed.
10337        let probe = t
10338            .const_f32_like(vec![0.0, 1.0, 1.0, 0.0], vec![2, 2])
10339            .unwrap();
10340        let threshold = t.const_f32_like(vec![0.5; 4], vec![2, 2]).unwrap();
10341        let mask = probe.gt(&threshold).unwrap(); // [0, 1, 1, 0] as Bool
10342        let out = t.masked_fill(&mask, fuel_ir::Scalar::F32(-9.0)).unwrap();
10343        assert_eq!(out.realize_f32(), vec![1.0, -9.0, -9.0, 4.0]);
10344    }
10345
10346    /// GAP-168(c) DISCRIMINATION: `Bool` and `U8` are byte-identical in storage,
10347    /// which is exactly the condition under which a wrong wiring is *silently
10348    /// correct*. This test proves they are NOT interchangeable end-to-end on CPU:
10349    /// a comparison yields a `Bool` (not `U8`) tensor, and `to_dtype(Bool)` on a
10350    /// `U8` tensor is a real `!= 0` CONVERSION — never a byte reinterpret.
10351    #[test]
10352    fn bool_is_distinguishable_from_u8_end_to_end() {
10353        // A comparison realizes end-to-end as a Bool tensor (NOT U8) whose bytes
10354        // are 0/1 — the byte-identity hazard's most likely hiding spot, closed:
10355        // dtype tag is Bool, the CPU kernel dispatches on [F32,F32,Bool] (its FKC
10356        // contract declares fixed(BOOL)), and Copy[Bool] materializes it to host.
10357        let t = cpu_f32(vec![0.0, 5.0, 3.0, 0.0], &[4]);
10358        let thr = t.const_f32_like(vec![0.5; 4], vec![4]).unwrap();
10359        let mask = t.gt(&thr).unwrap();
10360        assert_eq!(mask.dtype(), DType::Bool, "gt yields Bool, not U8");
10361        assert_eq!(mask.realize_u8(), vec![0, 1, 1, 0], "mask bytes are 0/1");
10362
10363        // ---- The cast discrimination, now that the 22 Bool pairs are wired ----
10364        //
10365        // NEGATIVE CONTROL FIRST, or the assertion below is vacuous: build a U8
10366        // tensor that genuinely holds 5. If this line ever came back as 0/1, the
10367        // real test would pass for the wrong reason — it would be comparing 0/1
10368        // against 0/1 and could not tell a conversion from a reinterpret.
10369        let u8_vals = t
10370            .const_f32_like(vec![0.0, 5.0, 3.0, 0.0], vec![4])
10371            .unwrap()
10372            .to_dtype(DType::U8)
10373            .unwrap();
10374        assert_eq!(u8_vals.dtype(), DType::U8);
10375        assert_eq!(
10376            u8_vals.realize_u8(),
10377            vec![0, 5, 3, 0],
10378            "negative control: the U8 source must really hold 5 and 3, else the \
10379             conversion assertion below cannot discriminate"
10380        );
10381
10382        // THE DISCRIMINATION: U8 -> Bool is a real `!= 0` conversion. A byte
10383        // reinterpret would yield [0, 5, 3, 0] — byte-identical storage makes
10384        // that the silently-correct-looking failure. A conversion yields 0/1.
10385        let as_bool = u8_vals.to_dtype(DType::Bool).unwrap();
10386        assert_eq!(as_bool.dtype(), DType::Bool);
10387        assert_eq!(
10388            as_bool.realize_u8(),
10389            vec![0, 1, 1, 0],
10390            "U8->Bool must CONVERT (5 -> 1), not reinterpret (5 -> 5)"
10391        );
10392
10393        // And back out: Bool -> F32 is exactly 0.0/1.0.
10394        assert_eq!(
10395            as_bool.to_dtype(DType::F32).unwrap().realize_f32(),
10396            vec![0.0, 1.0, 1.0, 0.0],
10397            "Bool->F32 yields 0.0/1.0"
10398        );
10399        // Bool -> U8 keeps the canonical 0/1 (this direction IS byte-preserving,
10400        // which is fine — it is the OTHER direction that must not be).
10401        assert_eq!(
10402            mask.to_dtype(DType::U8).unwrap().realize_u8(),
10403            vec![0, 1, 1, 0]
10404        );
10405
10406        // FINALLY, the two are not INTERCHANGEABLE at the API, which is what
10407        // stops a numeric mask being coerced silently: `masked_fill` requires a
10408        // Bool mask and rejects U8 at GRAPH-BUILD time, so the cast is explicit
10409        // at the call site rather than implied.
10410        let err = t.masked_fill(&u8_vals, fuel_ir::Scalar::F32(-9.0));
10411        assert!(
10412            err.is_err(),
10413            "a U8 mask must be REJECTED by masked_fill — Bool and U8 are \
10414             byte-identical, so accepting it would 'work' and erase the distinction"
10415        );
10416    }
10417
10418    /// GAP-183: `float -> Bool` is lowered in the optimizer to `Ne(x, x*0)` so it
10419    /// reaches CUDA's shipped `ne_{f32,f64,f16,bf16}` kernels, which a
10420    /// storage-level cast cannot compose. This pins the VALUES end-to-end, and
10421    /// the three interesting inputs are the whole point of the test — a lowering
10422    /// that got only the ordinary cases right would still be wrong:
10423    ///
10424    ///   -0.0  -> FALSE   (IEEE `-0.0 == 0.0`)
10425    ///   NaN   -> TRUE    (matches PyTorch `.bool()`)
10426    ///   ±inf  -> TRUE
10427    ///
10428    /// The zeros operand is itself NaN for non-finite x; that is harmless because
10429    /// `x != NaN` and `x != 0` agree for every non-finite x. This test is what
10430    /// would catch it if that ever stopped being true.
10431    #[test]
10432    fn float_to_bool_lowering_preserves_ieee_semantics() {
10433        let t = cpu_f32(
10434            vec![
10435                0.0,
10436                -0.0,
10437                5.0,
10438                -3.0,
10439                f32::NAN,
10440                f32::INFINITY,
10441                f32::NEG_INFINITY,
10442            ],
10443            &[7],
10444        );
10445        let b = t.to_dtype(DType::Bool).unwrap();
10446        assert_eq!(b.dtype(), DType::Bool, "to_dtype(Bool) still yields Bool");
10447        assert_eq!(
10448            b.realize_u8(),
10449            vec![0, 0, 1, 1, 1, 1, 1],
10450            "0 and -0.0 are false; every other value including NaN and both \
10451             infinities is true",
10452        );
10453    }
10454
10455    #[test]
10456    fn index_add_smoke() {
10457        let base = cpu_f32(vec![1.0, 1.0, 1.0, 1.0], &[2, 2]);
10458        let src = base
10459            .const_f32_like(vec![10.0, 20.0, 30.0, 40.0], vec![2, 2])
10460            .unwrap();
10461        let indices = base.const_u32_like(vec![0_u32, 0_u32], vec![2]).unwrap();
10462        let out = base.index_add(0, &indices, &src).unwrap();
10463        assert_eq!(out.shape().dims(), &[2, 2]);
10464        // both src rows added to row 0; row 1 unchanged
10465        let v = out.realize_f32();
10466        assert_eq!(v[0], 41.0); // 1 + 10 + 30
10467        assert_eq!(v[1], 61.0); // 1 + 20 + 40
10468        assert_eq!(v[2], 1.0);
10469        assert_eq!(v[3], 1.0);
10470    }
10471
10472    #[test]
10473    fn scatter_add_smoke() {
10474        let base = cpu_f32(vec![0.0, 0.0, 0.0, 0.0], &[2, 2]);
10475        let src = base
10476            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
10477            .unwrap();
10478        let indices = base
10479            .const_u32_like(vec![0_u32, 1_u32, 1_u32, 0_u32], vec![2, 2])
10480            .unwrap();
10481        let out = base.scatter_add(0, &indices, &src).unwrap();
10482        assert_eq!(out.shape().dims(), &[2, 2]);
10483    }
10484
10485    #[test]
10486    fn inplace_activations_compile_and_run() {
10487        let t = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]);
10488        // Each in-place op is destructive, so chain through fresh tensors.
10489        let r = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).relu_inplace();
10490        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).silu_inplace();
10491        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).gelu_tanh_inplace();
10492        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).tanh_inplace();
10493        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).sigmoid_inplace();
10494        let _ = t.affine_inplace(2.0, 1.0);
10495        // Spot-check the relu output.
10496        let v = r.realize_f32();
10497        assert_eq!(v, vec![0.0, 0.5, 0.0, 2.0]);
10498    }
10499
10500    #[test]
10501    fn const_f64_like_round_trips() {
10502        let anchor = cpu_f32(vec![0.0], &[1]);
10503        let t = anchor.const_f64_like(vec![1.5, 2.5, 3.5], vec![3]).unwrap();
10504        assert_eq!(t.shape().dims(), &[3]);
10505        assert_eq!(t.dtype(), DType::F64);
10506        assert_eq!(t.realize_f64(), vec![1.5, 2.5, 3.5]);
10507    }
10508
10509    #[test]
10510    fn const_i64_like_round_trips() {
10511        let anchor = cpu_f32(vec![0.0], &[1]);
10512        let t = anchor.const_i64_like(vec![-1_i64, 2, -3], vec![3]).unwrap();
10513        assert_eq!(t.shape().dims(), &[3]);
10514        assert_eq!(t.dtype(), DType::I64);
10515    }
10516
10517    #[test]
10518    fn on_device_smoke_cpu() {
10519        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10520        let pinned = t.on_device(&Device::cpu());
10521        assert_eq!(pinned.realize_f32(), vec![1.0, 2.0]);
10522    }
10523
10524    #[test]
10525    fn copy_to_device_same_device_round_trips() {
10526        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
10527        let copied = t.copy_to_device(&Device::cpu());
10528        assert_eq!(copied.realize_f32(), vec![1.0, 2.0, 3.0]);
10529    }
10530}
10531
10532// ============================================================================
10533// Phase A.2 composite primitives tests.
10534// ============================================================================
10535#[cfg(test)]
10536mod phase_a2_composite_tests {
10537    use super::*;
10538
10539    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10540        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10541    }
10542
10543    #[test]
10544    fn transpose_last_two_swaps_last_two_dims() {
10545        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10546        let out = t.transpose_last_two().unwrap();
10547        assert_eq!(out.shape().dims(), &[3, 2]);
10548        assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
10549    }
10550
10551    #[test]
10552    fn t_is_alias_of_transpose_last_two() {
10553        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10554        assert_eq!(
10555            t.t().unwrap().realize_f32(),
10556            t.transpose_last_two().unwrap().realize_f32()
10557        );
10558    }
10559
10560    #[test]
10561    fn transpose_dims_swaps_arbitrary_axes() {
10562        let t = cpu_f32((0..24).map(|i| i as f32).collect(), &[2, 3, 4]);
10563        let out = t.transpose_dims(0, 2).unwrap();
10564        assert_eq!(out.shape().dims(), &[4, 3, 2]);
10565    }
10566
10567    #[test]
10568    fn transpose_dims_identity_when_same_axis() {
10569        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10570        let out = t.transpose_dims(0, 0).unwrap();
10571        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10572    }
10573
10574    #[test]
10575    fn transpose_dims_errors_out_of_bounds() {
10576        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10577        assert!(t.transpose_dims(0, 2).is_err());
10578        assert!(t.transpose_dims(5, 0).is_err());
10579    }
10580
10581    #[test]
10582    fn flatten_merges_middle_dims() {
10583        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10584        let out = t.flatten(0, 1).unwrap();
10585        assert_eq!(out.shape().dims(), &[6, 4]);
10586    }
10587
10588    #[test]
10589    fn flatten_to_merges_leading_dims() {
10590        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10591        let out = t.flatten_to(1).unwrap();
10592        assert_eq!(out.shape().dims(), &[6, 4]);
10593    }
10594
10595    #[test]
10596    fn flatten_from_merges_trailing_dims() {
10597        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10598        let out = t.flatten_from(1).unwrap();
10599        assert_eq!(out.shape().dims(), &[2, 12]);
10600    }
10601
10602    #[test]
10603    fn flatten_all_produces_rank_one() {
10604        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10605        let out = t.flatten_all().unwrap();
10606        assert_eq!(out.shape().dims(), &[6]);
10607        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
10608    }
10609
10610    /// `rope_batched` at `B == 1` must be **bit-identical** to
10611    /// `rope_with_tables_decomposed`, and each row at `B == 3` must equal the
10612    /// single-position result at that row's own position — the exactness proof
10613    /// for the per-row RoPE that unblocks ragged (non-uniform-position) batched
10614    /// decode. A subtly wrong rotate-half (wrong half split, wrong sign, wrong
10615    /// concat order) still produces plausible tokens, so this asserts
10616    /// bit-equality; the CONTROL proves the per-row table is load-bearing.
10617    /// (Adopted from the Lightbulb consumer's verified `rope_batched` oracle;
10618    /// the mechanism belongs in Fuel.)
10619    #[test]
10620    fn rope_batched_matches_single_position_rope_row_by_row() {
10621        let lcg = |n: usize, seed: u32| -> Vec<f32> {
10622            let mut s = seed;
10623            (0..n)
10624                .map(|_| {
10625                    s = s.wrapping_mul(1103515245).wrapping_add(12345);
10626                    ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.5
10627                })
10628                .collect()
10629        };
10630        let (b, heads, hd) = (3usize, 4usize, 8usize);
10631        let base = 10000.0f64;
10632        let positions = [0usize, 7, 3];
10633
10634        let x_data = lcg(b * heads * hd, 11);
10635        let x = cpu_f32(x_data.clone(), &[b, heads, 1, hd]);
10636        let (cos, sin) = x.rope_tables_const_batched(base, &positions, hd);
10637        let got = x.rope_batched(&cos, &sin).unwrap().realize_f32();
10638
10639        let per_row = heads * hd;
10640        for (row, &pos) in positions.iter().enumerate() {
10641            let row_data = x_data[row * per_row..(row + 1) * per_row].to_vec();
10642            let xr = cpu_f32(row_data, &[1, heads, 1, hd]);
10643            let (c, s) = xr.rope_tables_const(base, pos, 1, hd);
10644            let want = xr
10645                .rope_with_tables_decomposed(&c, &s)
10646                .unwrap()
10647                .realize_f32();
10648            assert_eq!(
10649                &got[row * per_row..(row + 1) * per_row],
10650                &want[..],
10651                "row {row} (position {pos}) != decomposed RoPE at that position",
10652            );
10653        }
10654
10655        // CONTROL: prove the per-row table is load-bearing. Give EVERY row
10656        // position 0 (row 0's position); rows at other positions must now
10657        // DISAGREE with their own-position result — else the comparison above is
10658        // blind to the whole per-row-position mechanism.
10659        let shared = [positions[0]; 3];
10660        let (c0, s0) = x.rope_tables_const_batched(base, &shared, hd);
10661        let wrong = x.rope_batched(&c0, &s0).unwrap().realize_f32();
10662        for (row, &pos) in positions.iter().enumerate().skip(1) {
10663            assert_ne!(
10664                &wrong[row * per_row..(row + 1) * per_row],
10665                &got[row * per_row..(row + 1) * per_row],
10666                "CONTROL: row {row} at shared position 0 matched its own position \
10667                 {pos} — per-row RoPE not applied, or comparison blind to it",
10668            );
10669        }
10670    }
10671
10672    #[test]
10673    fn flatten_errors_on_bad_range() {
10674        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10675        assert!(t.flatten(0, 5).is_err());
10676        assert!(t.flatten(2, 1).is_err()); // start > end
10677    }
10678
10679    #[test]
10680    fn split_heads_then_merge_heads_round_trip() {
10681        // (B=1, N=2, embed=6) — split into 2 heads of head_dim=3.
10682        let x = cpu_f32((0..12).map(|i| i as f32).collect(), &[1, 2, 6]);
10683        let split = x.split_heads(2, 3).unwrap();
10684        assert_eq!(split.shape().dims(), &[1, 2, 2, 3]);
10685        let merged = split.merge_heads().unwrap();
10686        assert_eq!(merged.shape().dims(), &[1, 2, 6]);
10687        let m = merged.realize_f32();
10688        let original = x.realize_f32();
10689        for (a, b) in m.iter().zip(original.iter()) {
10690            assert!((a - b).abs() < 1e-7, "{a} vs {b}");
10691        }
10692    }
10693
10694    #[test]
10695    fn rope_tables_const_shapes_and_anchoring() {
10696        let anchor = cpu_f32(vec![0.0_f32; 8], &[1, 4, 2]);
10697        let (cos, sin) = anchor.rope_tables_const(10_000.0, 0, 4, 8);
10698        assert_eq!(cos.shape().dims(), &[4, 8]);
10699        assert_eq!(sin.shape().dims(), &[4, 8]);
10700        // First row at position 0: cos = 1.0, sin = 0.0 for every pair.
10701        let cv = cos.realize_f32();
10702        let sv = sin.realize_f32();
10703        // cos[0,...] should all be 1.0 (RoPE at position 0).
10704        for i in 0..8 {
10705            assert!((cv[i] - 1.0).abs() < 1e-5, "cos[0,{i}] = {}", cv[i]);
10706            assert!(sv[i].abs() < 1e-5, "sin[0,{i}] = {}", sv[i]);
10707        }
10708    }
10709
10710    #[test]
10711    fn embed_tokens_shape_and_lookup() {
10712        // 5-token vocab, 3-dim hidden. Vocab embedding table contains
10713        // row i = (i, i+0.5, i+1) so the lookup result is verifiable.
10714        let vocab_size = 5;
10715        let hidden = 3;
10716        let table: Vec<f32> = (0..vocab_size)
10717            .flat_map(|i| vec![i as f32, i as f32 + 0.5, i as f32 + 1.0])
10718            .collect();
10719        let tokens = vec![1_u32, 3, 0];
10720        let out = Tensor::embed_tokens(
10721            std::sync::Arc::from(table),
10722            vocab_size,
10723            hidden,
10724            &tokens,
10725            &crate::Device::cpu(),
10726        )
10727        .unwrap();
10728        assert_eq!(out.shape().dims(), &[1, 3, hidden]);
10729        let v = out.realize_f32();
10730        let want = [
10731            1.0_f32, 1.5, 2.0, // token 1
10732            3.0, 3.5, 4.0, // token 3
10733            0.0, 0.5, 1.0, // token 0
10734        ];
10735        for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10736            assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10737        }
10738    }
10739
10740    #[test]
10741    fn embed_tokens_anchored_lives_on_receiver_graph() {
10742        // Two paths: one bootstrapped via embed_tokens, one anchored
10743        // on a pre-existing tensor. Both produce identical values,
10744        // but only the anchored one can compose with the anchor.
10745        let vocab_size = 4;
10746        let hidden = 2;
10747        let table: Vec<f32> = (0..vocab_size)
10748            .flat_map(|i| vec![i as f32, i as f32 * 2.0])
10749            .collect();
10750        let table_arc: std::sync::Arc<[f32]> = std::sync::Arc::from(table);
10751        let tokens = vec![2_u32, 1];
10752
10753        let anchor = cpu_f32(vec![0.0_f32], &[1]);
10754        let embedded = anchor
10755            .embed_tokens_anchored(
10756                std::sync::Arc::clone(&table_arc),
10757                vocab_size,
10758                hidden,
10759                &tokens,
10760            )
10761            .unwrap();
10762        assert_eq!(embedded.shape().dims(), &[1, 2, hidden]);
10763
10764        // Anchored: composes with the anchor.
10765        let one_scaled = anchor
10766            .const_f32_like(std::sync::Arc::from(vec![1.0_f32]), Shape::from_dims(&[1]))
10767            .unwrap();
10768        let _ = embedded
10769            .add(
10770                &one_scaled
10771                    .reshape(Shape::from_dims(&[1, 1, 1]))
10772                    .unwrap()
10773                    .broadcast_to(Shape::from_dims(&[1, 2, hidden]))
10774                    .unwrap(),
10775            )
10776            .unwrap();
10777        let v = embedded.realize_f32();
10778        let want = [
10779            2.0_f32, 4.0, // token 2
10780            1.0, 2.0, // token 1
10781        ];
10782        for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10783            assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10784        }
10785    }
10786
10787    #[test]
10788    fn embed_tokens_empty_returns_error() {
10789        let r = Tensor::embed_tokens(
10790            std::sync::Arc::from(vec![0.0_f32]),
10791            1,
10792            1,
10793            &[],
10794            &crate::Device::cpu(),
10795        );
10796        assert!(r.is_err());
10797    }
10798
10799    #[test]
10800    fn softcap_matches_tanh_form() {
10801        // Tiny input; verify cap·tanh(x/cap) at known points.
10802        let x = cpu_f32(vec![0.0_f32, 5.0, -5.0, 30.0], &[1, 4]);
10803        let capped = x.softcap(10.0).realize_f32();
10804        // tanh(0)=0; tanh(0.5)≈0.4621; tanh(-0.5)≈-0.4621; tanh(3)≈0.9951.
10805        let expect = [0.0_f32, 4.6212, -4.6212, 9.9505];
10806        for (i, (&got, &want)) in capped.iter().zip(expect.iter()).enumerate() {
10807            assert!(
10808                (got - want).abs() < 1e-3,
10809                "softcap[{i}] got={got} want={want}"
10810            );
10811        }
10812    }
10813
10814    #[test]
10815    fn softcap_optional_none_returns_input_unchanged() {
10816        let x = cpu_f32(vec![1.0_f32, -2.0, 30.0], &[1, 3]);
10817        let out = x.softcap_optional(None).realize_f32();
10818        let expect = [1.0_f32, -2.0, 30.0];
10819        for (g, w) in out.iter().zip(expect.iter()) {
10820            assert!((g - w).abs() < 1e-6);
10821        }
10822        // Some(0.0) or negative cap also returns unchanged (guard).
10823        let out = x.softcap_optional(Some(0.0)).realize_f32();
10824        for (g, w) in out.iter().zip(expect.iter()) {
10825            assert!((g - w).abs() < 1e-6);
10826        }
10827    }
10828
10829    #[test]
10830    fn rope_partial_full_dim_matches_rope_with_tables() {
10831        // head_dim == rope_dim ⇒ should degenerate to full rope.
10832        let qk = cpu_f32(vec![1.0_f32; 1 * 1 * 2 * 4], &[1, 1, 2, 4]);
10833        let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 2, 4);
10834        let via_partial = qk.rope_partial(&cos, &sin, 4).unwrap();
10835        let via_full = qk.rope_with_tables(&cos, &sin).unwrap();
10836        let a = via_partial.realize_f32();
10837        let b = via_full.realize_f32();
10838        for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate() {
10839            assert!((av - bv).abs() < 1e-6, "{i}: {av} vs {bv}");
10840        }
10841    }
10842
10843    #[test]
10844    fn rope_partial_pass_through_suffix_unchanged() {
10845        // rope_dim=2, head_dim=4 ⇒ first 2 features rotated, last 2
10846        // unchanged. At position 0 the rotation is identity, so all 4
10847        // features should equal the input.
10848        let qk = cpu_f32(
10849            vec![
10850                // shape [1, 1, 1, 4] — one position, one head
10851                1.0_f32, 2.0, 3.0, 4.0,
10852            ],
10853            &[1, 1, 1, 4],
10854        );
10855        let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 1, 2);
10856        let out = qk.rope_partial(&cos, &sin, 2).unwrap().realize_f32();
10857        for (i, &v) in out.iter().enumerate() {
10858            let expect = [1.0_f32, 2.0, 3.0, 4.0][i];
10859            assert!((v - expect).abs() < 1e-6, "{i}: {v} != {expect}");
10860        }
10861    }
10862
10863    #[test]
10864    fn add_optional_trailing_bias_none_returns_input_unchanged() {
10865        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10866        let original = a.realize_f32();
10867        let out = a.add_optional_trailing_bias(None).unwrap();
10868        assert_eq!(out.realize_f32(), original);
10869    }
10870
10871    #[test]
10872    fn add_optional_trailing_bias_some_applies_add() {
10873        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10874        let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, 20.0, 30.0]);
10875        let out = a.add_optional_trailing_bias(Some(&bias)).unwrap();
10876        assert_eq!(out.realize_f32(), vec![11.0, 22.0, 33.0]);
10877    }
10878
10879    #[test]
10880    fn add_trailing_bias_broadcasts_across_leading_dims() {
10881        // (2, 3) input + length-3 bias should add per-column.
10882        let x = cpu_f32(vec![1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0], &[2, 3]);
10883        let bias = std::sync::Arc::<[f32]>::from(vec![100.0_f32, 200.0, 300.0]);
10884        let out = x.add_trailing_bias(bias).unwrap();
10885        assert_eq!(out.shape().dims(), &[2, 3]);
10886        let v = out.realize_f32();
10887        assert_eq!(v, vec![101.0, 202.0, 303.0, 110.0, 220.0, 330.0]);
10888    }
10889
10890    #[test]
10891    fn rms_norm_affine_with_offset_adds_offset_to_each_gain() {
10892        let x = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10893        let gain_raw: [f32; 3] = [-0.5, 0.0, 0.5];
10894        let via_offset = x.rms_norm_affine_with_offset(&gain_raw, 1.0, 1e-6).unwrap();
10895        let gain_shifted = std::sync::Arc::<[f32]>::from(vec![0.5_f32, 1.0, 1.5]);
10896        let via_plain = x.rms_norm_affine(gain_shifted, 1e-6).unwrap();
10897        let a = via_offset.realize_f32();
10898        let b = via_plain.realize_f32();
10899        for (x, y) in a.iter().zip(b.iter()) {
10900            assert!((x - y).abs() < 1e-6, "{x} vs {y}");
10901        }
10902    }
10903
10904    #[test]
10905    fn global_avg_pool_2d_averages_spatial_dims() {
10906        // (1, 2, 2, 3) — two channels, 2×3 spatial.
10907        // Channel 0: 1..=6, mean = 3.5.
10908        // Channel 1: 10, 20, 30, 40, 50, 60, mean = 35.
10909        let x = cpu_f32(
10910            vec![
10911                1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0,
10912            ],
10913            &[1, 2, 2, 3],
10914        );
10915        let out = x.global_avg_pool_2d().unwrap();
10916        assert_eq!(out.shape().dims(), &[1, 2]);
10917        let v = out.realize_f32();
10918        assert!((v[0] - 3.5).abs() < 1e-5);
10919        assert!((v[1] - 35.0).abs() < 1e-4);
10920    }
10921
10922    #[test]
10923    fn channel_affine_4d_applies_per_channel_gain_and_bias() {
10924        // (1, 2, 2, 2) — two channels, each a 2×2 spatial map.
10925        let x = cpu_f32(
10926            vec![
10927                1.0_f32, 2.0, 3.0, 4.0, // channel 0
10928                10.0, 20.0, 30.0, 40.0, // channel 1
10929            ],
10930            &[1, 2, 2, 2],
10931        );
10932        let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5]);
10933        let bias = std::sync::Arc::<[f32]>::from(vec![1.0_f32, -10.0]);
10934        let out = x.channel_affine_4d(gain, bias).unwrap();
10935        let v = out.realize_f32();
10936        // Channel 0: gain=2, bias=1 → 2x+1
10937        assert_eq!(&v[0..4], &[3.0, 5.0, 7.0, 9.0]);
10938        // Channel 1: gain=0.5, bias=-10 → 0.5x-10
10939        assert_eq!(&v[4..8], &[-5.0, 0.0, 5.0, 10.0]);
10940    }
10941
10942    #[test]
10943    fn additive_causal_mask_has_strict_lower_triangle() {
10944        let anchor = cpu_f32(vec![0.0_f32], &[1]);
10945        let mask = Tensor::additive_causal_mask_like(&anchor, 4);
10946        assert_eq!(mask.shape().dims(), &[4, 4]);
10947        let v = mask.realize_f32();
10948        // Expected (-inf shown as 'x'):
10949        //   0 x x x
10950        //   0 0 x x
10951        //   0 0 0 x
10952        //   0 0 0 0
10953        for i in 0..4 {
10954            for j in 0..4 {
10955                let got = v[i * 4 + j];
10956                if j > i {
10957                    assert!(
10958                        got.is_infinite() && got.is_sign_negative(),
10959                        "above-diag (i={i}, j={j}) should be -inf, got {got}"
10960                    );
10961                } else {
10962                    assert_eq!(
10963                        got, 0.0,
10964                        "on/below-diag (i={i}, j={j}) should be 0, got {got}"
10965                    );
10966                }
10967            }
10968        }
10969    }
10970
10971    #[test]
10972    fn layer_norm_affine_unit_gain_zero_bias_matches_layer_norm_last_dim() {
10973        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10974        let gain = std::sync::Arc::<[f32]>::from(vec![1.0_f32; 3]);
10975        let bias = std::sync::Arc::<[f32]>::from(vec![0.0_f32; 3]);
10976        let out_affine = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10977        let out_plain = a.layer_norm_last_dim(1e-5).unwrap();
10978        let va = out_affine.realize_f32();
10979        let vp = out_plain.realize_f32();
10980        for (a, b) in va.iter().zip(vp.iter()) {
10981            assert!((a - b).abs() < 1e-5, "{a} vs {b}");
10982        }
10983    }
10984
10985    #[test]
10986    fn layer_norm_affine_applies_gain_and_bias() {
10987        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10988        let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5, 1.5]);
10989        let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, -5.0, 0.0]);
10990        let out = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10991        let v = out.realize_f32();
10992        // Manual: mean=2, var=2/3; normed = (x-2)/sqrt(2/3+1e-5).
10993        let mean = 2.0_f32;
10994        let var = ((1.0 - mean).powi(2) + (2.0 - mean).powi(2) + (3.0 - mean).powi(2)) / 3.0;
10995        let den = (var + 1e-5_f32).sqrt();
10996        let expected = [
10997            ((1.0 - mean) / den) * 2.0 + 10.0,
10998            ((2.0 - mean) / den) * 0.5 + (-5.0),
10999            ((3.0 - mean) / den) * 1.5 + 0.0,
11000        ];
11001        for (got, want) in v.iter().zip(expected.iter()) {
11002            assert!((got - want).abs() < 1e-4, "{got} vs {want}");
11003        }
11004    }
11005
11006    #[test]
11007    fn l2_normalize_last_dim_unit_norm_per_row() {
11008        // (2, 3): rows [3,4,0] (norm 5) and [1,2,2] (norm 3).
11009        let a = cpu_f32(vec![3.0, 4.0, 0.0, 1.0, 2.0, 2.0], &[2, 3]);
11010        let out = a.l2_normalize(1_usize, 1e-12).unwrap();
11011        assert_eq!(out.shape().dims(), &[2, 3]);
11012        let v = out.realize_f32();
11013        let row0_norm = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
11014        let row1_norm = (v[3] * v[3] + v[4] * v[4] + v[5] * v[5]).sqrt();
11015        assert!((row0_norm - 1.0).abs() < 1e-5, "row 0 norm = {row0_norm}");
11016        assert!((row1_norm - 1.0).abs() < 1e-5, "row 1 norm = {row1_norm}");
11017        // Row 0: [3,4,0]/5 → [0.6, 0.8, 0.0].
11018        assert!((v[0] - 0.6).abs() < 1e-5);
11019        assert!((v[1] - 0.8).abs() < 1e-5);
11020        assert!(v[2].abs() < 1e-5);
11021    }
11022
11023    #[test]
11024    fn l2_normalize_eps_zero_works_when_nonzero() {
11025        let a = cpu_f32(vec![1.0_f32, 0.0], &[2]);
11026        let out = a.l2_normalize(0_usize, 0.0).unwrap();
11027        let v = out.realize_f32();
11028        assert!((v[0] - 1.0).abs() < 1e-6);
11029        assert!(v[1].abs() < 1e-6);
11030    }
11031
11032    #[test]
11033    fn repeat_interleave_last_dim_matches_torch_semantics() {
11034        // (2, 3) input: rows [1,2,3] and [4,5,6]. dim=1, repeats=2
11035        // → each element becomes two consecutive copies:
11036        // (2, 6): [1,1,2,2,3,3] and [4,4,5,5,6,6].
11037        let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11038        let out = a.repeat_interleave(1_usize, 2).unwrap();
11039        assert_eq!(out.shape().dims(), &[2, 6]);
11040        assert_eq!(
11041            out.realize_f32(),
11042            vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 6.0, 6.0]
11043        );
11044    }
11045
11046    #[test]
11047    fn repeat_interleave_middle_dim() {
11048        // (2, 2, 2) input. dim=1, repeats=3 → (2, 6, 2).
11049        let a = cpu_f32((0..8).map(|i| i as f32).collect(), &[2, 2, 2]);
11050        let out = a.repeat_interleave(1_usize, 3).unwrap();
11051        assert_eq!(out.shape().dims(), &[2, 6, 2]);
11052        // First sample's elements: (0,1) repeated 3× then (2,3) repeated 3×.
11053        let v = out.realize_f32();
11054        assert_eq!(&v[0..6], &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
11055        assert_eq!(&v[6..12], &[2.0, 3.0, 2.0, 3.0, 2.0, 3.0]);
11056    }
11057
11058    #[test]
11059    fn repeat_interleave_repeats_one_is_noop() {
11060        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11061        let out = a.repeat_interleave(0_usize, 1).unwrap();
11062        assert_eq!(out.shape().dims(), &[3]);
11063        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11064    }
11065
11066    #[test]
11067    fn repeat_interleave_repeats_zero_errors() {
11068        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11069        assert!(a.repeat_interleave(0_usize, 0).is_err());
11070    }
11071
11072    #[test]
11073    fn stack_adds_leading_dim() {
11074        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11075        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11076        let out = Tensor::stack(&[&a, &b], 0).unwrap();
11077        assert_eq!(out.shape().dims(), &[2, 3]);
11078        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
11079    }
11080
11081    #[test]
11082    fn stack_adds_trailing_dim() {
11083        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11084        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11085        let out = Tensor::stack(&[&a, &b], 1).unwrap();
11086        assert_eq!(out.shape().dims(), &[3, 2]);
11087        assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
11088    }
11089
11090    #[test]
11091    fn stack_rejects_mismatched_shapes() {
11092        let a = cpu_f32(vec![1.0, 2.0], &[2]);
11093        let b = a.const_f32_like(vec![3.0, 4.0, 5.0], vec![3]).unwrap();
11094        assert!(Tensor::stack(&[&a, &b], 0).is_err());
11095    }
11096
11097    #[test]
11098    fn stack_rejects_empty_input() {
11099        let result = Tensor::stack(&[], 0);
11100        assert!(result.is_err());
11101    }
11102
11103    #[test]
11104    fn repeat_tiles_along_each_dim() {
11105        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11106        let out = t.repeat(vec![3]).unwrap();
11107        assert_eq!(out.shape().dims(), &[6]);
11108        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 1.0, 2.0, 1.0, 2.0]);
11109    }
11110
11111    #[test]
11112    fn repeat_extends_rank_when_needed() {
11113        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11114        // repeat with shape [3, 2] left-pads tensor to [1, 2] then tiles to [3, 4]
11115        let out = t.repeat(vec![3, 2]).unwrap();
11116        assert_eq!(out.shape().dims(), &[3, 4]);
11117    }
11118
11119    #[test]
11120    fn repeat_identity_with_all_ones() {
11121        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11122        let out = t.repeat(vec![1]).unwrap();
11123        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11124    }
11125}
11126
11127// ============================================================================
11128// Phase A.3 keepdim reduction tests.
11129// ============================================================================
11130#[cfg(test)]
11131mod phase_a3_keepdim_tests {
11132    use super::*;
11133
11134    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11135        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11136    }
11137
11138    #[test]
11139    fn sum_keepdim_preserves_dim_as_one() {
11140        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11141        let out = t.sum_keepdim(1_usize).unwrap();
11142        assert_eq!(out.shape().dims(), &[2, 1]);
11143        assert_eq!(out.realize_f32(), vec![3.0, 7.0]);
11144    }
11145
11146    #[test]
11147    fn mean_keepdim_preserves_dim_as_one() {
11148        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11149        let out = t.mean_keepdim(0_usize).unwrap();
11150        assert_eq!(out.shape().dims(), &[1, 2]);
11151        assert_eq!(out.realize_f32(), vec![2.0, 3.0]);
11152    }
11153
11154    #[test]
11155    fn max_keepdim_preserves_dim_as_one() {
11156        let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11157        let out = t.max_keepdim(1_usize).unwrap();
11158        assert_eq!(out.shape().dims(), &[2, 1]);
11159        assert_eq!(out.realize_f32(), vec![3.0, 4.0]);
11160    }
11161
11162    #[test]
11163    fn min_keepdim_preserves_dim_as_one() {
11164        let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11165        let out = t.min_keepdim(1_usize).unwrap();
11166        assert_eq!(out.shape().dims(), &[2, 1]);
11167        assert_eq!(out.realize_f32(), vec![1.0, 2.0]);
11168    }
11169
11170    // ---- the divisor clamps at zero: var = sum((x-mean)^2) / max(0, n - correction) ----
11171    // (ruling 2026-11-25, torch): extent == correction -> 0/0 = NaN; extent < correction -> x/0 =
11172    // inf (NaN if the sum is 0); NEVER negative. Before, `correction > n` gave a finite, possibly
11173    // NEGATIVE variance ([1,3] with correction 3 was -2.0).
11174
11175    /// `var(dim, correction)` of `data` (given as f64) in the named dtype, realized as f64.
11176    fn var_in(dtype: &str, data: &[f64], shape: &[usize], dim: usize, correction: f64) -> Vec<f64> {
11177        let dev = Device::cpu();
11178        let s = Shape::from_dims(shape);
11179        match dtype {
11180            "f32" => Tensor::from_f32(data.iter().map(|&x| x as f32).collect::<Vec<_>>(), s, &dev)
11181                .unwrap()
11182                .var(dim, correction)
11183                .unwrap()
11184                .realize_f32()
11185                .iter()
11186                .map(|&x| x as f64)
11187                .collect(),
11188            "f64" => Tensor::from_f64(data.to_vec(), s, &dev)
11189                .unwrap()
11190                .var(dim, correction)
11191                .unwrap()
11192                .realize_f64(),
11193            "f16" => Tensor::from_f16(
11194                data.iter()
11195                    .map(|&x| half::f16::from_f64(x))
11196                    .collect::<Vec<_>>(),
11197                s,
11198                &dev,
11199            )
11200            .unwrap()
11201            .var(dim, correction)
11202            .unwrap()
11203            .realize_f16()
11204            .iter()
11205            .map(|x| x.to_f64())
11206            .collect(),
11207            "bf16" => Tensor::from_bf16(
11208                data.iter()
11209                    .map(|&x| half::bf16::from_f64(x))
11210                    .collect::<Vec<_>>(),
11211                s,
11212                &dev,
11213            )
11214            .unwrap()
11215            .var(dim, correction)
11216            .unwrap()
11217            .realize_bf16()
11218            .iter()
11219            .map(|x| x.to_f64())
11220            .collect(),
11221            other => panic!("dtype {other}"),
11222        }
11223    }
11224
11225    /// PIP #715 L2: a NaN correction is a typed error, never a silently clamped zero divisor (`inf`).
11226    #[test]
11227    fn var_rejects_a_nan_correction() {
11228        let dev = Device::cpu();
11229        let x = Tensor::from_f32(vec![1.0, 3.0], Shape::from_dims(&[2]), &dev).unwrap();
11230        assert!(x.var_keepdim(0, f64::NAN).is_err());
11231        // control: the same call with a finite correction succeeds
11232        assert!(x.var_keepdim(0, 1.0).is_ok());
11233    }
11234
11235    #[test]
11236    fn var_divisor_is_clamped_at_zero_in_every_dtype() {
11237        for dt in ["f32", "f64", "f16", "bf16"] {
11238            // extent == correction: 0/0 = NaN
11239            assert!(var_in(dt, &[5.0], &[1], 0, 1.0)[0].is_nan(), "{dt} [5] c=1");
11240            let v = var_in(dt, &[5.0, 7.0], &[2, 1], 1, 1.0);
11241            assert!(v[0].is_nan() && v[1].is_nan(), "{dt} [[5],[7]] c=1: {v:?}");
11242            // extent == correction with a nonzero sum: x/0 = inf
11243            assert_eq!(
11244                var_in(dt, &[1.0, 3.0], &[2], 0, 2.0)[0],
11245                f64::INFINITY,
11246                "{dt} [1,3] c=2"
11247            );
11248            // extent < correction: a zero sum is NaN, a nonzero sum is inf, NEVER negative
11249            assert!(var_in(dt, &[5.0], &[1], 0, 2.0)[0].is_nan(), "{dt} [5] c=2");
11250            assert_eq!(
11251                var_in(dt, &[1.0, 3.0], &[2], 0, 3.0)[0],
11252                f64::INFINITY,
11253                "{dt} [1,3] c=3"
11254            );
11255            // controls: population variance of one element is 0; Bessel on two is 2
11256            assert_eq!(var_in(dt, &[5.0], &[1], 0, 0.0)[0], 0.0, "{dt} [5] c=0");
11257            assert_eq!(
11258                var_in(dt, &[1.0, 3.0], &[2], 0, 1.0)[0],
11259                2.0,
11260                "{dt} [1,3] c=1"
11261            );
11262        }
11263    }
11264
11265    #[test]
11266    fn var_matches_unbiased_formula_with_correction_1() {
11267        // [[1,2,3],[4,5,6]] -> var along axis 1: each row has mean=mid, dev=[-1,0,1], sq sum=2, /(3-1) = 1
11268        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11269        let out = t.var(1, 1.0).unwrap();
11270        assert_eq!(out.shape().dims(), &[2]);
11271        let v = out.realize_f32();
11272        assert!((v[0] - 1.0).abs() < 1e-5, "var row 0 = {} != 1.0", v[0]);
11273        assert!((v[1] - 1.0).abs() < 1e-5, "var row 1 = {} != 1.0", v[1]);
11274    }
11275
11276    /// KISS-Ops §6.13 S14: `correction = 0.0` (the spec default, numpy's
11277    /// default) divides by `n` instead of `n - 1` -- same fixture as the
11278    /// Bessel test above, different divisor, so the two tests pin BOTH
11279    /// halves of the explicit-attribute contract against the same data.
11280    #[test]
11281    fn var_population_with_correction_0() {
11282        // Same fixture: dev=[-1,0,1], sq sum=2, /3 = 0.666...
11283        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11284        let out = t.var(1, 0.0).unwrap();
11285        let v = out.realize_f32();
11286        let want = 2.0 / 3.0;
11287        assert!(
11288            (v[0] - want).abs() < 1e-5,
11289            "population var row 0 = {} != {want}",
11290            v[0]
11291        );
11292        assert!(
11293            (v[1] - want).abs() < 1e-5,
11294            "population var row 1 = {} != {want}",
11295            v[1]
11296        );
11297    }
11298
11299    #[test]
11300    fn var_keepdim_preserves_dim() {
11301        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11302        let out = t.var_keepdim(1, 1.0).unwrap();
11303        assert_eq!(out.shape().dims(), &[2, 1]);
11304    }
11305
11306    #[test]
11307    fn var_errors_out_of_bounds() {
11308        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11309        assert!(t.var(3, 1.0).is_err());
11310        assert!(t.var_keepdim(3, 1.0).is_err());
11311    }
11312}
11313
11314// ============================================================================
11315// Phase A.4 scalar/binary composite tests.
11316// ============================================================================
11317#[cfg(test)]
11318mod phase_a4_composite_tests {
11319    use super::*;
11320
11321    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11322        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11323    }
11324
11325    #[test]
11326    fn affine_applies_mul_then_add() {
11327        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11328        let out = t.affine(2.0, 10.0);
11329        assert_eq!(out.realize_f32(), vec![12.0, 14.0, 16.0]);
11330    }
11331
11332    #[test]
11333    fn scale_and_shift_alias_of_affine() {
11334        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11335        assert_eq!(
11336            t.scale_and_shift(2.0, 10.0).realize_f32(),
11337            t.affine(2.0, 10.0).realize_f32(),
11338        );
11339    }
11340
11341    #[test]
11342    fn elu_matches_reference_values() {
11343        let t = cpu_f32(vec![1.0, 0.0, -1.0, -2.0], &[4]);
11344        let out = t.elu(1.0);
11345        let v = out.realize_f32();
11346        // x > 0: identity. x == 0: 0 (boundary; gt returns 0 → neg branch which is alpha*(1-1)=0).
11347        // x < 0: alpha * (exp(x) - 1).
11348        assert!((v[0] - 1.0).abs() < 1e-5);
11349        assert!(v[1].abs() < 1e-5);
11350        assert!((v[2] - ((-1.0_f32).exp() - 1.0)).abs() < 1e-5);
11351        assert!((v[3] - ((-2.0_f32).exp() - 1.0)).abs() < 1e-5);
11352    }
11353
11354    #[test]
11355    fn dot_of_rank_one_vectors() {
11356        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11357        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11358        let out = a.dot(&b).unwrap();
11359        assert_eq!(out.shape().elem_count(), 1);
11360        let v = out.realize_f32();
11361        assert_eq!(v[0], 32.0); // 1*4 + 2*5 + 3*6
11362    }
11363
11364    #[test]
11365    fn dot_rejects_non_rank_one() {
11366        let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11367        let b = a
11368            .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])
11369            .unwrap();
11370        assert!(a.dot(&b).is_err());
11371    }
11372
11373    #[test]
11374    fn dot_rejects_length_mismatch() {
11375        let a = cpu_f32(vec![1.0, 2.0], &[2]);
11376        let b = a.const_f32_like(vec![1.0, 2.0, 3.0], vec![3]).unwrap();
11377        assert!(a.dot(&b).is_err());
11378    }
11379
11380    #[test]
11381    fn mv_matrix_times_vector() {
11382        let m = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11383        let v = m.const_f32_like(vec![1.0, 1.0, 1.0], vec![3]).unwrap();
11384        let out = m.mv(&v).unwrap();
11385        assert_eq!(out.shape().dims(), &[2]);
11386        assert_eq!(out.realize_f32(), vec![6.0, 15.0]);
11387    }
11388
11389    #[test]
11390    fn matvec_is_mv_alias() {
11391        let m = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11392        let v = m.const_f32_like(vec![3.0, 4.0], vec![2]).unwrap();
11393        let a = m.mv(&v).unwrap().realize_f32();
11394        let b = m.matvec(&v).unwrap().realize_f32();
11395        assert_eq!(a, b);
11396    }
11397
11398    #[test]
11399    fn mv_rejects_shape_mismatch() {
11400        let m = cpu_f32(vec![1.0; 6], &[2, 3]);
11401        let v = m.const_f32_like(vec![1.0, 1.0], vec![2]).unwrap();
11402        assert!(m.mv(&v).is_err());
11403    }
11404
11405    #[test]
11406    fn broadcast_matmul_passes_through_to_matmul() {
11407        let a = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11408        let b = a
11409            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
11410            .unwrap();
11411        let out = a.broadcast_matmul(&b).unwrap();
11412        assert_eq!(out.realize_f32(), vec![5.0, 6.0, 7.0, 8.0]);
11413    }
11414}
11415
11416// ============================================================================
11417// Phase A.5 factory family tests.
11418// ============================================================================
11419#[cfg(test)]
11420mod phase_a5_factory_tests {
11421    use super::*;
11422
11423    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11424        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11425    }
11426
11427    #[test]
11428    fn ones_like_matches_shape_dtype_graph() {
11429        let t = cpu_f32(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
11430        let ones = t.ones_like().unwrap();
11431        assert_eq!(ones.shape().dims(), t.shape().dims());
11432        assert_eq!(ones.dtype(), t.dtype());
11433        assert_eq!(ones.realize_f32(), vec![1.0; 4]);
11434    }
11435
11436    #[test]
11437    fn zeros_like_matches_shape_dtype_graph() {
11438        let t = cpu_f32(vec![5.0, 6.0, 7.0], &[3]);
11439        let zeros = t.zeros_like().unwrap();
11440        assert_eq!(zeros.realize_f32(), vec![0.0; 3]);
11441    }
11442
11443    #[test]
11444    fn static_ones_f32() {
11445        let t = Tensor::ones(vec![2, 3], DType::F32, &Device::cpu()).unwrap();
11446        assert_eq!(t.shape().dims(), &[2, 3]);
11447        assert_eq!(t.realize_f32(), vec![1.0; 6]);
11448    }
11449
11450    #[test]
11451    fn static_zeros_f64() {
11452        let t = Tensor::zeros(vec![4], DType::F64, &Device::cpu()).unwrap();
11453        assert_eq!(t.dtype(), DType::F64);
11454        assert_eq!(t.realize_f64(), vec![0.0; 4]);
11455    }
11456
11457    #[test]
11458    fn full_with_f32_scalar() {
11459        let t = Tensor::full(vec![5], fuel_ir::Scalar::F32(2.5), &Device::cpu()).unwrap();
11460        assert_eq!(t.realize_f32(), vec![2.5; 5]);
11461    }
11462
11463    #[test]
11464    fn eye_identity_matrix() {
11465        let t = Tensor::eye(3, DType::F32, &Device::cpu());
11466        assert_eq!(t.shape().dims(), &[3, 3]);
11467        assert_eq!(
11468            t.realize_f32(),
11469            vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11470        );
11471    }
11472
11473    #[test]
11474    fn tril2_lower_triangular_ones() {
11475        let t = Tensor::tril2(3, DType::F32, &Device::cpu());
11476        assert_eq!(
11477            t.realize_f32(),
11478            vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0],
11479        );
11480    }
11481
11482    #[test]
11483    fn triu2_upper_triangular_ones() {
11484        let t = Tensor::triu2(3, DType::F32, &Device::cpu());
11485        assert_eq!(
11486            t.realize_f32(),
11487            vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
11488        );
11489    }
11490
11491    #[test]
11492    fn meshgrid_ij_indexing_two_inputs() {
11493        let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11494        let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11495        let grids = Tensor::meshgrid(&[&x, &y], false).unwrap();
11496        assert_eq!(grids.len(), 2);
11497        // ij: shapes are [len(x), len(y)] = [3, 2].
11498        assert_eq!(grids[0].shape().dims(), &[3, 2]);
11499        assert_eq!(grids[1].shape().dims(), &[3, 2]);
11500        // X grid: each row repeats x's value, so each row is identical along axis 1.
11501        assert_eq!(grids[0].realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
11502        // Y grid: each column repeats y's value, so each column is identical along axis 0.
11503        assert_eq!(grids[1].realize_f32(), vec![4.0, 5.0, 4.0, 5.0, 4.0, 5.0]);
11504    }
11505
11506    #[test]
11507    fn meshgrid_xy_indexing_swaps_first_two() {
11508        let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11509        let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11510        let grids = Tensor::meshgrid(&[&x, &y], true).unwrap();
11511        // xy: shapes flip to [len(y), len(x)] = [2, 3].
11512        assert_eq!(grids[0].shape().dims(), &[2, 3]);
11513        assert_eq!(grids[1].shape().dims(), &[2, 3]);
11514        // X grid: same row twice, each row is x.
11515        assert_eq!(grids[0].realize_f32(), vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
11516        // Y grid: each row repeats one y element.
11517        assert_eq!(grids[1].realize_f32(), vec![4.0, 4.0, 4.0, 5.0, 5.0, 5.0]);
11518    }
11519
11520    #[test]
11521    fn meshgrid_rejects_single_input() {
11522        let x = Tensor::from_f32(vec![1.0_f32, 2.0], vec![2], &Device::cpu()).unwrap();
11523        assert!(Tensor::meshgrid(&[&x], false).is_err());
11524    }
11525
11526    #[test]
11527    fn meshgrid_rejects_non_rank_one() {
11528        let x = Tensor::from_f32(vec![1.0; 4], vec![2, 2], &Device::cpu()).unwrap();
11529        let y = x.const_f32_like(vec![1.0, 2.0], vec![2]).unwrap();
11530        assert!(Tensor::meshgrid(&[&x, &y], false).is_err());
11531    }
11532
11533    // ---- additional deferred-Phase-A item tests ----
11534
11535    #[test]
11536    fn narrow_is_slice_alias() {
11537        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]);
11538        let a = t.narrow(0, 1, 3).unwrap().realize_f32();
11539        let b = t.slice(0, 1, 3).unwrap().realize_f32();
11540        assert_eq!(a, b);
11541        assert_eq!(a, vec![2.0, 3.0, 4.0]);
11542    }
11543
11544    #[test]
11545    fn chunk_splits_evenly() {
11546        let t = cpu_f32((1..=6).map(|i| i as f32).collect(), &[6]);
11547        let parts = t.chunk(3, 0).unwrap();
11548        assert_eq!(parts.len(), 3);
11549        assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0]);
11550        assert_eq!(parts[1].realize_f32(), vec![3.0, 4.0]);
11551        assert_eq!(parts[2].realize_f32(), vec![5.0, 6.0]);
11552    }
11553
11554    #[test]
11555    fn chunk_distributes_remainder_to_leading() {
11556        // size 7, 3 chunks → first 7%3=1 chunk gets the extra: sizes 3, 2, 2
11557        let t = cpu_f32((1..=7).map(|i| i as f32).collect(), &[7]);
11558        let parts = t.chunk(3, 0).unwrap();
11559        assert_eq!(parts.len(), 3);
11560        assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0, 3.0]);
11561        assert_eq!(parts[1].realize_f32(), vec![4.0, 5.0]);
11562        assert_eq!(parts[2].realize_f32(), vec![6.0, 7.0]);
11563    }
11564
11565    #[test]
11566    fn chunk_returns_singletons_when_size_less_than_chunks() {
11567        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11568        let parts = t.chunk(5, 0).unwrap();
11569        assert_eq!(parts.len(), 2);
11570        assert_eq!(parts[0].realize_f32(), vec![1.0]);
11571        assert_eq!(parts[1].realize_f32(), vec![2.0]);
11572    }
11573
11574    #[test]
11575    fn get_at_first_dim() {
11576        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11577        let row1 = t.get(1).unwrap();
11578        assert_eq!(row1.shape().dims(), &[2]);
11579        assert_eq!(row1.realize_f32(), vec![3.0, 4.0]);
11580    }
11581
11582    #[test]
11583    fn get_on_dim_arbitrary_axis() {
11584        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11585        let col0 = t.get_on_dim(1, 0).unwrap();
11586        assert_eq!(col0.shape().dims(), &[3]);
11587        assert_eq!(col0.realize_f32(), vec![1.0, 3.0, 5.0]);
11588    }
11589
11590    #[test]
11591    fn sum_dims_multi_dim_reduces_to_smaller() {
11592        // [2,3,4] sum over (0, 2) → [3]
11593        let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11594        let s = t.sum_dims([0, 2_usize]).unwrap();
11595        assert_eq!(s.shape().dims(), &[3]);
11596        // each element is 2*4 = 8 (sum across dim 0 = 2 elements, dim 2 = 4 elements)
11597        assert_eq!(s.realize_f32(), vec![8.0; 3]);
11598    }
11599
11600    #[test]
11601    fn mean_dims_multi_dim() {
11602        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11603        let m = t.mean_dims([0, 1_usize]).unwrap();
11604        assert_eq!(m.shape().dims(), &[] as &[usize]);
11605        assert_eq!(m.realize_f32(), vec![2.5]);
11606    }
11607
11608    #[test]
11609    fn sum_dims_keepdim_preserves_rank() {
11610        let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11611        let s = t.sum_dims_keepdim(&[0, 2]).unwrap();
11612        assert_eq!(s.shape().dims(), &[1, 3, 1]);
11613    }
11614
11615    #[test]
11616    fn mean_dims_keepdim_preserves_rank() {
11617        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11618        let m = t.mean_dims_keepdim(&[0, 1]).unwrap();
11619        assert_eq!(m.shape().dims(), &[1, 1]);
11620        assert_eq!(m.realize_f32(), vec![2.5]);
11621    }
11622
11623    #[test]
11624    fn rand_like_matches_shape_dtype() {
11625        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
11626        let r = t.rand_like(-1.0, 1.0).unwrap();
11627        assert_eq!(r.shape().dims(), t.shape().dims());
11628        assert_eq!(r.dtype(), t.dtype());
11629        // Every sample must be in [-1, 1).
11630        for v in r.realize_f32() {
11631            assert!((-1.0..1.0).contains(&v), "sample {v} out of [-1, 1)");
11632        }
11633    }
11634
11635    #[test]
11636    fn randn_like_matches_shape_dtype() {
11637        let t = cpu_f32(vec![0.0; 4], &[4]);
11638        let r = t.randn_like(0.0, 1.0).unwrap();
11639        assert_eq!(r.shape().dims(), &[4]);
11640        assert_eq!(r.dtype(), DType::F32);
11641        // Samples are random — just sanity-check they're finite.
11642        for v in r.realize_f32() {
11643            assert!(v.is_finite());
11644        }
11645    }
11646
11647    #[test]
11648    fn static_rand_f32() {
11649        let t = Tensor::rand(vec![100], 0.0, 1.0, DType::F32, &Device::cpu()).unwrap();
11650        let v = t.realize_f32();
11651        // Mean of uniform [0,1) should be ~0.5; tolerate sample noise.
11652        let mean: f32 = v.iter().sum::<f32>() / v.len() as f32;
11653        assert!((0.3..0.7).contains(&mean), "mean {mean} too far from 0.5");
11654    }
11655
11656    #[test]
11657    fn static_randn_f64() {
11658        let t = Tensor::randn(vec![1000], 0.0, 1.0, DType::F64, &Device::cpu()).unwrap();
11659        let v = t.realize_f64();
11660        let mean: f64 = v.iter().sum::<f64>() / v.len() as f64;
11661        // Normal(0,1) mean should be near 0; n=1000 gives stderr ~0.03.
11662        assert!(mean.abs() < 0.2, "mean {mean} too far from 0");
11663    }
11664
11665    #[test]
11666    fn arange_int_step() {
11667        let t = Tensor::arange(0.0, 5.0, &Device::cpu());
11668        assert_eq!(t.shape().dims(), &[5]);
11669        assert_eq!(t.realize_f32(), vec![0.0, 1.0, 2.0, 3.0, 4.0]);
11670    }
11671
11672    #[test]
11673    fn arange_step_fractional() {
11674        let t = Tensor::arange_step(2.0, 4.0, 0.5, &Device::cpu());
11675        assert_eq!(t.realize_f32(), vec![2.0, 2.5, 3.0, 3.5]);
11676    }
11677
11678    #[test]
11679    fn arange_step_negative_descends() {
11680        let t = Tensor::arange_step(5.0, 0.0, -1.0, &Device::cpu());
11681        assert_eq!(t.realize_f32(), vec![5.0, 4.0, 3.0, 2.0, 1.0]);
11682    }
11683
11684    #[test]
11685    fn linspace_includes_endpoints() {
11686        let t = Tensor::linspace(0.0, 1.0, 5, &Device::cpu());
11687        assert_eq!(t.shape().dims(), &[5]);
11688        let v = t.realize_f32();
11689        assert!((v[0] - 0.0).abs() < 1e-6);
11690        assert!((v[4] - 1.0).abs() < 1e-6);
11691        assert!((v[2] - 0.5).abs() < 1e-6);
11692    }
11693
11694    #[test]
11695    fn linspace_n_one_returns_start() {
11696        let t = Tensor::linspace(7.0, 99.0, 1, &Device::cpu());
11697        assert_eq!(t.realize_f32(), vec![7.0]);
11698    }
11699
11700    #[test]
11701    fn norm_is_sqrt_sum_sq() {
11702        let t = Tensor::from_f32(vec![3.0_f32, 4.0], vec![2], &Device::cpu()).unwrap();
11703        let n = t.norm();
11704        assert!((n.realize_f32()[0] - 5.0).abs() < 1e-6);
11705    }
11706
11707    #[test]
11708    fn pad_with_zeros_left_and_right() {
11709        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11710        let p = t.pad_with_zeros(0, 2, 1).unwrap();
11711        assert_eq!(p.shape().dims(), &[6]);
11712        assert_eq!(p.realize_f32(), vec![0.0, 0.0, 1.0, 2.0, 3.0, 0.0]);
11713    }
11714
11715    #[test]
11716    fn pad_with_zeros_identity_when_both_zero() {
11717        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11718        let p = t.pad_with_zeros(0, 0, 0).unwrap();
11719        assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11720    }
11721
11722    #[test]
11723    fn pad_with_zeros_rejects_bad_dim() {
11724        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11725        assert!(t.pad_with_zeros(3, 1, 1).is_err());
11726    }
11727
11728    #[test]
11729    fn pad_with_value_zero_matches_pad_with_zeros() {
11730        // pad_with_value(_, _, _, 0.0) must be observationally identical
11731        // to pad_with_zeros — the latter is now a wrapper for the former.
11732        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11733        let via_zeros = t.pad_with_zeros(0, 1, 2).unwrap();
11734        let via_value = t.pad_with_value(0, 1, 2, 0.0).unwrap();
11735        assert_eq!(via_zeros.shape().dims(), via_value.shape().dims());
11736        assert_eq!(via_zeros.shape().dims(), &[5, 2]);
11737        assert_eq!(via_zeros.realize_f32(), via_value.realize_f32());
11738        assert_eq!(
11739            via_value.realize_f32(),
11740            vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0],
11741        );
11742    }
11743
11744    #[test]
11745    fn pad_with_value_neg_inf_then_max_reduce_ignores_pad() {
11746        // Negative interior values: -1, -2, -3. Pad with -inf on both
11747        // sides. Max along dim 0 must be the interior max (-1.0), not
11748        // -inf. This is the load-bearing property for max_pool2d.
11749        let t = cpu_f32(vec![-1.0, -2.0, -3.0], &[3]);
11750        let padded = t.pad_with_value(0, 2, 2, f32::NEG_INFINITY).unwrap();
11751        assert_eq!(padded.shape().dims(), &[7]);
11752        let v = padded.realize_f32();
11753        // Layout: [-inf, -inf, -1, -2, -3, -inf, -inf]
11754        assert!(v[0].is_infinite() && v[0].is_sign_negative());
11755        assert!(v[1].is_infinite() && v[1].is_sign_negative());
11756        assert_eq!(v[2], -1.0);
11757        assert_eq!(v[3], -2.0);
11758        assert_eq!(v[4], -3.0);
11759        assert!(v[5].is_infinite() && v[5].is_sign_negative());
11760        assert!(v[6].is_infinite() && v[6].is_sign_negative());
11761        // max along the only dim drops the pad and returns the interior max.
11762        let m = padded.max_all().realize_f32();
11763        assert_eq!(m, vec![-1.0]);
11764    }
11765
11766    #[test]
11767    fn pad_with_value_identity_when_both_zero() {
11768        // The early-out path must fire regardless of value (no spurious
11769        // graph node when there's nothing to pad).
11770        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11771        let p = t.pad_with_value(0, 0, 0, f32::NEG_INFINITY).unwrap();
11772        assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11773    }
11774
11775    #[test]
11776    fn pad_with_value_rejects_bad_dim() {
11777        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11778        assert!(t.pad_with_value(3, 1, 1, 0.0).is_err());
11779    }
11780
11781    #[test]
11782    fn max_pool2d_with_pad_value_neg_inf_on_negative_interior() {
11783        // Negative-only interior values: a zero-padded max_pool2d would
11784        // incorrectly return 0 in boundary windows. -inf padding gives
11785        // the PyTorch-correct answer (the interior max).
11786        //
11787        // 1x1x3x3 tensor, all values negative:
11788        //   [ -1, -2, -3 ]
11789        //   [ -4, -5, -6 ]
11790        //   [ -7, -8, -9 ]
11791        // With kernel=3, stride=1, padding=1, output is 3x3 where the
11792        // (1,1) center sees the full grid → max = -1.
11793        let x = cpu_f32(
11794            vec![-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0],
11795            &[1, 1, 3, 3],
11796        );
11797        let out = x
11798            .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), f32::NEG_INFINITY)
11799            .unwrap();
11800        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
11801        let v = out.realize_f32();
11802        // Top-left corner (0,0): window sees only [(0,0),(0,1),(1,0),(1,1)]
11803        // = [-1,-2,-4,-5]; padded slots are -inf → max = -1.
11804        assert_eq!(v[0], -1.0);
11805        // Center (1,1): no padded slots in window → max of all 9 = -1.
11806        assert_eq!(v[4], -1.0);
11807        // Bottom-right (2,2): window sees [(1,1),(1,2),(2,1),(2,2)]
11808        // = [-5,-6,-8,-9]; padded slots are -inf → max = -5.
11809        assert_eq!(v[8], -5.0);
11810
11811        // KISS-Ops S14: `max_pool2d`'s own default pad value was 0.0
11812        // ("legacy behavior") -- the exact bug this test file demonstrates
11813        // above -- and is now `f32::NEG_INFINITY`. So `max_pool2d` (no
11814        // explicit pad value) must now agree with the NEG_INFINITY variant
11815        // above, not with a zero-padded one; the OLD zero-padded answer is
11816        // only reachable by asking for it explicitly via
11817        // `max_pool2d_with_pad_value(..., 0.0)`, which this block also
11818        // checks, to keep BOTH halves of the fix (new default AND old
11819        // explicit escape hatch) under one assertion.
11820        let default_pad = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
11821        let vd = default_pad.realize_f32();
11822        assert_eq!(
11823            vd[0], -1.0,
11824            "max_pool2d's default must now match NEG_INFINITY padding, not 0.0"
11825        );
11826        assert_eq!(vd[8], -5.0);
11827
11828        let explicit_zero_pad = x
11829            .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), 0.0)
11830            .unwrap();
11831        let vz = explicit_zero_pad.realize_f32();
11832        assert_eq!(
11833            vz[0], 0.0,
11834            "explicit 0.0 padding must still be reachable via max_pool2d_with_pad_value"
11835        );
11836        assert_eq!(vz[8], 0.0);
11837    }
11838
11839    #[test]
11840    fn max_pool2d_with_pad_value_zero_matches_max_pool2d() {
11841        // With pad_value = 0.0, the new variant must agree with the
11842        // legacy max_pool2d byte-for-byte.
11843        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11844        let x = cpu_f32(data, &[1, 1, 4, 4]);
11845        let a = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
11846        let b = x
11847            .max_pool2d_with_pad_value((2, 2), (2, 2), (0, 0), 0.0)
11848            .unwrap();
11849        assert_eq!(a.shape().dims(), b.shape().dims());
11850        assert_eq!(a.realize_f32(), b.realize_f32());
11851    }
11852
11853    // ---- Phase A.6 conv1d composite tests ----
11854
11855    #[test]
11856    fn conv1d_identity_kernel_passes_input_through() {
11857        // Single-batch, single-channel, kernel-1 identity → output equals input.
11858        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[1, 1, 5]);
11859        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11860        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11861        assert_eq!(out.shape().dims(), &[1, 1, 5]);
11862        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
11863    }
11864
11865    #[test]
11866    fn conv1d_sum_kernel_two_wide() {
11867        // Sum kernel of size 2: out[t] = x[t] + x[t+1].
11868        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11869        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11870        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11871        assert_eq!(out.shape().dims(), &[1, 1, 3]);
11872        assert_eq!(out.realize_f32(), vec![3.0, 5.0, 7.0]);
11873    }
11874
11875    #[test]
11876    fn conv1d_with_bias_applies_correctly() {
11877        let x = cpu_f32(vec![1.0, 1.0, 1.0], &[1, 1, 3]);
11878        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11879        let bias = x.const_f32_like(vec![10.0], vec![1]).unwrap();
11880        let out = x.conv1d(&w, Some(&bias), 1, 0, 1).unwrap();
11881        assert_eq!(out.realize_f32(), vec![11.0, 11.0, 11.0]);
11882    }
11883
11884    #[test]
11885    fn conv1d_stride_two_halves_output() {
11886        // Input length 6, kernel 2, stride 2 → output length (6-2)/2+1 = 3.
11887        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[1, 1, 6]);
11888        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11889        let out = x.conv1d(&w, None, 2, 0, 1).unwrap();
11890        assert_eq!(out.shape().dims(), &[1, 1, 3]);
11891        assert_eq!(out.realize_f32(), vec![3.0, 7.0, 11.0]);
11892    }
11893
11894    #[test]
11895    fn conv1d_padding_one_preserves_length() {
11896        // Input length 4, kernel 3, padding 1, stride 1 → output length 4.
11897        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11898        let w = x
11899            .const_f32_like(vec![1.0, 1.0, 1.0], vec![1, 1, 3])
11900            .unwrap();
11901        let out = x.conv1d(&w, None, 1, 1, 1).unwrap();
11902        assert_eq!(out.shape().dims(), &[1, 1, 4]);
11903        // out[0] = 0+x[0]+x[1] = 3; out[1] = x[0]+x[1]+x[2] = 6;
11904        // out[2] = x[1]+x[2]+x[3] = 9; out[3] = x[2]+x[3]+0 = 7
11905        assert_eq!(out.realize_f32(), vec![3.0, 6.0, 9.0, 7.0]);
11906    }
11907
11908    #[test]
11909    fn conv1d_multi_channel_output() {
11910        // 1 batch, 1 in-channel, 3 timesteps; 2 out-channels with kernel 1.
11911        let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
11912        // Weight [Cout=2, Cin=1, K=1]: filter 0 = 2.0, filter 1 = -1.0.
11913        let w = x.const_f32_like(vec![2.0, -1.0], vec![2, 1, 1]).unwrap();
11914        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11915        assert_eq!(out.shape().dims(), &[1, 2, 3]);
11916        // Channel 0: 2.0 × input. Channel 1: -1.0 × input.
11917        assert_eq!(out.realize_f32(), vec![2.0, 4.0, 6.0, -1.0, -2.0, -3.0]);
11918    }
11919
11920    #[test]
11921    fn conv1d_rejects_rank_two_input() {
11922        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11923        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11924        assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11925    }
11926
11927    #[test]
11928    fn conv1d_rejects_rank_two_weight() {
11929        let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11930        let w = x.const_f32_like(vec![1.0], vec![1, 1]).unwrap();
11931        assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11932    }
11933
11934    #[test]
11935    fn conv1d_rejects_zero_groups_or_stride() {
11936        let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11937        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11938        assert!(x.conv1d(&w, None, 0, 0, 1).is_err());
11939        assert!(x.conv1d(&w, None, 1, 0, 0).is_err());
11940    }
11941
11942    #[test]
11943    fn conv1d_with_algo_ignores_algo_param() {
11944        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11945        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11946        // Pass a dummy algo (the parameter is ignored on the lazy path).
11947        let a = x.conv1d_with_algo(&w, None, 1, 0, 1, "unused").unwrap();
11948        let b = x.conv1d(&w, None, 1, 0, 1).unwrap();
11949        assert_eq!(a.realize_f32(), b.realize_f32());
11950    }
11951
11952    // ---- Phase A.7 pooling / interpolation composite tests ----
11953
11954    #[test]
11955    fn avg_pool2d_2x2_stride2() {
11956        // 1×1×4×4 input with values 0..15.
11957        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11958        let x = cpu_f32(data, &[1, 1, 4, 4]);
11959        let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
11960        assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
11961        // Each 2x2 block average: top-left = (0+1+4+5)/4 = 2.5,
11962        // top-right = (2+3+6+7)/4 = 4.5, bottom-left = (8+9+12+13)/4 = 10.5,
11963        // bottom-right = (10+11+14+15)/4 = 12.5.
11964        let v = out.realize_f32();
11965        assert!((v[0] - 2.5).abs() < 1e-5);
11966        assert!((v[1] - 4.5).abs() < 1e-5);
11967        assert!((v[2] - 10.5).abs() < 1e-5);
11968        assert!((v[3] - 12.5).abs() < 1e-5);
11969    }
11970
11971    #[test]
11972    fn avg_pool2d_3x3_stride1_padding1_preserves_size() {
11973        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11974        let out = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11975        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
11976    }
11977
11978    /// KISS-Ops §6.13 S14: `count_include_pad = false` must divide each
11979    /// border window by its TRUE valid-tap count, not the uniform `kh·kw`.
11980    /// Fixture: a 1x1x4x4 all-ones input, 3x3 kernel, padding 1.
11981    ///
11982    /// `excluded` (count_include_pad=false) must be EXACTLY 1.0 at every
11983    /// output position, border included: averaging any positive count of
11984    /// real taps that are all 1.0 is always 1.0, regardless of how many
11985    /// padded slots surround them — this is the invariant the fix exists
11986    /// to restore. `included` (count_include_pad=true, today's old
11987    /// behavior) must NOT share that invariant: it divides by the uniform
11988    /// 9 regardless of how many taps were real, so a corner window (only
11989    /// 4 of 9 taps real) computes `4/9 ≈ 0.444`, well below 1.0 — the two
11990    /// modes genuinely disagree at the border, which is the point of the
11991    /// fix. (On fully-interior positions, where every tap is real either
11992    /// way, both modes necessarily agree — not asserted here since it
11993    /// proves nothing about the fix; see the non-uniform fixture below for
11994    /// a sharper per-position contrast.)
11995    #[test]
11996    fn avg_pool2d_excludes_padding_keeps_uniform_data_exactly_at_its_true_value() {
11997        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11998        let included = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11999        let excluded = x.avg_pool2d((3, 3), (1, 1), (1, 1), false).unwrap();
12000        assert_eq!(included.shape().dims(), excluded.shape().dims());
12001
12002        let ve = excluded.realize_f32();
12003        for (i, &v) in ve.iter().enumerate() {
12004            assert!(
12005                (v - 1.0).abs() < 1e-5,
12006                "count_include_pad=false must be exactly 1.0 at every position \
12007                 (all real taps are 1.0) — position {i} got {v}",
12008            );
12009        }
12010
12011        let vi = included.realize_f32();
12012        assert!(
12013            (vi[0] - 1.0).abs() > 0.1,
12014            "count_include_pad=true must NOT match at a corner (4 of 9 taps \
12015             real → 4/9, far from 1.0) — got {}, modes should disagree here",
12016            vi[0]
12017        );
12018    }
12019
12020    /// The actual discriminating case: non-uniform data at a border window.
12021    /// A 1x1x2x2 input `[[10, 10], [10, 10]]`, kernel 2x2, padding 1 (so
12022    /// the TOP-LEFT output position's window is `[[pad,pad],[pad,10]]` --
12023    /// only ONE of four taps is real). count_include_pad=true (today's old
12024    /// behavior) divides by the uniform 4: `10/4 = 2.5`. count_include_pad
12025    /// =false (ONNX/PyTorch default) divides by the TRUE valid count, 1:
12026    /// `10/1 = 10.0` -- the actual average of the real values in the
12027    /// window, which is what "average pooling, excluding padding" means.
12028    #[test]
12029    fn avg_pool2d_excludes_padding_from_divisor_discriminating() {
12030        let x = cpu_f32(vec![10.0, 10.0, 10.0, 10.0], &[1, 1, 2, 2]);
12031        let included = x.avg_pool2d((2, 2), (1, 1), (1, 1), true).unwrap();
12032        let excluded = x.avg_pool2d((2, 2), (1, 1), (1, 1), false).unwrap();
12033        let vi = included.realize_f32();
12034        let ve = excluded.realize_f32();
12035        assert!(
12036            (vi[0] - 2.5).abs() < 1e-5,
12037            "count_include_pad=true: top-left = 10/4 = 2.5, got {}",
12038            vi[0]
12039        );
12040        assert!(
12041            (ve[0] - 10.0).abs() < 1e-5,
12042            "count_include_pad=false: top-left = 10/1 (ONE real tap) = 10.0, got {}",
12043            ve[0]
12044        );
12045    }
12046
12047    /// A 1x1 input with padding >= kernel size: EVERY output window is
12048    /// entirely padding, so the count-include-pad=false divisor would be
12049    /// zero everywhere. Must refuse with a descriptive error rather than
12050    /// let `broadcast_div` emit NaN/inf.
12051    #[test]
12052    fn avg_pool2d_rejects_zero_valid_tap_window() {
12053        let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12054        let err = x
12055            .avg_pool2d((1, 1), (1, 1), (2, 2), false)
12056            .expect_err("a window with zero real taps must be rejected, not silently NaN");
12057        let msg = err.to_string();
12058        assert!(
12059            msg.contains("divide by zero") || msg.contains("no valid"),
12060            "error should explain the zero-valid-tap cause, got: {msg}"
12061        );
12062
12063        // Positive control: count_include_pad=true has no notion of "valid
12064        // taps" (it always divides by kh*kw), so the SAME shape must still
12065        // succeed under that mode -- proving the rejection is specific to
12066        // the zero-valid-tap case, not a blanket refusal of this shape.
12067        let ok = x.avg_pool2d((1, 1), (1, 1), (2, 2), true);
12068        assert!(
12069            ok.is_ok(),
12070            "count_include_pad=true must still accept this shape (uniform divisor, never zero)"
12071        );
12072    }
12073
12074    #[test]
12075    fn avg_pool2d_multi_channel() {
12076        // 1×2×2×2: each channel is filled with its index.
12077        let x = cpu_f32(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], &[1, 2, 2, 2]);
12078        let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
12079        assert_eq!(out.shape().dims(), &[1, 2, 1, 1]);
12080        assert_eq!(out.realize_f32(), vec![0.0, 1.0]);
12081    }
12082
12083    #[test]
12084    fn max_pool2d_2x2_stride2() {
12085        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
12086        let x = cpu_f32(data, &[1, 1, 4, 4]);
12087        let out = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
12088        assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
12089        // Each 2x2 block max: 5, 7, 13, 15.
12090        assert_eq!(out.realize_f32(), vec![5.0, 7.0, 13.0, 15.0]);
12091    }
12092
12093    #[test]
12094    fn max_pool2d_3x3_stride1_padding1() {
12095        let x = cpu_f32(
12096            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
12097            &[1, 1, 3, 3],
12098        );
12099        let out = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
12100        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12101        // Center should be the global max 9; corners should be the max of their 2×2 window.
12102        let v = out.realize_f32();
12103        // (1,1) center: max of all 9 = 9
12104        assert!((v[4] - 9.0).abs() < 1e-5);
12105    }
12106
12107    #[test]
12108    fn upsample_nearest2d_2x() {
12109        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12110        let out = x.upsample_nearest2d(2).unwrap();
12111        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12112        // Each cell replicated 2×2: rows are [1,1,2,2; 1,1,2,2; 3,3,4,4; 3,3,4,4].
12113        assert_eq!(
12114            out.realize_f32(),
12115            vec![
12116                1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 3.0, 3.0, 4.0, 4.0,
12117            ],
12118        );
12119    }
12120
12121    #[test]
12122    fn upsample_nearest2d_3x() {
12123        let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12124        let out = x.upsample_nearest2d(3).unwrap();
12125        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12126        assert_eq!(out.realize_f32(), vec![5.0; 9]);
12127    }
12128
12129    #[test]
12130    fn upsample_nearest2d_identity_scale_one() {
12131        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12132        let out = x.upsample_nearest2d(1).unwrap();
12133        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
12134    }
12135
12136    #[test]
12137    fn upsample_nearest1d_2x() {
12138        let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
12139        let out = x.upsample_nearest1d(2).unwrap();
12140        assert_eq!(out.shape().dims(), &[1, 1, 6]);
12141        assert_eq!(out.realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
12142    }
12143
12144    #[test]
12145    fn interpolate2d_integer_multiple() {
12146        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12147        let out = x.interpolate2d(4, 4).unwrap();
12148        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12149    }
12150
12151    #[test]
12152    fn interpolate2d_accepts_non_integer_ratio() {
12153        // Lifted from "rejects non-integer ratio" — arbitrary
12154        // ratios are now supported via the index_select composite
12155        // (matching the eager UpsampleNearest2D convention). See
12156        // tests/lazy_interpolate2d_oracle.rs for parity checks.
12157        let x = cpu_f32(vec![1.0; 4], &[1, 1, 2, 2]);
12158        let out = x.interpolate2d(3, 4).unwrap();
12159        assert_eq!(out.shape().dims(), &[1, 1, 3, 4]);
12160    }
12161
12162    #[test]
12163    fn interpolate1d_integer_multiple() {
12164        let x = cpu_f32(vec![1.0, 2.0], &[1, 1, 2]);
12165        let out = x.interpolate1d(6).unwrap();
12166        assert_eq!(out.shape().dims(), &[1, 1, 6]);
12167        assert_eq!(out.realize_f32(), vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]);
12168    }
12169
12170    #[test]
12171    fn pool_rejects_bad_rank() {
12172        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
12173        assert!(x.avg_pool2d((2, 2), (2, 2), (0, 0), true).is_err());
12174        assert!(x.max_pool2d((2, 2), (2, 2), (0, 0)).is_err());
12175    }
12176
12177    #[test]
12178    fn pool_rejects_zero_kernel() {
12179        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
12180        assert!(x.avg_pool2d((0, 2), (1, 1), (0, 0), true).is_err());
12181        assert!(x.max_pool2d((2, 0), (1, 1), (0, 0)).is_err());
12182    }
12183
12184    // ---- Phase A.8 scope-limited harmonization aliases ----
12185
12186    #[test]
12187    fn numel_matches_elem_count() {
12188        let t = cpu_f32(vec![1.0; 12], &[3, 4]);
12189        assert_eq!(t.numel(), t.elem_count());
12190        assert_eq!(t.numel(), 12);
12191    }
12192
12193    #[test]
12194    fn dim_returns_specific_axis_size() {
12195        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12196        assert_eq!(t.dim(0).unwrap(), 2);
12197        assert_eq!(t.dim(1).unwrap(), 3);
12198        assert_eq!(t.dim(2).unwrap(), 4);
12199        assert!(t.dim(3).is_err());
12200    }
12201
12202    #[test]
12203    fn to_dtype_switches_dtype() {
12204        let t = cpu_f32(vec![1.0, 2.0], &[2]);
12205        let b = t.to_dtype(DType::F64).unwrap();
12206        assert_eq!(b.dtype(), DType::F64);
12207        assert_eq!(b.realize_f64(), vec![1.0, 2.0]);
12208    }
12209
12210    #[test]
12211    fn to_dtype_same_dtype_is_noop() {
12212        let t = cpu_f32(vec![1.0_f32], &[1]);
12213        let b = t.to_dtype(DType::F32).unwrap();
12214        assert_eq!(b.dtype(), DType::F32);
12215    }
12216
12217    #[test]
12218    fn detach_is_identity_on_lazy() {
12219        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12220        let d = t.detach();
12221        assert_eq!(d.realize_f32(), t.realize_f32());
12222    }
12223
12224    #[test]
12225    fn track_op_is_true_on_lazy() {
12226        let t = cpu_f32(vec![0.0], &[1]);
12227        assert!(t.track_op());
12228    }
12229
12230    // ---- Phase A.8a Dim/Dims trait port ergonomics tests ----
12231
12232    #[test]
12233    fn try_permute_accepts_tuple_syntax() {
12234        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12235        // Eager-style tuple permute now works on lazy.
12236        let out = t.permute((2_usize, 0_usize, 1_usize)).unwrap();
12237        assert_eq!(out.shape().dims(), &[4, 2, 3]);
12238    }
12239
12240    #[test]
12241    fn dim_arg_methods_accept_negative_indexing() {
12242        use fuel_ir::D;
12243        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
12244        // squeeze, sum_dim, mean_dim, etc. all accept D::Minus1 now.
12245        let sum_last = t.shape().dims().to_vec(); // just demonstrate compile
12246        assert_eq!(sum_last, vec![2, 3]);
12247        // sum_dim is still Self-returning (Phase A.8b will flip), so test
12248        // a method that already returns Result + dim arg.
12249        let cumsum_last = t.cumsum(D::Minus1).unwrap();
12250        assert_eq!(cumsum_last.shape().dims(), &[2, 3]);
12251    }
12252
12253    #[test]
12254    fn unsqueeze_accepts_dim_trait() {
12255        use fuel_ir::D;
12256        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12257        // Append a new last dim via D::Minus1 (rank-aware negative indexing).
12258        let out = t.unsqueeze(D::Minus1).unwrap();
12259        // The position D::Minus1 in to_index_plus_one is "the very end"
12260        // → output rank 2 with the new dim trailing.
12261        assert_eq!(out.shape().dims().len(), 2);
12262    }
12263}
12264pub struct TokenDataHost {
12265    pub token_ids: fuel_ir::HostBuffer,
12266    pub rope_cos: fuel_ir::HostBuffer,
12267    pub rope_sin: fuel_ir::HostBuffer,
12268    pub mask: fuel_ir::HostBuffer,
12269    pub offset: Option<fuel_ir::HostBuffer>,
12270}
12271
12272/// Same per-token data as [`crate::inference_context::DecodeTokenData`],
12273/// as raw host bytes instead of freshly-uploaded device Arcs — for
12274/// [`fuel_dispatch::pipelined::CapturedDecodeSession::replay_token`]'s
12275/// in-place H2D overwrite of fixed buffers. `LlamaModel`-private.
12276#[cfg(feature = "cuda")]
12277pub struct TokenDataBytes {
12278    pub token_ids: Vec<u8>,
12279    pub rope_cos: Vec<u8>,
12280    pub rope_sin: Vec<u8>,
12281    pub mask: Vec<u8>,
12282    pub offset: Option<Vec<u8>>,
12283}
12284
12285/// D2H a [`fuel_dispatch::pipelined::CapturedDecodeSession::replay_token`]
12286/// result's device-resident output Arc to a host `Vec<f32>`.
12287///
12288/// The capture mechanism deliberately keeps the output device-resident
12289/// INSIDE the capture (a `Copy`/`Move` node is capture-unsafe — see
12290/// `LlamaModel::forward_with_kv_context_captured`'s design note); this
12291/// reads it back OUTSIDE the capture, dispatching on the same
12292/// `BackendStorage` variants every other pipelined D2H site in this
12293/// codebase does (`CudaStorageBytes::to_cpu_bytes` / `CpuStorageBytes::
12294/// bytes`) rather than hand-rolling a new D2H mechanism. Capture is
12295/// f32-only today (project constraint), so the bytes are reinterpreted
12296/// as f32 directly.
12297#[cfg(feature = "cuda")]
12298pub fn captured_output_to_f32(
12299    output: &Arc<std::sync::RwLock<fuel_memory::Storage>>,
12300) -> fuel_ir::error::Result<Vec<f32>> {
12301    use fuel_memory::BackendStorage;
12302    let guard = output.read().map_err(|_| {
12303        fuel_ir::Error::Msg("captured decode output storage lock poisoned".into()).bt()
12304    })?;
12305    let bytes: Vec<u8> = match &guard.inner {
12306        BackendStorage::Cpu(c) => c.bytes().to_vec(),
12307        BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
12308        #[allow(unreachable_patterns)]
12309        other => {
12310            return Err(fuel_ir::Error::Msg(format!(
12311                "captured decode output is BackendStorage::{:?}, expected Cpu or Cuda",
12312                std::mem::discriminant(other),
12313            ))
12314            .bt());
12315        }
12316    };
12317    Ok(bytemuck::cast_slice::<u8, f32>(&bytes).to_vec())
12318}