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    #[cfg(feature = "cuda")]
2009    pub fn realize_f32_cuda(&self, device: &fuel_cuda_backend::CudaDevice) -> Vec<f32> {
2010        let graph = self.inner.graph().clone();
2011        let target = self.inner.id();
2012        let fc_device: crate::Device = device.clone().into();
2013        crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2014            .expect("realize_f32_cuda via PipelinedExecutor")
2015    }
2016
2017    // The legacy-executor-signature `realize_f32_vulkan` was deleted in
2018    // executor-unification Session 2 (2026-06-11). This bridge-based
2019    // wrapper restores Vulkan/CUDA realize parity (2026-06-15): it goes
2020    // through `pipelined_bridge::realize_one_as` on a Vulkan `Device`,
2021    // the same production path `realize_f32` / `realize_f32_cuda` use —
2022    // so it exercises the `optimize_graph` realize path on the Vulkan
2023    // backend.
2024    #[cfg(feature = "vulkan")]
2025    pub fn realize_f32_vulkan(
2026        &self,
2027        backend: &std::sync::Arc<fuel_vulkan_backend::VulkanBackend>,
2028    ) -> Vec<f32> {
2029        let graph = self.inner.graph().clone();
2030        let target = self.inner.id();
2031        let fc_device: crate::Device = backend.clone().into();
2032        crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &fc_device)
2033            .expect("realize_f32_vulkan via PipelinedExecutor")
2034    }
2035}
2036
2037/// Realize many tensors in a single CPU topo-walk. Phase 7.6 step 9c E.2.
2038pub fn realize_many_f32(tensors: &[&Tensor]) -> Vec<Vec<f32>> {
2039    if tensors.is_empty() {
2040        return Vec::new();
2041    }
2042    let graph = tensors[0].inner.graph().clone();
2043    let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2044    let device = crate::Device::cpu();
2045    crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &device)
2046        .expect("realize_many_f32 via PipelinedExecutor")
2047}
2048
2049/// CUDA variant of realize_many_f32. Phase 7.6 step 9c E.2: signature
2050/// change from `&mut GraphExecutor<CudaBackend>` to `&CudaDevice`.
2051#[cfg(feature = "cuda")]
2052pub fn realize_many_f32_cuda(
2053    tensors: &[&Tensor],
2054    device: &fuel_cuda_backend::CudaDevice,
2055) -> Vec<Vec<f32>> {
2056    if tensors.is_empty() {
2057        return Vec::new();
2058    }
2059    let graph = tensors[0].inner.graph().clone();
2060    let targets: Vec<fuel_graph::NodeId> = tensors.iter().map(|t| t.inner.id()).collect();
2061    let fc_device: crate::Device = device.clone().into();
2062    crate::pipelined_bridge::realize_many_as::<f32>(&graph, &targets, &fc_device)
2063        .expect("realize_many_f32_cuda via PipelinedExecutor")
2064}
2065
2066#[cfg(test)]
2067mod tests {
2068    use super::*;
2069    use crate::Shape;
2070
2071    #[test]
2072    fn constructors_wrap_graph_tensor_correctly() {
2073        let t =
2074            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2075        assert_eq!(t.dtype(), DType::F32);
2076        assert_eq!(t.shape().dims(), &[3]);
2077        assert_eq!(t.rank(), 1);
2078        assert_eq!(t.elem_count(), 3);
2079    }
2080
2081    #[test]
2082    fn add_builds_add_node_in_underlying_graph() {
2083        let a =
2084            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2085        let b = a
2086            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2087            .unwrap();
2088        let c = a.add(&b).unwrap();
2089        assert_eq!(c.shape().dims(), &[3]);
2090        // All three tensors share one underlying graph (by Arc cloning
2091        // via const_f32_like / add).
2092        assert!(std::sync::Arc::ptr_eq(
2093            c.graph_tensor().graph(),
2094            a.graph_tensor().graph(),
2095        ));
2096    }
2097
2098    #[test]
2099    fn chained_lazy_method_call_builds_sensible_graph() {
2100        // Exercise a small pipeline typical of what an early LLaMA
2101        // port would write: RmsNorm → matmul → RMS-style residual.
2102        // We just verify the shapes thread through cleanly and the
2103        // final tensor is consistent.
2104        let x = Tensor::from_f32(
2105            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2106            Shape::from_dims(&[2, 3]),
2107            &Device::cpu(),
2108        )
2109        .unwrap();
2110        let w = x
2111            .const_f32_like(
2112                vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
2113                Shape::from_dims(&[3, 3]),
2114            )
2115            .unwrap();
2116        let y = x
2117            .rms_norm_last_dim(1e-6)
2118            .unwrap()
2119            .matmul(&w)
2120            .unwrap()
2121            .relu();
2122        assert_eq!(y.shape().dims(), &[2, 3]);
2123        assert_eq!(y.dtype(), DType::F32);
2124    }
2125
2126    #[test]
2127    fn rope_through_lazy_wrapper() {
2128        // Verify the RoPE builder is reachable through Tensor.
2129        let x = Tensor::from_f32(
2130            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
2131            Shape::from_dims(&[2, 4]),
2132            &Device::cpu(),
2133        )
2134        .unwrap();
2135        let y = x.rope(10000.0, 0).unwrap();
2136        assert_eq!(y.shape().dims(), &[2, 4]);
2137        assert_eq!(y.dtype(), DType::F32);
2138    }
2139
2140    #[test]
2141    fn rope_delta_rotate_equals_direct_shift() {
2142        // rung-2 primitive: a K block rotated at its ORIGINAL positions then
2143        // uniformly delta-rotated by M is byte-equal to the same raw K rotated
2144        // DIRECTLY at the shifted positions. This is the exactness that lets a
2145        // cached prefix be reused at a non-zero offset. Everything is in the POOL
2146        // block layout [block_size, n_kv_heads, head_dim] that `read_block` yields.
2147        let dev = Device::cpu();
2148        let (n_kv_heads, head_dim, bs) = (2usize, 4usize, 4usize);
2149        let theta = 10000.0;
2150        let (p0, m) = (0usize, 8usize); // block at positions 0..4, shift by 8 → 8..12
2151        let raw: Vec<f32> = (0..bs * n_kv_heads * head_dim)
2152            .map(|i| (i as f32 * 0.017).sin())
2153            .collect();
2154        // Reference: rope a pool-layout [bs,Hkv,D] block DIRECTLY at `start_pos`
2155        // (heads forward → rope → back), mirroring the helper's permute so the two
2156        // paths are compared in the same layout.
2157        let rope_pool_at = |data: &[f32], start_pos: usize| -> Vec<f32> {
2158            let k = Tensor::from_f32(
2159                data.to_vec(),
2160                Shape::from_dims(&[bs, n_kv_heads, head_dim]),
2161                &dev,
2162            )
2163            .unwrap();
2164            let k4 = k
2165                .permute([1, 0, 2])
2166                .unwrap()
2167                .reshape(Shape::from_dims(&[1, n_kv_heads, bs, head_dim]))
2168                .unwrap();
2169            let (c, s) = k4.rope_tables_const(theta, start_pos, bs, head_dim);
2170            k4.rope_with_tables_decomposed(&c, &s)
2171                .unwrap()
2172                .reshape(Shape::from_dims(&[n_kv_heads, bs, head_dim]))
2173                .unwrap()
2174                .permute([1, 0, 2])
2175                .unwrap()
2176                .realize_f32()
2177        };
2178        let direct = rope_pool_at(&raw, p0 + m); // rope directly at shifted positions
2179        let at_p0 = rope_pool_at(&raw, p0); // cached, rotated at original positions
2180        let shifted =
2181            Tensor::rope_delta_rotate_block_f32(&dev, &at_p0, theta, m, bs, n_kv_heads, head_dim);
2182        let maxdiff = direct
2183            .iter()
2184            .zip(&shifted)
2185            .map(|(a, b)| (a - b).abs())
2186            .fold(0.0f32, f32::max);
2187        assert!(
2188            maxdiff < 1e-5,
2189            "delta-rotate == direct shift (maxdiff {maxdiff})"
2190        );
2191    }
2192
2193    #[test]
2194    fn cast_switches_dtype_through_wrapper() {
2195        let x =
2196            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2197        let y = x.to_dtype(DType::F64).unwrap();
2198        assert_eq!(y.dtype(), DType::F64);
2199        assert_eq!(y.shape().dims(), &[3]);
2200    }
2201
2202    #[test]
2203    fn indexing_builds_correct_output_shape() {
2204        let data =
2205            Tensor::from_f32(vec![1.0; 12], Shape::from_dims(&[3, 4]), &Device::cpu()).unwrap();
2206        let idx = data
2207            .const_u32_like(vec![0, 2, 1], Shape::from_dims(&[3]))
2208            .unwrap();
2209        let out = data.index_select(0, &idx).unwrap();
2210        assert_eq!(out.shape().dims(), &[3, 4]);
2211    }
2212
2213    // ---- Bridge realization tests ----
2214
2215    #[test]
2216    fn realize_f32_executes_the_underlying_graph() {
2217        // The moment of truth: build a graph through Tensor and
2218        // then realize it end-to-end. (a + b) * a for a = [1, 2, 3],
2219        // b = [4, 5, 6] should yield [5, 14, 27].
2220        let a =
2221            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
2222        let b = a
2223            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
2224            .unwrap();
2225        let c = a.add(&b).unwrap().mul(&a).unwrap();
2226        let result = c.realize_f32();
2227        assert_eq!(result, vec![5.0, 14.0, 27.0]);
2228    }
2229
2230    #[test]
2231    fn realize_f32_relu_and_maximum_propagate_nan_end_to_end() {
2232        // Pinned NaN-semantics convention (2026-07-08,
2233        // docs/architecture/10-decisions-log.md): Relu/Maximum/Minimum are
2234        // NaN-propagating (torch parity). This guards the full lazy path
2235        // (graph build -> optimize -> dispatch -> CPU kernel -> realize),
2236        // not just the scalar-kernel unit tests in fuel-cpu-backend.
2237        let a = Tensor::from_f32(
2238            vec![f32::NAN, -2.0, 3.0],
2239            Shape::from_dims(&[3]),
2240            &Device::cpu(),
2241        )
2242        .unwrap();
2243        let relu_result = a.relu().realize_f32();
2244        assert!(
2245            relu_result[0].is_nan(),
2246            "relu(NaN) must propagate NaN through realize, got {}",
2247            relu_result[0]
2248        );
2249        assert_eq!(relu_result[1], 0.0, "relu(-2) must clip to 0");
2250        assert_eq!(relu_result[2], 3.0, "relu(3) must pass through");
2251
2252        let b = a
2253            .const_f32_like(vec![1.0, f32::NAN, 2.0], Shape::from_dims(&[3]))
2254            .unwrap();
2255        let max_result = a.maximum(&b).unwrap().realize_f32();
2256        assert!(
2257            max_result[0].is_nan(),
2258            "maximum(NaN, 1) must propagate NaN through realize, got {}",
2259            max_result[0]
2260        );
2261        assert!(
2262            max_result[1].is_nan(),
2263            "maximum(-2, NaN) must propagate NaN through realize, got {}",
2264            max_result[1]
2265        );
2266        assert_eq!(max_result[2], 3.0, "maximum(3, 2) non-NaN sanity");
2267    }
2268
2269    // ===== GAP-048: KISS-Ops §6.15 resolution helpers (fmax_ieee / fmin_ieee /
2270    // rem_trunc) — realized end-to-end because fuel-graph tests only BUILD; the
2271    // VALUE divergence needs a backend. Do NOT move these "closer to the code" in
2272    // fuel-graph: there they cannot realize and become vacuous. =====
2273
2274    #[test]
2275    fn fmax_fmin_ieee_suppress_nan_where_prop_propagates() {
2276        // §6.15-0001 divergence born-red. The IEEE (suppress) and torch-parity
2277        // (propagate) halves diverge ONLY on a NaN operand — a no-NaN fixture
2278        // passes under BOTH and is vacuous, so the fixture must carry NaN.
2279        let a = Tensor::from_f32(
2280            vec![f32::NAN, 2.0, 5.0],
2281            Shape::from_dims(&[3]),
2282            &Device::cpu(),
2283        )
2284        .unwrap();
2285        let b = a
2286            .const_f32_like(vec![3.0, f32::NAN, 4.0], Shape::from_dims(&[3]))
2287            .unwrap();
2288
2289        let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2290        assert_eq!(fmax[0], 3.0, "fmax_ieee(NaN,3) suppresses NaN → 3");
2291        assert_eq!(fmax[1], 2.0, "fmax_ieee(2,NaN) suppresses NaN → 2");
2292        assert_eq!(fmax[2], 5.0, "fmax_ieee(5,4) → 5");
2293        let max = a.maximum(&b).unwrap().realize_f32();
2294        assert!(
2295            max[0].is_nan() && max[1].is_nan(),
2296            "maximum PROPAGATES NaN — the divergence that makes fmax_ieee distinct"
2297        );
2298
2299        let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2300        assert_eq!(fmin[0], 3.0, "fmin_ieee(NaN,3) suppresses NaN → 3");
2301        assert_eq!(fmin[1], 2.0, "fmin_ieee(2,NaN) suppresses NaN → 2");
2302        assert_eq!(fmin[2], 4.0, "fmin_ieee(5,4) → 4");
2303        let min = a.minimum(&b).unwrap().realize_f32();
2304        assert!(
2305            min[0].is_nan() && min[1].is_nan(),
2306            "minimum PROPAGATES NaN — the divergence that makes fmin_ieee distinct"
2307        );
2308    }
2309
2310    #[test]
2311    fn fmax_fmin_ieee_signed_zero_tie_operand_a_wins_bitwise() {
2312        // KISS Appendix A.3: on a ±0 tie (cmp_ge and cmp_le both true) operand `a`
2313        // (self) wins in all four minmax ops. ⚠️ Asserted on to_bits() — a value
2314        // compare cannot tell +0.0 from -0.0 and would pass VACUOUSLY. Fuel has
2315        // live ±0 tie-bias on CPU (#67)/Vulkan (#76) minmax paths, so if the CPU
2316        // `ge`/`where` path is tie-biased this born-red REVEALS it rather than
2317        // hiding it behind a value compare.
2318        //
2319        // ⚠️ SENSITIVITY PROVEN, not assumed (this test passed on first write, and
2320        // a first-write pass demonstrates nothing about its own sensitivity):
2321        // sabotaging the fmax_ieee decomposition `cmp_ge` → `cmp_gt` flips the tie
2322        // to b-wins and this goes RED with left=0 (+0.0) vs right=0x80000000 (-0.0).
2323        // So the a-wins result below is EARNED — the CPU ge/where path resolves the
2324        // tie a-wins, not tie-biased. Testing BOTH operand orders (each asserting
2325        // the *first* operand's zero) is the permanent discriminator: an order
2326        // swap or a collapse-to-constant flips one side; a return-`a`/return-`b`
2327        // collapse is caught by the sibling NaN test (fmax(NaN,3)=3 needs `b`,
2328        // fmax(2,NaN)=2 needs `a`). GAP-048.
2329        let a = Tensor::from_f32(vec![-0.0, 0.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
2330        let b = a
2331            .const_f32_like(vec![0.0, -0.0], Shape::from_dims(&[2]))
2332            .unwrap();
2333
2334        let fmax = a.fmax_ieee(&b).unwrap().realize_f32();
2335        assert_eq!(
2336            fmax[0].to_bits(),
2337            (-0.0f32).to_bits(),
2338            "fmax_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2339        );
2340        assert_eq!(
2341            fmax[1].to_bits(),
2342            (0.0f32).to_bits(),
2343            "fmax_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2344        );
2345
2346        let fmin = a.fmin_ieee(&b).unwrap().realize_f32();
2347        assert_eq!(
2348            fmin[0].to_bits(),
2349            (-0.0f32).to_bits(),
2350            "fmin_ieee(-0.0,+0.0): operand a wins the tie → -0.0 (bitwise)"
2351        );
2352        assert_eq!(
2353            fmin[1].to_bits(),
2354            (0.0f32).to_bits(),
2355            "fmin_ieee(+0.0,-0.0): operand a wins the tie → +0.0 (bitwise)"
2356        );
2357    }
2358
2359    #[test]
2360    fn rem_trunc_diverges_from_floored_rem_on_opposite_signs() {
2361        // §6.15-0003 divergence born-red. rem_trunc (sign of the DIVIDEND, C99
2362        // fmod) vs rem (floored, sign of the divisor) diverge ONLY when the
2363        // operands have opposite signs — a same-sign fixture is vacuous.
2364        let a = Tensor::from_f32(
2365            vec![-7.0, 7.0, -7.0],
2366            Shape::from_dims(&[3]),
2367            &Device::cpu(),
2368        )
2369        .unwrap();
2370        let b = a
2371            .const_f32_like(vec![3.0, -3.0, -3.0], Shape::from_dims(&[3]))
2372            .unwrap();
2373
2374        let rt = a.rem_trunc(&b).unwrap().realize_f32();
2375        assert_eq!(rt[0], -1.0, "-7 rem_trunc 3 = -1 (sign of dividend)");
2376        assert_eq!(rt[1], 1.0, "7 rem_trunc -3 = 1 (sign of dividend)");
2377        assert_eq!(rt[2], -1.0, "-7 rem_trunc -3 = -1");
2378        let rf = a.rem(&b).unwrap().realize_f32();
2379        assert_eq!(
2380            rf[0], 2.0,
2381            "-7 rem 3 = 2 (floored, sign of divisor) — the divergence from rem_trunc"
2382        );
2383    }
2384
2385    #[test]
2386    fn trunc_edges_signed_zero_nan_inf_bitwise() {
2387        // GAP-300: trunc's expansion (q>=0 ? floor : ceil) is FUEL's own — no KISS
2388        // vector catches an error in it, so its edges are verified HERE. ⚠️ ±0 on
2389        // to_bits() (value compare 0.0 == -0.0 is vacuous).
2390        let q = Tensor::from_f32(
2391            vec![
2392                2.7,
2393                -2.7,
2394                -0.0,
2395                0.0,
2396                f32::NAN,
2397                f32::INFINITY,
2398                f32::NEG_INFINITY,
2399            ],
2400            Shape::from_dims(&[7]),
2401            &Device::cpu(),
2402        )
2403        .unwrap();
2404        let t = q.trunc().realize_f32();
2405        assert_eq!(t[0], 2.0, "trunc(2.7) = 2 (toward zero)");
2406        assert_eq!(t[1], -2.0, "trunc(-2.7) = -2 (toward zero, NOT -3)");
2407        assert_eq!(
2408            t[2].to_bits(),
2409            (-0.0f32).to_bits(),
2410            "trunc(-0.0) must PRESERVE -0.0 (bitwise, not +0.0)"
2411        );
2412        assert_eq!(
2413            t[3].to_bits(),
2414            (0.0f32).to_bits(),
2415            "trunc(+0.0) = +0.0 (bitwise)"
2416        );
2417        assert!(t[4].is_nan(), "trunc(NaN) = NaN");
2418        assert_eq!(t[5], f32::INFINITY, "trunc(+inf) = +inf");
2419        assert_eq!(t[6], f32::NEG_INFINITY, "trunc(-inf) = -inf");
2420    }
2421
2422    #[test]
2423    fn realize_f32_matmul_hand_computed() {
2424        // Classic 2x3 @ 3x2 matmul through the bridge.
2425        let a = Tensor::from_f32(
2426            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
2427            Shape::from_dims(&[2, 3]),
2428            &Device::cpu(),
2429        )
2430        .unwrap();
2431        let b = a
2432            .const_f32_like(
2433                vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
2434                Shape::from_dims(&[3, 2]),
2435            )
2436            .unwrap();
2437        let c = a.matmul(&b).unwrap();
2438        assert_eq!(c.shape().dims(), &[2, 2]);
2439        assert_eq!(c.realize_f32(), vec![58.0, 64.0, 139.0, 154.0]);
2440    }
2441
2442    #[test]
2443    fn fast_and_reference_agree_on_medium_matmul() {
2444        // 64 × 96 @ 96 × 32 — bigger than anything we could hand-check
2445        // but small enough to verify every element. The fast path
2446        // goes through gemm, the reference path uses the naive triple
2447        // loop; results should agree within float-rounding tolerance.
2448        let m = 64;
2449        let k = 96;
2450        let n = 32;
2451        let a_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.01).sin()).collect();
2452        let b_data: Vec<f32> = (0..k * n).map(|i| (i as f32 * 0.013).cos()).collect();
2453        let a = Tensor::from_f32(a_data, Shape::from_dims(&[m, k]), &Device::cpu()).unwrap();
2454        let b = a.const_f32_like(b_data, Shape::from_dims(&[k, n])).unwrap();
2455        let c = a.matmul(&b).unwrap();
2456        let fast = c.realize_f32();
2457        let reference = c.realize_f32();
2458        assert_eq!(fast.len(), reference.len());
2459        for (i, (&f, &r)) in fast.iter().zip(&reference).enumerate() {
2460            // Accept either absolute or relative tolerance — gemm's
2461            // blocked accumulation order differs from the naive triple
2462            // loop, so values near zero can have large relative diffs
2463            // on tiny absolute diffs. Both bounds are loose enough for
2464            // float-noise but tight enough to catch real bugs.
2465            let diff = (f - r).abs();
2466            let rel = if r.abs() > 1e-6 { diff / r.abs() } else { 0.0 };
2467            assert!(
2468                diff < 1e-4 || rel < 1e-3,
2469                "at index {i}: fast={f}, reference={r}, diff={diff}, rel={rel}",
2470            );
2471        }
2472    }
2473
2474    /// Reference attention (B=1, multi-head, GQA-aware) in plain Rust:
2475    /// `out = softmax( softcap(scale·QKᵀ) [+ causal -inf] ) · V`. q
2476    /// `[hq,sq,d]`, k/v `[hkv,sk,d]` (GQA: q-head `h` attends kv-head
2477    /// `h / (hq/hkv)`), out `[hq,sq,d]`.
2478    fn ref_attention(
2479        q: &[f32],
2480        k: &[f32],
2481        v: &[f32],
2482        hq: usize,
2483        hkv: usize,
2484        sq: usize,
2485        sk: usize,
2486        d: usize,
2487        scale: f32,
2488        causal: bool,
2489        softcap: Option<f32>,
2490        alibi: Option<&[f32]>,
2491    ) -> Vec<f32> {
2492        let g = hq / hkv;
2493        let mut out = vec![0.0f32; hq * sq * d];
2494        for h in 0..hq {
2495            let hk = h / g;
2496            let qh = &q[h * sq * d..(h + 1) * sq * d];
2497            let kh = &k[hk * sk * d..(hk + 1) * sk * d];
2498            let vh = &v[hk * sk * d..(hk + 1) * sk * d];
2499            for i in 0..sq {
2500                let mut scores = vec![0.0f32; sk];
2501                for j in 0..sk {
2502                    let mut s = 0.0f32;
2503                    for l in 0..d {
2504                        s += qh[i * d + l] * kh[j * d + l];
2505                    }
2506                    let mut sc = scale * s;
2507                    if let Some(cap) = softcap {
2508                        sc = cap * (sc / cap).tanh();
2509                    }
2510                    if let Some(slopes) = alibi {
2511                        // alibi bias = slope[h] · (key_pos - query_pos).
2512                        sc += slopes[h] * (j as f32 - i as f32);
2513                    }
2514                    scores[j] = if causal && j > i {
2515                        f32::NEG_INFINITY
2516                    } else {
2517                        sc
2518                    };
2519                }
2520                let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2521                let mut sum = 0.0f32;
2522                let exps: Vec<f32> = scores
2523                    .iter()
2524                    .map(|&s| {
2525                        let e = (s - m).exp();
2526                        sum += e;
2527                        e
2528                    })
2529                    .collect();
2530                for l in 0..d {
2531                    let mut o = 0.0f32;
2532                    for j in 0..sk {
2533                        o += (exps[j] / sum) * vh[j * d + l];
2534                    }
2535                    out[(h * sq + i) * d + l] = o;
2536                }
2537            }
2538        }
2539        out
2540    }
2541
2542    /// Numerical parity: lower a FlashAttn node to its primitive
2543    /// decomposition, realize it on CPU, and assert it matches the plain-Rust
2544    /// reference — verifying the recipe's *math* (scale·QKᵀ → softmax → ·V),
2545    /// the `Triu` `-inf` causal mask, GQA head-repeat, the `tanh` softcap, and
2546    /// the alibi bias (which is the sole config that lowers to `Op::Iota`).
2547    fn flash_decompose_vs_reference(
2548        hq: usize,
2549        hkv: usize,
2550        causal: bool,
2551        softcap: Option<f32>,
2552        alibi: bool,
2553    ) {
2554        let dev = Device::cpu();
2555        let (sq, sk, d) = (2usize, 2usize, 2usize);
2556        // deterministic, varied inputs so the comparison is meaningful.
2557        let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2558        let k_data: Vec<f32> = (0..hkv * sk * d).map(|i| (i as f32 * 0.13).cos()).collect();
2559        let v_data: Vec<f32> = (0..hkv * sk * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2560        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
2561        // swapping the exact constant would perturb these attention-scale parity tests.
2562        #[allow(clippy::approx_constant)]
2563        let scale = 0.7071f32;
2564        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2565        let k = q
2566            .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2567            .unwrap();
2568        let v = q
2569            .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, sk, d]))
2570            .unwrap();
2571        // Distinct positive slope per head (powers of 1/2 — the alibi default).
2572        let alibi_slopes: Option<Vec<f32>> = if alibi {
2573            Some((0..hq).map(|h| 0.5f32.powi(h as i32 + 1)).collect())
2574        } else {
2575            None
2576        };
2577        let alibi_t = alibi_slopes.as_ref().map(|s| {
2578            q.const_f32_like(s.clone(), Shape::from_dims(&[hq]))
2579                .unwrap()
2580        });
2581        let attn = q
2582            .flash_attn(&k, &v, alibi_t.as_ref(), scale, causal, None, None, softcap)
2583            .unwrap();
2584
2585        // Decompose explicitly, then realize the primitive subgraph.
2586        let graph = attn.inner.graph().clone();
2587        let id = attn.inner.id();
2588        let roots =
2589            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2590        assert_eq!(roots.len(), 1, "lowering should keep a single root");
2591        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
2592            .expect("realize decomposed FlashAttn on CPU");
2593
2594        let expected = ref_attention(
2595            &q_data,
2596            &k_data,
2597            &v_data,
2598            hq,
2599            hkv,
2600            sq,
2601            sk,
2602            d,
2603            scale,
2604            causal,
2605            softcap,
2606            alibi_slopes.as_deref(),
2607        );
2608        assert_eq!(got.len(), expected.len());
2609        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
2610            assert!(
2611                (g - e).abs() < 1e-4,
2612                "FlashAttn decompose mismatch (hq={hq} hkv={hkv} causal={causal} \
2613                 softcap={softcap:?} alibi={alibi}) at {i}: got {g}, expected {e}",
2614            );
2615        }
2616    }
2617
2618    // ---- FlashAttn on masked and NaN rows (ruling 2026-11-25; every path) ----
2619    // (1) a FULLY MASKED row (no key admitted by causal/window) is ZEROS; (2) a NaN in Q, or in
2620    // K/V at a position the query ATTENDS, makes that output NaN (never swallowed); (3) a NaN in a
2621    // V row whose key is MASKED OUT for a query is UNSPECIFIED: an implementation MAY ignore it (the
2622    // fused CPU kernel) or propagate it (the dense decomposition, Vulkan); the result depends on tile
2623    // geometry, so NO test pins either: the row must not crash and, if it is not NaN, must equal the
2624    // NaN-free reference; (4) normal rows are unaffected in a mixed batch.
2625
2626    struct AttnCase {
2627        name: &'static str,
2628        q: Vec<f32>,
2629        k: Vec<f32>,
2630        v: Vec<f32>,
2631        sq: usize,
2632        sk: usize,
2633        causal: bool,
2634        wl: Option<usize>,
2635    }
2636
2637    fn attn_cases() -> Vec<AttnCase> {
2638        let nan = f32::NAN;
2639        let bq = vec![0.5f32, -0.25, 0.1, 0.9, -0.4, 0.3];
2640        let bk = vec![0.3f32, 0.2, -0.1, 0.6];
2641        let bv = vec![1.0f32, 2.0, 3.0, 4.0];
2642        let c = |name, q: Vec<f32>, k: Vec<f32>, v: Vec<f32>, sq, sk, causal, wl| AttnCase {
2643            name,
2644            q,
2645            k,
2646            v,
2647            sq,
2648            sk,
2649            causal,
2650            wl,
2651        };
2652        vec![
2653            c(
2654                "control",
2655                bq[..4].to_vec(),
2656                bk.clone(),
2657                bv.clone(),
2658                2,
2659                2,
2660                false,
2661                None,
2662            ),
2663            // sq=3 > sk=2, causal, window_left=0: row 2 attends nothing.
2664            c(
2665                "fully-masked-row-mixed",
2666                bq.clone(),
2667                bk.clone(),
2668                bv.clone(),
2669                3,
2670                2,
2671                true,
2672                Some(0),
2673            ),
2674            c(
2675                "nan-q-row1",
2676                vec![0.5, -0.25, nan, 0.9],
2677                bk.clone(),
2678                bv.clone(),
2679                2,
2680                2,
2681                false,
2682                None,
2683            ),
2684            c(
2685                "nan-k-row1",
2686                bq[..4].to_vec(),
2687                vec![0.3, 0.2, nan, 0.6],
2688                bv.clone(),
2689                2,
2690                2,
2691                false,
2692                None,
2693            ),
2694            c(
2695                "nan-v-row1",
2696                bq[..4].to_vec(),
2697                bk.clone(),
2698                vec![1.0, 2.0, nan, 4.0],
2699                2,
2700                2,
2701                false,
2702                None,
2703            ),
2704            // PIP #715 M1: a non-finite score at a MASKED-OUT position must never reach the softmax.
2705            // sq=3 > sk=2, causal, window_left=0: row 2 attends nothing, and its Q is NaN. Contract (1)
2706            // "a fully masked row is zeros" takes precedence over (2) "NaN in Q makes the row NaN":
2707            // nothing is attended, so nothing is poisoned (the fused CPU kernel's result).
2708            c(
2709                "nan-q-fully-masked-row",
2710                vec![0.5, -0.25, 0.1, 0.9, nan, 0.3],
2711                bk.clone(),
2712                bv.clone(),
2713                3,
2714                2,
2715                true,
2716                Some(0),
2717            ),
2718            // Row 0 does not attend key 1 (causal); key 1 is NaN / +inf. Row 0 must be its NaN-free value.
2719            c(
2720                "nan-k-masked-key",
2721                bq[..4].to_vec(),
2722                vec![0.3, 0.2, nan, nan],
2723                bv.clone(),
2724                2,
2725                2,
2726                true,
2727                None,
2728            ),
2729            c(
2730                "inf-k-masked-key",
2731                bq[..4].to_vec(),
2732                vec![0.3, 0.2, f32::INFINITY, f32::INFINITY],
2733                bv.clone(),
2734                2,
2735                2,
2736                true,
2737                None,
2738            ),
2739            c(
2740                "nan-v-masked-key",
2741                bq[..4].to_vec(),
2742                bk.clone(),
2743                vec![1.0, 2.0, nan, 4.0],
2744                2,
2745                2,
2746                true,
2747                None,
2748            ),
2749        ]
2750    }
2751
2752    /// What one output element must be.
2753    #[derive(Debug, Clone, Copy)]
2754    enum Want {
2755        /// Must be NaN.
2756        Nan,
2757        /// Must equal this value within 1e-4.
2758        Val(f32),
2759        /// UNSPECIFIED (contract (3)): NaN is allowed; otherwise it must equal this NaN-free reference.
2760        NanOrVal(f32),
2761        /// Not asserted (the attended non-finite score row: a pre-existing fused/decomposed difference, PIP L1).
2762        Any,
2763    }
2764
2765    fn attn_expected(name: &str) -> Vec<Want> {
2766        use Want::{Any as a, Nan as n, NanOrVal as o, Val as s};
2767        match name {
2768            "control" => vec![s(1.8943309), s(2.894331), s(2.1126559), s(3.1126556)],
2769            "fully-masked-row-mixed" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2770            "nan-q-row1" => vec![s(1.8943309), s(2.894331), n, n],
2771            "nan-k-row1" => vec![n, n, n, n],
2772            "nan-v-row1" => vec![n, s(2.894331), n, s(3.1126556)],
2773            // Row 0 attends only key 0 (the NaN V row is masked out for it): UNSPECIFIED; the
2774            // NaN-free reference is [1, 2]. Row 1 attends the NaN V row: column 0 must be NaN.
2775            "nan-v-masked-key" => vec![o(1.0), o(2.0), n, s(3.1126556)],
2776            "nan-q-fully-masked-row" => vec![s(1.0), s(2.0), s(3.0), s(4.0), s(0.0), s(0.0)],
2777            "nan-k-masked-key" => vec![s(1.0), s(2.0), n, n],
2778            "inf-k-masked-key" => vec![s(1.0), s(2.0), a, a],
2779            other => panic!("no expectation for {other}"),
2780        }
2781    }
2782
2783    fn attn_check(name: &str, path: &str, got: &[f32], want: &[Want]) -> Option<String> {
2784        assert_eq!(got.len(), want.len(), "{name}/{path}");
2785        let bad: Vec<String> = got
2786            .iter()
2787            .zip(want)
2788            .enumerate()
2789            .filter(|(_, (g, w))| match w {
2790                Want::Nan => !g.is_nan(),
2791                Want::Val(x) => g.is_nan() || (**g - *x).abs() > 1e-4,
2792                Want::NanOrVal(x) => !g.is_nan() && (**g - *x).abs() > 1e-4,
2793                Want::Any => false,
2794            })
2795            .map(|(i, (g, w))| format!("[{i}] got {g} want {w:?}"))
2796            .collect();
2797        (!bad.is_empty()).then(|| format!("{name}/{path}: {}", bad.join("; ")))
2798    }
2799
2800    // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2: the expected values in
2801    // `attn_expected` were computed with exactly 0.7071 (same posture as `flash_decompose_vs_reference`).
2802    #[allow(clippy::approx_constant)]
2803    fn attn_tensor(c: &AttnCase) -> Tensor {
2804        let dev = Device::cpu();
2805        let q = Tensor::from_f32(c.q.clone(), Shape::from_dims(&[1, 1, c.sq, 2]), &dev).unwrap();
2806        let k = q
2807            .const_f32_like(c.k.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2808            .unwrap();
2809        let v = q
2810            .const_f32_like(c.v.clone(), Shape::from_dims(&[1, 1, c.sk, 2]))
2811            .unwrap();
2812        q.flash_attn(&k, &v, None, 0.7071, c.causal, c.wl, None, None)
2813            .unwrap()
2814    }
2815
2816    #[test]
2817    fn flash_attn_fused_cpu_follows_the_masked_and_nan_row_contract() {
2818        let mut bad = Vec::new();
2819        for c in attn_cases() {
2820            let got = attn_tensor(&c).realize_f32();
2821            bad.extend(attn_check(c.name, "fused", &got, &attn_expected(c.name)));
2822        }
2823        assert!(bad.is_empty(), "{bad:#?}");
2824    }
2825
2826    #[test]
2827    fn flash_attn_decomposed_cpu_follows_the_masked_and_nan_row_contract() {
2828        let mut bad = Vec::new();
2829        for c in attn_cases() {
2830            let attn = attn_tensor(&c);
2831            let graph = attn.inner.graph().clone();
2832            let id = attn.inner.id();
2833            let roots =
2834                fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2835            let got =
2836                crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
2837                    .expect("realize decomposed FlashAttn on CPU");
2838            bad.extend(attn_check(
2839                c.name,
2840                "decomposed",
2841                &got,
2842                &attn_expected(c.name),
2843            ));
2844        }
2845        assert!(bad.is_empty(), "{bad:#?}");
2846    }
2847
2848    #[test]
2849    fn flash_attn_decompose_vanilla() {
2850        flash_decompose_vs_reference(1, 1, false, None, false);
2851    }
2852
2853    #[test]
2854    fn flash_attn_decompose_causal() {
2855        flash_decompose_vs_reference(1, 1, true, None, false);
2856    }
2857
2858    #[test]
2859    fn flash_attn_decompose_gqa_causal() {
2860        flash_decompose_vs_reference(2, 1, true, None, false); // Hq=2, Hkv=1 (head-repeat)
2861    }
2862
2863    #[test]
2864    fn flash_attn_decompose_softcap() {
2865        flash_decompose_vs_reference(1, 1, false, Some(0.5), false); // small cap → tanh saturates
2866    }
2867
2868    #[test]
2869    fn flash_attn_decompose_alibi() {
2870        // alibi is the only config that lowers to Op::Iota (relative-position
2871        // values) — this exercises the new 0-input Iota execution path.
2872        flash_decompose_vs_reference(2, 2, false, None, true);
2873    }
2874
2875    #[test]
2876    fn flash_attn_decompose_alibi_causal() {
2877        flash_decompose_vs_reference(2, 2, true, None, true);
2878    }
2879
2880    /// Plain-Rust reference for **capacity-K decode attention**: attend `q`
2881    /// (`Sq` queries at absolute positions `[kl−Sq, kl)`) against the first
2882    /// `kl` keys/values of a `cap`-capacity KV buffer, with bottom-right
2883    /// causal masking (query `i` attends keys `j ≤ (kl−Sq)+i`). GQA folds
2884    /// `h → h/(Hq/Hkv)`.
2885    fn ref_decode_attn(
2886        q: &[f32],
2887        k: &[f32],
2888        v: &[f32],
2889        hq: usize,
2890        hkv: usize,
2891        sq: usize,
2892        cap: usize,
2893        kl: usize,
2894        d: usize,
2895        scale: f32,
2896        causal: bool,
2897    ) -> Vec<f32> {
2898        let g = hq / hkv;
2899        let offset = kl - sq;
2900        let mut out = vec![0f32; hq * sq * d];
2901        for h in 0..hq {
2902            let hk = h / g;
2903            for i in 0..sq {
2904                let qh = &q[((h * sq) + i) * d..][..d];
2905                let mut scores = vec![f32::NEG_INFINITY; kl];
2906                for j in 0..kl {
2907                    if causal && j > offset + i {
2908                        continue;
2909                    }
2910                    let kh = &k[((hk * cap) + j) * d..][..d];
2911                    let s: f32 = (0..d).map(|l| qh[l] * kh[l]).sum();
2912                    scores[j] = scale * s;
2913                }
2914                let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2915                let mut sum = 0f32;
2916                let exps: Vec<f32> = scores
2917                    .iter()
2918                    .map(|&s| {
2919                        let e = (s - m).exp();
2920                        sum += e;
2921                        e
2922                    })
2923                    .collect();
2924                for l in 0..d {
2925                    let mut o = 0f32;
2926                    for j in 0..kl {
2927                        o += (exps[j] / sum) * v[((hk * cap) + j) * d + l];
2928                    }
2929                    out[(h * sq + i) * d + l] = o;
2930                }
2931            }
2932        }
2933        out
2934    }
2935
2936    /// Recipe principle (G2): a **concrete** `k_len` FlashAttn is a *static*
2937    /// config that used to return self (`k_len.is_some()` short-circuit). It
2938    /// now decomposes: `Slice` K/V to the live prefix and run the SDPA recipe
2939    /// bottom-right-aligned (`q_pos_offset = kl − Sq`). RED before the fix (an
2940    /// `Op::Fused(FLASH_ATTN)` island survives lowering); GREEN after, matching
2941    /// the decode-attention reference. Uses GQA (Hq=2, Hkv=1), Sq=2 (so the
2942    /// offset causal band is exercised, not a Sq=1 no-op), capacity 4, kl=3.
2943    #[test]
2944    fn flash_attn_decompose_concrete_klen() {
2945        use fuel_graph::Op;
2946        use fuel_graph::registry::FusedOps;
2947        use fuel_ir::DynScalar;
2948        let dev = Device::cpu();
2949        let (hq, hkv, sq, cap, kl, d) = (2usize, 1usize, 2usize, 4usize, 3usize, 2usize);
2950        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
2951        // swapping the exact constant would perturb these attention-scale parity tests.
2952        #[allow(clippy::approx_constant)]
2953        let scale = 0.7071f32;
2954        let causal = true;
2955        let q_data: Vec<f32> = (0..hq * sq * d).map(|i| (i as f32 * 0.1).sin()).collect();
2956        let k_data: Vec<f32> = (0..hkv * cap * d)
2957            .map(|i| (i as f32 * 0.13).cos())
2958            .collect();
2959        let v_data: Vec<f32> = (0..hkv * cap * d).map(|i| i as f32 * 0.07 + 1.0).collect();
2960        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, hq, sq, d]), &dev).unwrap();
2961        let k = q
2962            .inner
2963            .const_f32_like(k_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2964            .unwrap();
2965        let v = q
2966            .inner
2967            .const_f32_like(v_data.clone(), Shape::from_dims(&[1, hkv, cap, d]))
2968            .unwrap();
2969        // Concrete k_len — the fused node that formerly returned self.
2970        let attn = q.inner.flash_attn_dyn(
2971            &k,
2972            &v,
2973            None,
2974            scale,
2975            causal,
2976            None,
2977            None,
2978            None,
2979            DynScalar::Concrete(kl),
2980        );
2981
2982        let graph = attn.graph().clone();
2983        let id = attn.id();
2984        let roots =
2985            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
2986        assert_eq!(roots.len(), 1, "lowering should keep a single root");
2987
2988        // Born-red discriminator: no Op::Fused(FLASH_ATTN) reachable from the root.
2989        {
2990            let g = graph.read().unwrap();
2991            let mut stack = vec![roots[0]];
2992            let mut seen = std::collections::HashSet::new();
2993            while let Some(nid) = stack.pop() {
2994                if !seen.insert(nid) {
2995                    continue;
2996                }
2997                let node = g.node(nid);
2998                assert!(
2999                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::FLASH_ATTN),
3000                    "concrete-k_len FlashAttn still fused after lowering (self-return)",
3001                );
3002                for &inp in &node.inputs {
3003                    stack.push(inp);
3004                }
3005            }
3006        }
3007
3008        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3009            .expect("realize decomposed concrete-k_len FlashAttn on CPU");
3010        let expected = ref_decode_attn(
3011            &q_data, &k_data, &v_data, hq, hkv, sq, cap, kl, d, scale, causal,
3012        );
3013        assert_eq!(got.len(), expected.len());
3014        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
3015            assert!(
3016                (gv - ev).abs() < 1e-4,
3017                "concrete-k_len decode mismatch at {i}: got {gv}, expected {ev}",
3018            );
3019        }
3020    }
3021
3022    /// Bit-exact comparison of two `f32` slices (via raw bit patterns), so a
3023    /// last-ULP divergence is not masked by `==` and NaNs compare by pattern.
3024    fn assert_f32_bits_eq(got: &[f32], want: &[f32], ctx: &str) {
3025        assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3026        for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3027            assert_eq!(
3028                g.to_bits(),
3029                w.to_bits(),
3030                "{ctx}: bit mismatch at {i}: got {g} (0x{:08x}), want {w} (0x{:08x})",
3031                g.to_bits(),
3032                w.to_bits(),
3033            );
3034        }
3035    }
3036
3037    /// Assert two positive-`f32` slices agree to within `max_ulp` ULPs. Used
3038    /// to document the (migration-orthogonal) 1-ULP gap between a primitive
3039    /// `Div` and the fused kernel's reciprocal-multiply.
3040    fn assert_f32_within_ulp(got: &[f32], want: &[f32], max_ulp: i64, ctx: &str) {
3041        assert_eq!(got.len(), want.len(), "{ctx}: length mismatch");
3042        for (i, (&g, &w)) in got.iter().zip(want).enumerate() {
3043            let d = (g.to_bits() as i64 - w.to_bits() as i64).abs();
3044            assert!(
3045                d <= max_ulp,
3046                "{ctx}: {d} ULP at {i} (> {max_ulp}): got {g} (0x{:08x}), want {w} (0x{:08x})",
3047                g.to_bits(),
3048                w.to_bits(),
3049            );
3050        }
3051    }
3052
3053    /// Real-backend accumulation-order parity for the Increment-C-slice-1
3054    /// "shrink-via-swap" reduce spellings (prior-review nit, I3).
3055    ///
3056    /// The migration parity tests in `fuel-graph`
3057    /// (`*_matches_frozen_legacy`) run BOTH the recipe decompose and the
3058    /// frozen legacy builder through a shared toy-`f64` reference
3059    /// interpreter, so they pin recipe STRUCTURE only and — by construction
3060    /// — cannot exercise the concern that the CPU backend's `SumDim`
3061    /// (reduction chassis `reduce`) and `ReduceSumTo` (chassis `reduce_to`),
3062    /// or `MaxDim` vs `ReduceMaxTo`, might accumulate a last-dim reduction in
3063    /// a DIFFERENT order and diverge in `f32`. The recipe swapped
3064    /// `ReduceSumTo(keepdim)` → `SumDim(last)`+`Unsqueeze` (and the max
3065    /// side likewise), so the two spellings dispatch two DIFFERENT CPU
3066    /// reduce kernels.
3067    ///
3068    /// This realizes both spellings as BARE reduce roots on the ACTUAL CPU
3069    /// backend — a bare reduce cannot re-fuse into a `SoftmaxLastDim`
3070    /// (no surrounding `Div`/`Exp`), and there is no `SumDim`↔`ReduceSumTo`
3071    /// canonicalization, so the two reduce kernels genuinely execute — over
3072    /// data engineered so a left-fold and a right-fold `f32` sum DIFFER,
3073    /// which gives the bit-exact equality real teeth. Result: bit-exact,
3074    /// because both chassis fold every element into its output slot in
3075    /// row-major flat order (`reduce`: `for flat in 0..total_input`;
3076    /// `reduce_to`: `for in_flat in 0..in_elems`).
3077    #[test]
3078    fn reduce_swap_sumdim_vs_reducesumto_bit_exact_on_cpu_backend() {
3079        let dev = Device::cpu();
3080        let (rows, cols) = (2usize, 4usize);
3081        // Each row is order-sensitive in f32 (catastrophic cancellation):
3082        // its left-fold sum differs from its right-fold sum, so bit-exact
3083        // equality of the two spellings is a NON-trivial statement about the
3084        // backend's accumulation order.
3085        let data: Vec<f32> = vec![1e8, 1.0, -1e8, 1.0, 3.0e7, 2.0, -3.0e7, -1.0];
3086
3087        // Independent host references: fold each row left-to-right and
3088        // right-to-left in f32. They disagree — the data is adversarial.
3089        let mut left_fold = vec![0.0f32; rows];
3090        let mut right_fold = vec![0.0f32; rows];
3091        for r in 0..rows {
3092            let row = &data[r * cols..(r + 1) * cols];
3093            let mut acc = 0.0f32;
3094            for &v in row.iter() {
3095                acc += v;
3096            }
3097            left_fold[r] = acc;
3098            let mut acc_r = 0.0f32;
3099            for &v in row.iter().rev() {
3100                acc_r += v;
3101            }
3102            right_fold[r] = acc_r;
3103        }
3104        assert_ne!(
3105            left_fold, right_fold,
3106            "test data must be accumulation-order-sensitive so the parity has teeth",
3107        );
3108
3109        let x = Tensor::from_f32(data.clone(), Shape::from_dims(&[rows, cols]), &dev).unwrap();
3110        // Recipe spelling: rank-reducing SumDim(last) (chassis `reduce`).
3111        let sumdim = x.inner.sum_dim(1);
3112        let got_sumdim = crate::pipelined_bridge::realize_one_as::<f32>(
3113            &sumdim.graph().clone(),
3114            sumdim.id(),
3115            &dev,
3116        )
3117        .expect("realize SumDim(last) on CPU");
3118        // Legacy spelling: ReduceSumTo(keepdim [rows,1]) (chassis `reduce_to`).
3119        let reducesumto = x.inner.reduce_sum_to(Shape::from_dims(&[rows, 1]));
3120        let got_reducesumto = crate::pipelined_bridge::realize_one_as::<f32>(
3121            &reducesumto.graph().clone(),
3122            reducesumto.id(),
3123            &dev,
3124        )
3125        .expect("realize ReduceSumTo(keepdim) on CPU");
3126
3127        // The load-bearing parity: the two reduce kernels agree bit-exactly.
3128        assert_f32_bits_eq(&got_sumdim, &got_reducesumto, "SumDim vs ReduceSumTo");
3129        // Correctness + which order: both equal the row-major left-fold (and,
3130        // because the data is adversarial, NOT the right-fold).
3131        assert_f32_bits_eq(&got_sumdim, &left_fold, "SumDim vs left-fold");
3132
3133        // Max side: MaxDim(last) (chassis `reduce`) vs ReduceMaxTo(keepdim)
3134        // (chassis `reduce_to`). Max is order-independent, but the swap still
3135        // dispatches two DIFFERENT CPU kernels; confirm they agree bit-exactly
3136        // and equal the per-row maximum.
3137        let maxdim = x.inner.max_dim(1);
3138        let got_maxdim = crate::pipelined_bridge::realize_one_as::<f32>(
3139            &maxdim.graph().clone(),
3140            maxdim.id(),
3141            &dev,
3142        )
3143        .expect("realize MaxDim(last) on CPU");
3144        let reducemaxto = x.inner.reduce_max_to(Shape::from_dims(&[rows, 1]));
3145        let got_reducemaxto = crate::pipelined_bridge::realize_one_as::<f32>(
3146            &reducemaxto.graph().clone(),
3147            reducemaxto.id(),
3148            &dev,
3149        )
3150        .expect("realize ReduceMaxTo(keepdim) on CPU");
3151        let row_max: Vec<f32> = (0..rows)
3152            .map(|r| {
3153                data[r * cols..(r + 1) * cols]
3154                    .iter()
3155                    .cloned()
3156                    .fold(f32::NEG_INFINITY, f32::max)
3157            })
3158            .collect();
3159        assert_f32_bits_eq(&got_maxdim, &got_reducemaxto, "MaxDim vs ReduceMaxTo");
3160        assert_f32_bits_eq(&got_maxdim, &row_max, "MaxDim vs per-row max");
3161    }
3162
3163    /// End-to-end real-backend parity for the migrated `SoftmaxLastDim`
3164    /// (Increment C slice 1 pilot, I3). The migration swapped the keepdim
3165    /// reduce spelling `ReduceMaxTo`/`ReduceSumTo(keepdim)` →
3166    /// `MaxDim`/`SumDim(last)` + `Unsqueeze(append)` (the D3 shrink-via-swap).
3167    /// This realizes the WHOLE softmax on the ACTUAL CPU backend two ways and
3168    /// asserts the swap is numerically inert:
3169    /// * RECIPE path — `lowering_only` lowers the fused node to its recipe
3170    ///   (`SumDim`/`MaxDim` spelling) primitive subgraph, then realize it;
3171    /// * LEGACY path — the pre-migration `ReduceMaxTo`/`ReduceSumTo` primitive
3172    ///   subgraph, hand-built here with the same `Sub`/`Exp`/`Div`.
3173    ///
3174    /// The two must be BIT-EXACT: `reduce_swap_…` proves `SumDim`≡`ReduceSumTo`
3175    /// and `MaxDim`≡`ReduceMaxTo` bit-exactly on the CPU backend, and every
3176    /// other node (and the true-`Div` normalize) is identical, so the whole
3177    /// pipeline agrees to the bit. (The runtime-fusion pass does NOT re-fuse
3178    /// either primitive subgraph back to the `SoftmaxLastDim` kernel — see the
3179    /// secondary assertion, which measures the migration-ORTHOGONAL 1-ULP gap
3180    /// between the primitive `Div` and the fused kernel's reciprocal-multiply
3181    /// `e*(1/sum)`.) Adversarial mixed-magnitude rows make it non-trivial.
3182    #[test]
3183    fn softmax_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3184        let dev = Device::cpu();
3185        let (rows, cols) = (3usize, 5usize);
3186        let data: Vec<f32> = (0..rows * cols)
3187            .map(|i| ((i as f32) * 0.37).sin() * 4.0 - (i as f32) * 0.11)
3188            .collect();
3189        let shape = || Shape::from_dims(&[rows, cols]);
3190        let keepdim = || Shape::from_dims(&[rows, 1]);
3191
3192        // RECIPE path: lower the fused node to the recipe (SumDim spelling).
3193        let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3194            .unwrap()
3195            .softmax_last_dim()
3196            .expect("softmax recipe build");
3197        let graph = recipe.inner.graph().clone();
3198        let id = recipe.inner.id();
3199        let roots =
3200            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3201        assert_eq!(roots.len(), 1, "lowering keeps a single root");
3202        let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3203            .expect("realize recipe-decomposed softmax on CPU");
3204
3205        // LEGACY path: the pre-migration ReduceMaxTo/ReduceSumTo(keepdim)
3206        // spelling, hand-built with identical Sub/Exp/Div.
3207        let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3208        let m = x.reduce_max_to(keepdim());
3209        let mb = m.broadcast_to(shape());
3210        let s = x.sub(&mb);
3211        let e = s.exp();
3212        let d = e.reduce_sum_to(keepdim());
3213        let db = d.broadcast_to(shape());
3214        let legacy = e.div(&db);
3215        let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3216            &legacy.graph().clone(),
3217            legacy.id(),
3218            &dev,
3219        )
3220        .expect("realize legacy softmax on CPU");
3221
3222        // PRIMARY: the migration is numerically inert — bit-exact.
3223        assert_f32_bits_eq(&recipe_out, &legacy_out, "softmax recipe vs legacy");
3224        // Sanity: it is a real softmax (each row sums to ~1).
3225        for r in 0..rows {
3226            let sum: f32 = recipe_out[r * cols..(r + 1) * cols].iter().sum();
3227            assert!((sum - 1.0).abs() < 1e-5, "row {r} softmax sum = {sum}");
3228        }
3229
3230        // SECONDARY (documentation): the fused/production kernel differs by
3231        // at most 1 ULP — NOT from the migration but from its reciprocal-
3232        // multiply normalize (`e*(1/sum)`) vs the primitive true-`Div`.
3233        let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3234            .unwrap()
3235            .softmax_last_dim()
3236            .expect("softmax fused build")
3237            .realize_f32();
3238        assert_f32_within_ulp(&recipe_out, &fused_out, 1, "softmax recipe vs fused kernel");
3239    }
3240
3241    /// End-to-end real-backend parity for the migrated `RmsNormLastDim`
3242    /// (Increment C slice 1, T7, I3) — the norm counterpart of
3243    /// `softmax_last_dim_recipe_decompose_matches_legacy_on_cpu`. Here the D3
3244    /// shrink-via-swap replaced the keepdim `Reshape` with `Unsqueeze`
3245    /// (append) while the reducing `MeanDim(last)` is UNCHANGED, so the swap
3246    /// is metadata-only; the recipe-decompose realize must match a hand-built
3247    /// legacy `Reshape`-keepdim subgraph bit-exactly on the CPU backend.
3248    #[test]
3249    fn rms_norm_last_dim_recipe_decompose_matches_legacy_on_cpu() {
3250        let dev = Device::cpu();
3251        let (rows, cols) = (3usize, 6usize);
3252        let eps = 1e-6f64;
3253        let data: Vec<f32> = (0..rows * cols)
3254            .map(|i| ((i as f32) * 0.29).cos() * 2.5 + 0.5)
3255            .collect();
3256        let shape = || Shape::from_dims(&[rows, cols]);
3257        let keepdim = || Shape::from_dims(&[rows, 1]);
3258
3259        // RECIPE path: lower the fused node (MeanDim + Unsqueeze spelling).
3260        let recipe = Tensor::from_f32(data.clone(), shape(), &dev)
3261            .unwrap()
3262            .rms_norm_last_dim(eps)
3263            .expect("rms_norm recipe build");
3264        let graph = recipe.inner.graph().clone();
3265        let id = recipe.inner.id();
3266        let roots =
3267            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3268        assert_eq!(roots.len(), 1, "lowering keeps a single root");
3269        let recipe_out = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3270            .expect("realize recipe-decomposed rms_norm on CPU");
3271
3272        // LEGACY path: MeanDim(last) + Reshape-keepdim spelling, same eps and
3273        // same true-`Div` normalize.
3274        let x = Tensor::from_f32(data.clone(), shape(), &dev).unwrap().inner;
3275        let sq = x.sqr();
3276        let mean = sq.mean_dim(1);
3277        let mean_kd = mean.reshape(keepdim());
3278        let denom_sq = mean_kd.add_scalar(eps);
3279        let denom = denom_sq.sqrt();
3280        let denom_b = denom.broadcast_to(shape());
3281        let legacy = x.div(&denom_b);
3282        let legacy_out = crate::pipelined_bridge::realize_one_as::<f32>(
3283            &legacy.graph().clone(),
3284            legacy.id(),
3285            &dev,
3286        )
3287        .expect("realize legacy rms_norm on CPU");
3288
3289        // PRIMARY: the keepdim swap is metadata-only — bit-exact.
3290        assert_f32_bits_eq(&recipe_out, &legacy_out, "rms_norm recipe vs legacy");
3291
3292        // SECONDARY (documentation): the fused kernel's reciprocal-multiply
3293        // (`x*rms_inv`) differs from the primitive true-`Div` by ≤1 ULP.
3294        let fused_out = Tensor::from_f32(data.clone(), shape(), &dev)
3295            .unwrap()
3296            .rms_norm_last_dim(eps)
3297            .expect("rms_norm fused build")
3298            .realize_f32();
3299        assert_f32_within_ulp(
3300            &recipe_out,
3301            &fused_out,
3302            1,
3303            "rms_norm recipe vs fused kernel",
3304        );
3305    }
3306
3307    /// Recipe principle (G2/G3 — part 1): SelectiveScan is the constitution's
3308    /// canonical **basis gap** (a higher-order `Scan` primitive). Fuel now HAS
3309    /// that primitive (`Op::Scan`), so `decompose` lowers to it — closing G3.
3310    /// This test flips the former surfaced-gap posture: (a) NON-REGRESSION —
3311    /// the fused CPU kernel still realizes `y = 12`; (b) VERIFICATION —
3312    /// `lowering_only` leaves NO `Op::Fused(SELECTIVE_SCAN)`, an `Op::Scan`
3313    /// terminal is present, and `unroll_scan` + realize of the ys oracle
3314    /// contains `y = 12` (`h = 3`). The fused kernel remains the executed
3315    /// production path; the `Op::Scan` recipe is the optimizer base-map cover
3316    /// + the numeric verify oracle.
3317    #[test]
3318    fn selective_scan_decompose_lowers_to_scan_and_matches() {
3319        use fuel_graph::Op;
3320        use fuel_graph::registry::FusedOps;
3321        let dev = Device::cpu();
3322        let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3323        let delta = u
3324            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3325            .unwrap();
3326        let a = u
3327            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3328            .unwrap();
3329        let b = u
3330            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3331            .unwrap();
3332        let c = u
3333            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3334            .unwrap();
3335        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ false);
3336
3337        // (a) NON-REGRESSION: the fused kernel still runs and produces 12.0.
3338        let got = y.realize_f32();
3339        assert_eq!(got.len(), 1);
3340        assert!((got[0] - 12.0).abs() < 1e-4, "fused kernel y: {}", got[0]);
3341
3342        // (b) VERIFICATION: lowering leaves NO Op::Fused(SELECTIVE_SCAN); an
3343        // Op::Scan terminal is present; unroll+realize matches h=3,y=12.
3344        let graph = y.inner.graph().clone();
3345        let id = y.inner.id();
3346        let roots =
3347            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3348        assert_eq!(roots.len(), 1);
3349        let scan_id = {
3350            let g = graph.read().unwrap();
3351            let mut stack = vec![roots[0]];
3352            let mut seen = std::collections::HashSet::new();
3353            let mut scan_id = None;
3354            while let Some(nid) = stack.pop() {
3355                if !seen.insert(nid) {
3356                    continue;
3357                }
3358                let node = g.node(nid);
3359                assert!(
3360                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SELECTIVE_SCAN),
3361                    "SelectiveScan must lower to Op::Scan, not remain fused"
3362                );
3363                if matches!(node.op, Op::Scan { .. }) {
3364                    scan_id = Some(nid);
3365                }
3366                for &inp in &node.inputs {
3367                    stack.push(inp);
3368                }
3369            }
3370            scan_id.expect("an Op::Scan terminal must be present after lowering")
3371        };
3372        // Unroll the Op::Scan (seqlen = 1) and realize the ys oracle.
3373        let ys = {
3374            let mut g = graph.write().unwrap();
3375            fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3376                .expect("unroll")
3377                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3378        };
3379        let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3380            .expect("realize unrolled selective_scan oracle on CPU");
3381        assert!(
3382            oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3383            "unroll oracle must contain y = 12, got {oracle:?}"
3384        );
3385    }
3386
3387    /// Recipe principle (G2/G3 — part 2): SsdChunkScan (Mamba-2's State-Space
3388    /// Duality scan) was the constitution's twin **basis gap** to SelectiveScan.
3389    /// Fuel now HAS the higher-order `Op::Scan` primitive, so `decompose` lowers
3390    /// to it — closing G3 part 2. The SSD recurrence carries a per-head SCALAR
3391    /// gate `exp(dt·a_h)` (`a` is `[heads]`, broadcast across the whole
3392    /// `head_dim×state_dim` block), with NO softplus. This test mirrors the
3393    /// SelectiveScan gate test: (a) NON-REGRESSION — the fused CPU kernel still
3394    /// realizes `y = 12`; (b) VERIFICATION — `lowering_only` leaves NO
3395    /// `Op::Fused(SSD_CHUNK_SCAN)`, an `Op::Scan` terminal is present, and
3396    /// `unroll_scan` + realize of the ys oracle contains `y = 12`.
3397    /// Fixture (batch=heads=head_dim=state_dim=1, seqlen=chunk_size=1):
3398    /// `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`.
3399    #[test]
3400    fn ssd_chunk_scan_decompose_lowers_to_scan_and_matches() {
3401        use fuel_graph::Op;
3402        use fuel_graph::registry::FusedOps;
3403        let dev = Device::cpu();
3404        // x [batch, seqlen, heads, head_dim] = [1,1,1,1]; dt [b,s,h]=[1,1,1];
3405        // a [heads]=[1]; b/c [b,s,h,state]=[1,1,1,1].
3406        let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3407        let dt = x
3408            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3409            .unwrap();
3410        let a = x
3411            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3412            .unwrap();
3413        let b = x
3414            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3415            .unwrap();
3416        let c = x
3417            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3418            .unwrap();
3419        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, /* chunk_size */ 1);
3420
3421        // (a) NON-REGRESSION: the fused kernel still runs and produces 12.0.
3422        let got = y.realize_f32();
3423        assert!(
3424            (got[0] - 12.0).abs() < 1e-4,
3425            "fused ssd kernel y: {}",
3426            got[0]
3427        );
3428
3429        // (b) VERIFICATION: lowering leaves NO Op::Fused(SSD_CHUNK_SCAN); an
3430        // Op::Scan terminal is present; unroll+realize matches h=3, y=12.
3431        let graph = y.inner.graph().clone();
3432        let id = y.inner.id();
3433        let roots =
3434            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
3435        let scan_id = {
3436            let g = graph.read().unwrap();
3437            let mut stack = vec![roots[0]];
3438            let mut seen = std::collections::HashSet::new();
3439            let mut scan_id = None;
3440            while let Some(nid) = stack.pop() {
3441                if !seen.insert(nid) {
3442                    continue;
3443                }
3444                let node = g.node(nid);
3445                assert!(
3446                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::SSD_CHUNK_SCAN),
3447                    "SsdChunkScan must lower to Op::Scan, not remain fused"
3448                );
3449                if matches!(node.op, Op::Scan { .. }) {
3450                    scan_id = Some(nid);
3451                }
3452                for &inp in &node.inputs {
3453                    stack.push(inp);
3454                }
3455            }
3456            scan_id.expect("an Op::Scan terminal must be present after lowering")
3457        };
3458        let ys = {
3459            let mut g = graph.write().unwrap();
3460            fuel_graph::scan::unroll_scan(&mut g, scan_id, 1)
3461                .expect("unroll")
3462                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3463        };
3464        let oracle = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
3465            .expect("realize unrolled ssd_chunk_scan oracle on CPU");
3466        assert!(
3467            oracle.iter().any(|&v| (v - 12.0).abs() < 1e-4),
3468            "oracle y=12, got {oracle:?}"
3469        );
3470    }
3471
3472    // ---- Op::Scan Phase 2 (C3/C4/C5): numeric BPTT finite-difference gates ---
3473    //
3474    // Prove the lower_scans_for_backward pre-pass gradients are correct against
3475    // finite differences over the SAME unrolled graph (self-consistent, decoupled
3476    // from kernel F64-accumulate parity). These need realize, so they live here.
3477
3478    #[test]
3479    fn affine_scan_bptt_matches_finite_difference() {
3480        use fuel_graph::{Node, NodeHandle, Op, ScanEmit, ScanRole};
3481        use fuel_ir::{DType, Shape};
3482        let dev = Device::cpu();
3483        // f(init, a, b): carry_{t+1} = a*carry_t + b, carry_0 = init, bound = 3, loss = carry_3.
3484        // Closed form: carry_3 = a^3*init + b*(a^2 + a + 1). d/dinit = a^3.
3485        let build = |init_v: f32,
3486                     a_v: f32,
3487                     b_v: f32|
3488         -> (
3489            std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
3490            fuel_graph::NodeId,
3491            fuel_graph::NodeHandle,
3492            fuel_graph::NodeHandle,
3493            fuel_graph::NodeHandle,
3494        ) {
3495            let init =
3496                NodeHandle::from_f32(vec![init_v], Shape::from_dims(&[1]), dev.as_dyn()).unwrap();
3497            let g = init.graph().clone();
3498            let a = NodeHandle::from_existing(g.clone(), init.id())
3499                .const_f32_like(vec![a_v], Shape::from_dims(&[1]))
3500                .unwrap();
3501            let b = NodeHandle::from_existing(g.clone(), init.id())
3502                .const_f32_like(vec![b_v], Shape::from_dims(&[1]))
3503                .unwrap();
3504            let nc = {
3505                let mut gw = g.write().unwrap();
3506                let s = Shape::from_dims(&[1]);
3507                let hole = gw.push(Node {
3508                    op: Op::ScanPlaceholder {
3509                        role: ScanRole::Carry,
3510                        index: 0,
3511                    },
3512                    inputs: vec![],
3513                    shape: s.clone(),
3514                    dtype: DType::F32,
3515                });
3516                let ac = gw.push(Node {
3517                    op: Op::Mul,
3518                    inputs: vec![a.id(), hole],
3519                    shape: s.clone(),
3520                    dtype: DType::F32,
3521                });
3522                gw.push(Node {
3523                    op: Op::Add,
3524                    inputs: vec![ac, b.id()],
3525                    shape: s.clone(),
3526                    dtype: DType::F32,
3527                })
3528            };
3529            let nc_t = NodeHandle::from_existing(g.clone(), nc);
3530            let out = init
3531                .scan(
3532                    &[],
3533                    &[a.clone(), b.clone()],
3534                    &nc_t,
3535                    &nc_t,
3536                    3,
3537                    ScanEmit::Final,
3538                )
3539                .expect("scan");
3540            (g, out.id(), init, a, b)
3541        };
3542        // Forward value via unroll+realize (self-consistent oracle).
3543        let fwd = |init_v: f32, a_v: f32, b_v: f32| -> f32 {
3544            let (g, out_id, _i, _a, _b) = build(init_v, a_v, b_v);
3545            let scan_id = {
3546                let gr = g.read().unwrap();
3547                gr.node(out_id).inputs[0]
3548            };
3549            let carry = {
3550                let mut gw = g.write().unwrap();
3551                fuel_graph::scan::unroll_scan(&mut gw, scan_id, 3)
3552                    .expect("unroll")
3553                    .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
3554            }; // emit=Final -> selected=final_carry
3555            crate::pipelined_bridge::realize_one_as::<f32>(&g, carry, &dev).expect("realize")[0]
3556        };
3557        // Autograd grad w.r.t. init at (1.0, 0.5, 0.1).
3558        let (g, out_id, init, a, b) = build(1.0, 0.5, 0.1);
3559        let out = fuel_graph::NodeHandle::from_existing(g.clone(), out_id);
3560        let grads = out.backward();
3561        let realize_grad = |t: &fuel_graph::NodeHandle| {
3562            crate::pipelined_bridge::realize_one_as::<f32>(
3563                &g,
3564                grads.get(t).expect("grad").id(),
3565                &dev,
3566            )
3567            .expect("realize grad")[0]
3568        };
3569        let g_init = realize_grad(&init);
3570        let g_a = realize_grad(&a);
3571        let g_b = realize_grad(&b);
3572        // Central finite differences.
3573        let h = 1e-3f32;
3574        let fd = |dinit: f32, da: f32, db: f32| {
3575            (fwd(1.0 + dinit, 0.5 + da, 0.1 + db) - fwd(1.0 - dinit, 0.5 - da, 0.1 - db))
3576                / (2.0 * h)
3577        };
3578        assert!(
3579            (g_init - fd(h, 0.0, 0.0)).abs() < 2e-2,
3580            "d/dinit: autograd {g_init} vs FD {}",
3581            fd(h, 0.0, 0.0)
3582        );
3583        assert!(
3584            (g_a - fd(0.0, h, 0.0)).abs() < 2e-2,
3585            "d/da: autograd {g_a} vs FD {}",
3586            fd(0.0, h, 0.0)
3587        );
3588        assert!(
3589            (g_b - fd(0.0, 0.0, h)).abs() < 2e-2,
3590            "d/db: autograd {g_b} vs FD {}",
3591            fd(0.0, 0.0, h)
3592        );
3593    }
3594
3595    #[test]
3596    fn selective_scan_is_differentiable_backward_matches_fd() {
3597        let dev = Device::cpu();
3598        let fwd = |u_v: f32| -> f32 {
3599            let u = Tensor::from_f32(vec![u_v], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3600            let delta = u
3601                .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3602                .unwrap();
3603            let a = u
3604                .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3605                .unwrap();
3606            let b = u
3607                .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3608                .unwrap();
3609            let c = u
3610                .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3611                .unwrap();
3612            u.selective_scan(&delta, &a, &b, &c, false).realize_f32()[0]
3613        };
3614        // Autograd at u=2.0.
3615        let u = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1]), &dev).unwrap();
3616        let delta = u
3617            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3618            .unwrap();
3619        let a = u
3620            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1, 1]))
3621            .unwrap();
3622        let b = u
3623            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1]))
3624            .unwrap();
3625        let c = u
3626            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1]))
3627            .unwrap();
3628        let y = u.selective_scan(&delta, &a, &b, &c, false);
3629        let grads = y.inner.backward();
3630        let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3631        let g_u =
3632            crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3633                .expect("realize")[0];
3634        let h = 1e-3;
3635        let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3636        assert!(
3637            (g_u - fd).abs() < 5e-2,
3638            "selective_scan d/du: autograd {g_u} vs FD {fd}"
3639        );
3640    }
3641
3642    #[test]
3643    fn ssd_chunk_scan_is_differentiable_backward_matches_fd() {
3644        let dev = Device::cpu();
3645        // x [batch,seqlen,heads,head_dim]=[1,1,1,1]; dt [b,s,h]=[1,1,1]; a [heads]=[1];
3646        // b/c [b,s,h,state]=[1,1,1,1]. Single step: h = dt*b*x = 1.5x, y = c*h = 6x (linear).
3647        let fwd = |x_v: f32| -> f32 {
3648            let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3649            let dt = x
3650                .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3651                .unwrap();
3652            let a = x
3653                .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3654                .unwrap();
3655            let b = x
3656                .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3657                .unwrap();
3658            let c = x
3659                .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3660                .unwrap();
3661            x.ssd_chunk_scan(&dt, &a, &b, &c, 1).realize_f32()[0]
3662        };
3663        // Autograd at x=2.0.
3664        let x = Tensor::from_f32(vec![2.0f32], Shape::from_dims(&[1, 1, 1, 1]), &dev).unwrap();
3665        let dt = x
3666            .const_f32_like(vec![0.5f32], Shape::from_dims(&[1, 1, 1]))
3667            .unwrap();
3668        let a = x
3669            .const_f32_like(vec![-1.0f32], Shape::from_dims(&[1]))
3670            .unwrap();
3671        let b = x
3672            .const_f32_like(vec![3.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3673            .unwrap();
3674        let c = x
3675            .const_f32_like(vec![4.0f32], Shape::from_dims(&[1, 1, 1, 1]))
3676            .unwrap();
3677        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 1);
3678        let grads = y.inner.backward();
3679        let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
3680        let g_x =
3681            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
3682                .expect("realize")[0];
3683        let h = 1e-3;
3684        let fd = (fwd(2.0 + h) - fwd(2.0 - h)) / (2.0 * h);
3685        assert!(
3686            (g_x - fd).abs() < 5e-2,
3687            "ssd_chunk_scan d/dx: autograd {g_x} vs FD {fd}"
3688        );
3689    }
3690
3691    /// Autograd gradient of `act(x)` at a scalar `x`, and the central finite
3692    /// difference of the functional forward at the same point.
3693    fn act_grad_and_fd(
3694        x_v: f32,
3695        act: impl Fn(&Tensor) -> Tensor,
3696        fd_act: impl Fn(&Tensor) -> Tensor,
3697    ) -> (f32, f32) {
3698        let dev = Device::cpu();
3699        let x = Tensor::from_f32(vec![x_v], Shape::from_dims(&[1]), &dev).unwrap();
3700        let y = act(&x);
3701        let grads = y.inner.backward();
3702        let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3703        let g =
3704            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3705                .expect("realize")[0];
3706        let fwd = |v: f32| -> f32 {
3707            let t = Tensor::from_f32(vec![v], Shape::from_dims(&[1]), &dev).unwrap();
3708            fd_act(&t).realize_f32()[0]
3709        };
3710        let h = 1e-2f32;
3711        (g, (fwd(x_v + h) - fwd(x_v - h)) / (2.0 * h))
3712    }
3713
3714    /// GeluTanh backward used to panic ("inference-only"); it must now match
3715    /// the finite difference of the forward across the curve, including the
3716    /// negative lobe and x = 0.
3717    #[test]
3718    fn gelu_tanh_backward_matches_finite_difference() {
3719        for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3720            let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh(), |x| x.gelu_tanh());
3721            assert!(
3722                (g - fd).abs() < 2e-3,
3723                "gelu_tanh d/dx at {x_v}: autograd {g} vs FD {fd}"
3724            );
3725        }
3726    }
3727
3728    /// Same gradient through the in-place op (its input is read pre-mutation).
3729    #[test]
3730    fn gelu_tanh_inplace_backward_matches_finite_difference() {
3731        for x_v in [-3.0f32, -1.5, -0.5, 0.0, 0.3, 1.0, 2.5] {
3732            let (g, fd) = act_grad_and_fd(x_v, |x| x.gelu_tanh_inplace(), |x| x.gelu_tanh());
3733            assert!(
3734                (g - fd).abs() < 2e-3,
3735                "gelu_tanh_inplace d/dx at {x_v}: autograd {g} vs FD {fd}"
3736            );
3737        }
3738    }
3739
3740    /// Retained sabotage sibling: the finite-difference harness must be able to
3741    /// tell GeluTanh's derivative from a wrong one. SiLU's autograd gradient is
3742    /// checked against GeluTanh's FD at a point where they differ by far more
3743    /// than the tolerance above; if this ever passes the tolerance the two
3744    /// gates above have gone vacuous.
3745    #[test]
3746    fn finite_difference_harness_rejects_a_wrong_activation_gradient() {
3747        let (g_silu, fd_gelu) = act_grad_and_fd(-1.5, |x| x.silu(), |x| x.gelu_tanh());
3748        assert!(
3749            (g_silu - fd_gelu).abs() > 2e-2,
3750            "silu grad {g_silu} too close to gelu_tanh FD {fd_gelu}: harness cannot discriminate"
3751        );
3752    }
3753
3754    /// Autograd gradient of `sum(build(x))` wrt the input `x` and its central
3755    /// finite difference, per element. `build` receives the differentiated
3756    /// input (a graph leaf) and must build every other operand on its graph.
3757    fn grad_vs_fd(
3758        x_vals: &[f32],
3759        x_shape: &[usize],
3760        build: impl Fn(&Tensor) -> Tensor,
3761    ) -> (Vec<f32>, Vec<f32>) {
3762        grad_vs_fd_impl(x_vals, x_shape, build, false)
3763    }
3764
3765    /// As [`grad_vs_fd`], for a fused op with no backend kernel: the FORWARD
3766    /// values are realized after lowering the fused node to primitives.
3767    fn grad_vs_fd_lowered(
3768        x_vals: &[f32],
3769        x_shape: &[usize],
3770        build: impl Fn(&Tensor) -> Tensor,
3771    ) -> (Vec<f32>, Vec<f32>) {
3772        grad_vs_fd_impl(x_vals, x_shape, build, true)
3773    }
3774
3775    fn grad_vs_fd_impl(
3776        x_vals: &[f32],
3777        x_shape: &[usize],
3778        build: impl Fn(&Tensor) -> Tensor,
3779        lower_forward: bool,
3780    ) -> (Vec<f32>, Vec<f32>) {
3781        let dev = Device::cpu();
3782        let x = Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3783        let y = build(&x);
3784        let grads = y.inner.backward();
3785        let g_id = grads.get(x.graph_tensor()).expect("grad x").id();
3786        let g =
3787            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_id, &dev)
3788                .expect("realize");
3789        let fwd_sum = |vals: &[f32]| -> f32 {
3790            let t = Tensor::from_f32(vals.to_vec(), Shape::from_dims(x_shape), &dev).unwrap();
3791            let y = build(&t);
3792            if lower_forward {
3793                let graph = y.inner.graph().clone();
3794                let roots = fuel_graph::opt::RuleRegistry::lowering_only()
3795                    .optimize_to_fixpoint(&graph, &[y.inner.id()]);
3796                crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
3797                    .expect("realize lowered forward")
3798                    .iter()
3799                    .sum()
3800            } else {
3801                y.realize_f32().iter().sum()
3802            }
3803        };
3804        let h = 1e-2f32;
3805        let fd = (0..x_vals.len())
3806            .map(|i| {
3807                let (mut p, mut m) = (x_vals.to_vec(), x_vals.to_vec());
3808                p[i] += h;
3809                m[i] -= h;
3810                (fwd_sum(&p) - fwd_sum(&m)) / (2.0 * h)
3811            })
3812            .collect();
3813        (g, fd)
3814    }
3815
3816    fn assert_grad_close(label: &str, g: &[f32], fd: &[f32]) {
3817        assert_eq!(g.len(), fd.len(), "{label}: length");
3818        for (i, (a, b)) in g.iter().zip(fd).enumerate() {
3819            assert!(
3820                (a - b).abs() < 5e-3 + 5e-3 * b.abs(),
3821                "{label}[{i}]: autograd {a} vs FD {b}"
3822            );
3823        }
3824    }
3825
3826    /// A fused op with no hand-written backward arm used to reach the "no
3827    /// backward arm wired yet" panic. Its total `decompose` is differentiable,
3828    /// so the backward pre-pass now lowers it first (ROADMAP item 17, H11).
3829    #[test]
3830    fn nf4_matmul_activation_gradient_matches_finite_difference() {
3831        let (g, fd) = grad_vs_fd(&[1.0, 2.0, 2.0, 4.0], &[1, 4], |act| {
3832            let w_packed = Tensor::from_graph_tensor(
3833                act.graph_tensor()
3834                    .const_u8_like(vec![247_u8, 247, 127, 127], Shape::from_dims(&[2, 2]))
3835                    .unwrap(),
3836            );
3837            let absmax = act
3838                .const_f32_like(vec![1.0_f32, 2.0, 10.0, 20.0], Shape::from_dims(&[2, 2]))
3839                .unwrap();
3840            act.nf4_matmul(&w_packed, &absmax, 2)
3841        });
3842        assert_grad_close("nf4_matmul d/dact", &g, &fd);
3843    }
3844
3845    /// AWQ: arbitrary packed words are valid data (any nibble is a code), so a
3846    /// fixed set of words exercises the decompose's dequantize-then-matmul
3847    /// path under autograd. Kernel layout: `K = 64`, `group_size = 64`
3848    /// (`zeros_w = 2`), `N = 8`.
3849    #[test]
3850    fn awq_matmul_activation_gradient_matches_finite_difference() {
3851        let x_vals: Vec<f32> = (0..64).map(|k| ((k * 7) % 13) as f32 * 0.1 - 0.6).collect();
3852        let (g, fd) = grad_vs_fd_lowered(&x_vals, &[1, 64], |act| {
3853            let words: Vec<u32> = (0..64u32)
3854                .map(|i| i.wrapping_mul(0x9E37_79B1) ^ 0x1234_5678)
3855                .collect();
3856            let weight = act
3857                .graph_tensor()
3858                .const_u32_like(words, Shape::from_dims(&[8, 8]))
3859                .unwrap();
3860            let zeros = act
3861                .graph_tensor()
3862                .const_u32_like(vec![0x7777_7777; 16], Shape::from_dims(&[8, 2]))
3863                .unwrap();
3864            let scales: Vec<half::f16> = (0..128)
3865                .map(|i| half::f16::from_f32(0.05 + 0.01 * (i % 7) as f32))
3866                .collect();
3867            let scales = act
3868                .const_f16_like(scales, Shape::from_dims(&[8, 16]))
3869                .unwrap();
3870            Tensor::from_graph_tensor(act.graph_tensor().awq_matmul(
3871                &weight,
3872                &zeros,
3873                scales.graph_tensor(),
3874                64,
3875                8,
3876            ))
3877        });
3878        assert_grad_close("awq_matmul d/dact", &g, &fd);
3879    }
3880
3881    #[test]
3882    fn causal_conv1d_weight_and_bias_gradients_match_finite_difference() {
3883        let x_data = vec![0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7];
3884        for use_silu in [false, true] {
3885            // d/dweight: weight is the differentiated leaf.
3886            let (g, fd) = grad_vs_fd(&[0.5, -0.25, 0.75, 0.1, 0.9, -0.4], &[2, 1, 3], |w| {
3887                let x = w
3888                    .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3889                    .unwrap();
3890                let b = w
3891                    .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3892                    .unwrap();
3893                x.causal_conv1d(w, &b, use_silu)
3894            });
3895            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dw"), &g, &fd);
3896            // d/dbias.
3897            let (g, fd) = grad_vs_fd(&[0.05, -0.05], &[2], |b| {
3898                let x = b
3899                    .const_f32_like(x_data.clone(), Shape::from_dims(&[1, 2, 4]))
3900                    .unwrap();
3901                let w = b
3902                    .const_f32_like(
3903                        vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3904                        Shape::from_dims(&[2, 1, 3]),
3905                    )
3906                    .unwrap();
3907                x.causal_conv1d(&w, b, use_silu)
3908            });
3909            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dbias"), &g, &fd);
3910        }
3911    }
3912
3913    #[test]
3914    fn causal_conv1d_input_gradient_matches_finite_difference() {
3915        // x [1, 2, 4] (channels 2, seq 2, kernel 3 -> left-padded length 4).
3916        for use_silu in [false, true] {
3917            let (g, fd) = grad_vs_fd(
3918                &[0.3, -0.5, 0.8, 0.1, -0.2, 0.6, 0.4, -0.7],
3919                &[1, 2, 4],
3920                |x| {
3921                    let w = x
3922                        .const_f32_like(
3923                            vec![0.5, -0.25, 0.75, 0.1, 0.9, -0.4],
3924                            Shape::from_dims(&[2, 1, 3]),
3925                        )
3926                        .unwrap();
3927                    let b = x
3928                        .const_f32_like(vec![0.05, -0.05], Shape::from_dims(&[2]))
3929                        .unwrap();
3930                    x.causal_conv1d(&w, &b, use_silu)
3931                },
3932            );
3933            assert_grad_close(&format!("causal_conv1d(silu={use_silu}) d/dx"), &g, &fd);
3934        }
3935    }
3936
3937    // Review Fix 2: the seqlen=1 SSM gates above multiply exp(dt*a) by a zero
3938    // initial carry, so `y` is linear in the input and the multi-step recurrent
3939    // gate is never FD-checked for the SSM ops. These seqlen>=2 gates carry a
3940    // NON-ZERO h across steps (a < 0), so d(sum y)/d(early input) flows THROUGH
3941    // the gate exp(dt*a) — the multi-step BPTT the headline SSM deliverable needs.
3942
3943    #[test]
3944    fn selective_scan_seqlen2_bptt_matches_finite_difference() {
3945        let dev = Device::cpu();
3946        // u/delta [batch,seqlen,dim]=[1,2,1]; a [dim,dstate]=[1,1] (< 0, stable gate);
3947        // b/c [batch,seqlen,dstate]=[1,2,1]. loss = sum(y) (ones-seed over [1,2,1]).
3948        let fwd = |u_vals: &[f32]| -> f32 {
3949            let u = Tensor::from_f32(u_vals.to_vec(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3950            let delta = u
3951                .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3952                .unwrap();
3953            let a = u
3954                .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3955                .unwrap();
3956            let b = u
3957                .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3958                .unwrap();
3959            let c = u
3960                .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3961                .unwrap();
3962            u.selective_scan(&delta, &a, &b, &c, false)
3963                .realize_f32()
3964                .iter()
3965                .sum()
3966        };
3967        let u0 = vec![1.0f32, 2.0];
3968        let u = Tensor::from_f32(u0.clone(), Shape::from_dims(&[1, 2, 1]), &dev).unwrap();
3969        let delta = u
3970            .const_f32_like(vec![0.7f32, 0.7], Shape::from_dims(&[1, 2, 1]))
3971            .unwrap();
3972        let a = u
3973            .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1, 1]))
3974            .unwrap();
3975        let b = u
3976            .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3977            .unwrap();
3978        let c = u
3979            .const_f32_like(vec![1.0f32, 1.0], Shape::from_dims(&[1, 2, 1]))
3980            .unwrap();
3981        let y = u.selective_scan(&delta, &a, &b, &c, false);
3982        let grads = y.inner.backward(); // ones-seed over [1,2,1] == grad of sum(y)
3983        let g_u_id = grads.get(u.graph_tensor()).expect("grad u").id();
3984        let g_u =
3985            crate::pipelined_bridge::realize_one_as::<f32>(&u.inner.graph().clone(), g_u_id, &dev)
3986                .expect("realize");
3987        // FD over u_1 (index 0): d(sum y)/d u_1 = dB + c*exp(dt*a)*dB — the second
3988        // term is the recurrent gate carrying u_1 into y_2.
3989        let h = 1e-3f32;
3990        let mut up = u0.clone();
3991        up[0] += h;
3992        let mut um = u0.clone();
3993        um[0] -= h;
3994        let fd0 = (fwd(&up) - fwd(&um)) / (2.0 * h);
3995        assert!(
3996            (g_u[0] - fd0).abs() < 5e-2,
3997            "selective_scan seqlen2 dL/du_1: autograd {} vs FD {fd0}",
3998            g_u[0]
3999        );
4000        // Non-triviality: the gate contribution makes this strictly > the pure-dB
4001        // seqlen=1 grad — a real, non-vacuous multi-step gradient (~1.19 here).
4002        assert!(
4003            g_u[0].abs() > 0.5,
4004            "recurrent-gate grad must be non-trivial, got {g_u:?}"
4005        );
4006    }
4007
4008    #[test]
4009    fn ssd_chunk_scan_seqlen4_chunk2_bptt_matches_finite_difference() {
4010        let dev = Device::cpu();
4011        // seqlen=4, chunk=2 -> a 2-CHUNK Op::Scan (bound=2): the inter-chunk state
4012        // carry passes exp(dt*a) across chunks. x [b,s,h,hd]=[1,4,1,1]; dt [b,s,h]=[1,4,1];
4013        // a [heads]=[1] (< 0); b/c [b,s,h,state]=[1,4,1,1].
4014        let fwd = |x_vals: &[f32]| -> f32 {
4015            let x =
4016                Tensor::from_f32(x_vals.to_vec(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4017            let dt = x
4018                .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4019                .unwrap();
4020            let a = x
4021                .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4022                .unwrap();
4023            let b = x
4024                .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4025                .unwrap();
4026            let c = x
4027                .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4028                .unwrap();
4029            x.ssd_chunk_scan(&dt, &a, &b, &c, 2)
4030                .realize_f32()
4031                .iter()
4032                .sum()
4033        };
4034        let x0 = vec![1.0f32, 2.0, 3.0, 4.0];
4035        let x = Tensor::from_f32(x0.clone(), Shape::from_dims(&[1, 4, 1, 1]), &dev).unwrap();
4036        let dt = x
4037            .const_f32_like(vec![0.6f32, 0.6, 0.6, 0.6], Shape::from_dims(&[1, 4, 1]))
4038            .unwrap();
4039        let a = x
4040            .const_f32_like(vec![-0.5f32], Shape::from_dims(&[1]))
4041            .unwrap();
4042        let b = x
4043            .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4044            .unwrap();
4045        let c = x
4046            .const_f32_like(vec![1.0f32, 1.0, 1.0, 1.0], Shape::from_dims(&[1, 4, 1, 1]))
4047            .unwrap();
4048        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, 2);
4049        let grads = y.inner.backward();
4050        let g_x_id = grads.get(x.graph_tensor()).expect("grad x").id();
4051        let g_x =
4052            crate::pipelined_bridge::realize_one_as::<f32>(&x.inner.graph().clone(), g_x_id, &dev)
4053                .expect("realize");
4054        // FD over x_0 (a chunk-0 input): its contribution to y_3/y_4 (chunk 1)
4055        // rides the cross-chunk gate exp(dt*a) — multi-step BPTT.
4056        let h = 1e-3f32;
4057        let mut xp = x0.clone();
4058        xp[0] += h;
4059        let mut xm = x0.clone();
4060        xm[0] -= h;
4061        let fd0 = (fwd(&xp) - fwd(&xm)) / (2.0 * h);
4062        assert!(
4063            (g_x[0] - fd0).abs() < 5e-2,
4064            "ssd_chunk_scan seqlen4 dL/dx_0: autograd {} vs FD {fd0}",
4065            g_x[0]
4066        );
4067        assert!(
4068            g_x[0].abs() > 0.5,
4069            "cross-chunk-gate grad must be non-trivial, got {g_x:?}"
4070        );
4071    }
4072
4073    // ---- Task 8: general-dimension SSM parity gate (C7 non-regression) ------
4074    //
4075    // The all-1s gap-test fixtures above (Task 6/7) share a single flat order
4076    // across every axis, so they cannot catch an axis transposition in the
4077    // decompose. The tests below run each SSM op at DISTINGUISHING multi-dim
4078    // sizes and assert the `unroll_scan` oracle (over the lowered `Op::Scan`)
4079    // matches the fused kernel element-wise, which is only possible if every
4080    // per-step slice / broadcast / reduce axis in the Task-6/7 decompose lines
4081    // up with the kernel's layout.
4082
4083    /// Walk the lowered graph from `root`, assert NO `Op::Fused(fused_id)`
4084    /// survives the `lowering_only()` pass, and return the `Op::Scan` terminal
4085    /// the decompose emitted (there must be exactly one on the SSM path).
4086    fn find_scan_terminal(
4087        graph: &std::sync::Arc<std::sync::RwLock<fuel_graph::Graph>>,
4088        root: fuel_graph::NodeId,
4089        fused_id: fuel_graph::registry::FusedOpId,
4090    ) -> fuel_graph::NodeId {
4091        use fuel_graph::Op;
4092        let g = graph.read().unwrap();
4093        let mut stack = vec![root];
4094        let mut seen = std::collections::HashSet::new();
4095        let mut scan_id = None;
4096        while let Some(nid) = stack.pop() {
4097            if !seen.insert(nid) {
4098                continue;
4099            }
4100            let node = g.node(nid);
4101            assert!(
4102                !matches!(node.op, Op::Fused(fid, _) if fid == fused_id),
4103                "SSM op must lower to Op::Scan, not remain fused",
4104            );
4105            if matches!(node.op, Op::Scan { .. }) {
4106                scan_id = Some(nid);
4107            }
4108            for &inp in &node.inputs {
4109                stack.push(inp);
4110            }
4111        }
4112        scan_id.expect("an Op::Scan terminal must be present after lowering")
4113    }
4114
4115    /// Reindex a flat row-major `[seqlen, batch, tail]` buffer — the layout
4116    /// `unroll_scan` stacks its per-step ys into (scan axis 0) — to
4117    /// `[batch, seqlen, tail]`, the fused kernel's `y` layout, so the two align
4118    /// element-wise. `tail` is the product of the trailing per-token dims (`dim`
4119    /// for selective_scan; `heads*head_dim` for ssd) — a contiguous block whose
4120    /// internal order is preserved by the batch/seqlen swap.
4121    ///
4122    /// This is done in host code deliberately: the executor treats `Op::Permute`
4123    /// as a metadata-only view (shared bytes + strided layout), so realizing a
4124    /// `Permute` *root* can hand back byte-shared storage still in seqlen-major
4125    /// order — an unreliable comparand. Realizing the contiguous unroll `Concat`
4126    /// (`ys`) and permuting the flat host bytes here is unambiguous.
4127    fn scan_ys_to_fused_layout(ys: &[f32], seqlen: usize, batch: usize, tail: usize) -> Vec<f32> {
4128        assert_eq!(ys.len(), seqlen * batch * tail, "ys layout mismatch");
4129        let mut out = vec![0f32; ys.len()];
4130        for s in 0..seqlen {
4131            for bb in 0..batch {
4132                for t in 0..tail {
4133                    out[(bb * seqlen + s) * tail + t] = ys[(s * batch + bb) * tail + t];
4134                }
4135            }
4136        }
4137        out
4138    }
4139
4140    /// Task 8 (part 1) — `selective_scan` general-dimension parity.
4141    ///
4142    /// **C7 non-regression:** `PipelinedExecutor::realize` dispatches
4143    /// `Op::Fused(SELECTIVE_SCAN)` **directly** to its kernel and never runs a
4144    /// `RuleRegistry` lowering pass, so `decompose`→`Op::Scan` is reached ONLY by
4145    /// the `lowering_only()` verification below — the fused kernel is the
4146    /// executed path *by construction*. The `realize_f32()` leg (a) is the proof
4147    /// the fused kernel still runs (no `O(seqlen)` unroll on the hot path).
4148    ///
4149    /// **Distinguishing dims** batch=2, seqlen=3, dim=2, dstate=2 with EVERY
4150    /// element distinct and asymmetric: `u`/`delta` index `dim`, `b`/`c` index
4151    /// `dstate`, and `a` is a full `[dim,dstate]` gate — so a dim↔dstate
4152    /// broadcast swap multiplies wrong pairs, and because `h` threads across the
4153    /// (order-sensitive) seqlen recurrence, a batch↔seqlen transpose changes the
4154    /// result. The all-1s fixture cannot see either; this can.
4155    #[test]
4156    fn selective_scan_multidim_unroll_matches_fused_kernel() {
4157        use fuel_graph::registry::FusedOps;
4158        let dev = Device::cpu();
4159        let (batch, seqlen, dim, dstate) = (2usize, 3usize, 2usize, 2usize);
4160        // [batch, seqlen, dim] — all distinct, mixed signs.
4161        let u = Tensor::from_f32(
4162            vec![
4163                0.5, -0.3, 1.0, 0.2, -0.5, 0.7, 0.25, 0.9, -0.8, 0.4, 0.6, -0.1,
4164            ],
4165            Shape::from_dims(&[batch, seqlen, dim]),
4166            &dev,
4167        )
4168        .unwrap();
4169        // [batch, seqlen, dim] — positive (delta is a rate); all distinct.
4170        let delta = u
4171            .const_f32_like(
4172                vec![
4173                    0.1, 0.2, 0.3, 0.15, 0.25, 0.4, 0.35, 0.05, 0.2, 0.3, 0.12, 0.28,
4174                ],
4175                Shape::from_dims(&[batch, seqlen, dim]),
4176            )
4177            .unwrap();
4178        // [dim, dstate] — negative (Mamba a<0 → stable gate in (0,1)); distinct.
4179        let a = u
4180            .const_f32_like(
4181                vec![-0.7, -0.3, -0.5, -0.9],
4182                Shape::from_dims(&[dim, dstate]),
4183            )
4184            .unwrap();
4185        // [batch, seqlen, dstate] — distinct.
4186        let b = u
4187            .const_f32_like(
4188                vec![
4189                    1.0, 0.5, 0.25, 0.75, 0.6, 0.2, 0.8, 0.4, 0.3, 0.9, 0.55, 0.15,
4190                ],
4191                Shape::from_dims(&[batch, seqlen, dstate]),
4192            )
4193            .unwrap();
4194        // [batch, seqlen, dstate] — distinct.
4195        let c = u
4196            .const_f32_like(
4197                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],
4198                Shape::from_dims(&[batch, seqlen, dstate]),
4199            )
4200            .unwrap();
4201        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ false);
4202
4203        // (a) Fused kernel (executed production path) runs and is well-shaped.
4204        let fused = y.realize_f32();
4205        assert_eq!(fused.len(), batch * seqlen * dim);
4206
4207        // (b) Unroll oracle over the lowered Op::Scan matches the fused kernel.
4208        let graph = y.inner.graph().clone();
4209        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4210            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4211        assert_eq!(roots.len(), 1);
4212        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4213        let ys = {
4214            let mut g = graph.write().unwrap();
4215            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4216                .expect("unroll")
4217                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4218        };
4219        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4220            .expect("realize selective_scan unroll oracle on CPU");
4221        // ys is [seqlen,batch,dim]; fused y is [batch,seqlen,dim].
4222        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4223        assert_eq!(oracle.len(), fused.len());
4224        let mut max_drift = 0f32;
4225        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4226            let d = (o - f).abs();
4227            max_drift = max_drift.max(d);
4228            // 1e-3 sabotage-calibrated: native-F32 unroll vs F64-accumulate
4229            // kernel. Honest drift here is ~1e-6 (printed); a batch/seqlen or
4230            // dim/dstate transpose diverges by O(0.1..10) — far above 1e-3.
4231            assert!(
4232                d < 1e-3,
4233                "selective_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4234            );
4235        }
4236        eprintln!("selective_scan multidim: max honest drift = {max_drift:e}");
4237    }
4238
4239    /// Task 8 (part 1, softplus) — `selective_scan` with `delta_softplus=true`,
4240    /// the branch unexercised at T=1. `delta` carries mixed-sign values so the
4241    /// stable softplus form `Relu(x)+Log(1+Exp(Neg(Abs(x))))` does real work on
4242    /// both the `x>0` and `x<0` sides before the scan. Same fused-vs-oracle
4243    /// parity as the non-softplus case.
4244    #[test]
4245    fn selective_scan_softplus_multitoken_unroll_matches_fused_kernel() {
4246        use fuel_graph::registry::FusedOps;
4247        let dev = Device::cpu();
4248        let (batch, seqlen, dim, dstate) = (1usize, 3usize, 2usize, 2usize);
4249        let u = Tensor::from_f32(
4250            vec![0.5, -0.3, 1.0, 0.2, -0.5, 0.7],
4251            Shape::from_dims(&[batch, seqlen, dim]),
4252            &dev,
4253        )
4254        .unwrap();
4255        // Mixed signs → softplus exercises max(x,0) AND ln(1+exp(-|x|)).
4256        let delta = u
4257            .const_f32_like(
4258                vec![-0.5, 0.2, 0.8, -1.0, 0.3, -0.2],
4259                Shape::from_dims(&[batch, seqlen, dim]),
4260            )
4261            .unwrap();
4262        let a = u
4263            .const_f32_like(
4264                vec![-0.7, -0.3, -0.5, -0.9],
4265                Shape::from_dims(&[dim, dstate]),
4266            )
4267            .unwrap();
4268        let b = u
4269            .const_f32_like(
4270                vec![1.0, 0.5, 0.25, 0.75, 0.6, 0.2],
4271                Shape::from_dims(&[batch, seqlen, dstate]),
4272            )
4273            .unwrap();
4274        let c = u
4275            .const_f32_like(
4276                vec![2.0, 1.0, 0.5, 1.5, 0.8, 0.3],
4277                Shape::from_dims(&[batch, seqlen, dstate]),
4278            )
4279            .unwrap();
4280        let y = u.selective_scan(&delta, &a, &b, &c, /* delta_softplus */ true);
4281
4282        let fused = y.realize_f32();
4283        assert_eq!(fused.len(), batch * seqlen * dim);
4284
4285        let graph = y.inner.graph().clone();
4286        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4287            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4288        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SELECTIVE_SCAN);
4289        let ys = {
4290            let mut g = graph.write().unwrap();
4291            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4292                .expect("unroll")
4293                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4294        };
4295        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4296            .expect("realize selective_scan softplus oracle on CPU");
4297        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, dim);
4298        let mut max_drift = 0f32;
4299        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4300            let d = (o - f).abs();
4301            max_drift = max_drift.max(d);
4302            assert!(
4303                d < 1e-3,
4304                "selective_scan softplus mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4305            );
4306        }
4307        eprintln!("selective_scan softplus: max honest drift = {max_drift:e}");
4308    }
4309
4310    /// Task 8 (part 2) — `ssd_chunk_scan` general-dimension parity.
4311    ///
4312    /// **C7 non-regression** (same construction as part 1): the executor
4313    /// dispatches `Op::Fused(SSD_CHUNK_SCAN)` straight to its kernel; the
4314    /// `decompose`→`Op::Scan` recipe is reached only by `lowering_only()` here.
4315    ///
4316    /// **Distinguishing dims** batch=2, seqlen=4, heads=2, head_dim=2,
4317    /// state_dim=2, chunk_size=2. Per-head `a = [-0.6, -1.0]` (head 0's gate
4318    /// leaking into head 1 flips the decay); `x` (indexes head_dim), `b`/`c`
4319    /// (index state_dim) use three DIFFERENT value ramps, so a head_dim↔state_dim
4320    /// broadcast swap (`bc_x` vs `bc_state`) mixes the wrong axes, and the
4321    /// seqlen recurrence + batch↔seqlen permute are exercised because batch>1.
4322    /// Every element is distinct.
4323    #[test]
4324    fn ssd_chunk_scan_multidim_unroll_matches_fused_kernel() {
4325        use fuel_graph::registry::FusedOps;
4326        let dev = Device::cpu();
4327        let (batch, seqlen, heads, head_dim, state_dim, chunk) =
4328            (2usize, 4usize, 2usize, 2usize, 2usize, 2usize);
4329        // Distinct value ramps (different base + slope per tensor) guarantee no
4330        // accidental symmetry; dt stays positive, a stays negative (stable gate).
4331        let x_data: Vec<f32> = (0..batch * seqlen * heads * head_dim)
4332            .map(|i| 0.20 + 0.05 * i as f32)
4333            .collect();
4334        let dt_data: Vec<f32> = (0..batch * seqlen * heads)
4335            .map(|i| 0.10 + 0.04 * i as f32)
4336            .collect();
4337        let b_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4338            .map(|i| 0.15 + 0.03 * i as f32)
4339            .collect();
4340        let c_data: Vec<f32> = (0..batch * seqlen * heads * state_dim)
4341            .map(|i| 0.25 + 0.035 * i as f32)
4342            .collect();
4343        let x = Tensor::from_f32(
4344            x_data,
4345            Shape::from_dims(&[batch, seqlen, heads, head_dim]),
4346            &dev,
4347        )
4348        .unwrap();
4349        let dt = x
4350            .const_f32_like(dt_data, Shape::from_dims(&[batch, seqlen, heads]))
4351            .unwrap();
4352        let a = x
4353            .const_f32_like(vec![-0.6f32, -1.0], Shape::from_dims(&[heads]))
4354            .unwrap();
4355        let b = x
4356            .const_f32_like(b_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4357            .unwrap();
4358        let c = x
4359            .const_f32_like(c_data, Shape::from_dims(&[batch, seqlen, heads, state_dim]))
4360            .unwrap();
4361        let y = x.ssd_chunk_scan(&dt, &a, &b, &c, chunk);
4362
4363        // (a) Fused kernel (executed production path) runs and is well-shaped.
4364        let fused = y.realize_f32();
4365        assert_eq!(fused.len(), batch * seqlen * heads * head_dim);
4366
4367        // (b) Unroll oracle over the lowered Op::Scan matches the fused kernel.
4368        let graph = y.inner.graph().clone();
4369        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4370            .optimize_to_fixpoint(&graph, &[y.inner.id()]);
4371        assert_eq!(roots.len(), 1);
4372        let scan_id = find_scan_terminal(&graph, roots[0], FusedOps::SSD_CHUNK_SCAN);
4373        let ys = {
4374            let mut g = graph.write().unwrap();
4375            fuel_graph::scan::unroll_scan(&mut g, scan_id, seqlen)
4376                .expect("unroll")
4377                .0[0] // GAP-303: selected side is a Vec; emit=All => one stacked ys
4378        };
4379        let ys_flat = crate::pipelined_bridge::realize_one_as::<f32>(&graph, ys, &dev)
4380            .expect("realize ssd_chunk_scan unroll oracle on CPU");
4381        // ys is [seqlen,batch,heads,head_dim]; fused y is
4382        // [batch,seqlen,heads,head_dim]. tail = heads*head_dim (contiguous).
4383        let oracle = scan_ys_to_fused_layout(&ys_flat, seqlen, batch, heads * head_dim);
4384        assert_eq!(oracle.len(), fused.len());
4385        let mut max_drift = 0f32;
4386        for (i, (o, f)) in oracle.iter().zip(fused.iter()).enumerate() {
4387            let d = (o - f).abs();
4388            max_drift = max_drift.max(d);
4389            assert!(
4390                d < 1e-3,
4391                "ssd_chunk_scan multidim mismatch at {i}: oracle {o} vs fused {f} (drift {d})",
4392            );
4393        }
4394        eprintln!("ssd_chunk_scan multidim: max honest drift = {max_drift:e}");
4395    }
4396
4397    /// Recipe principle (G2): Nf4Matmul must decompose to a **fused-free**
4398    /// primitive subgraph whose realize matches the fused kernel. RED before
4399    /// the total decompose landed (the self-return left an
4400    /// `Op::Fused(NF4_MATMUL)` opaque island in the base map); GREEN after.
4401    /// Uses the hand-computed two-outputs / two-blocks case (expected `[10,
4402    /// 50]`) shared with `fuel_cpu_backend`'s byte-kernel test, so the
4403    /// indicator-sum codebook + nibble unpack + per-block scale are checked
4404    /// against the same numbers the fused CPU kernel produces.
4405    #[test]
4406    fn nf4_matmul_decompose_matches_kernel() {
4407        use fuel_graph::Op;
4408        use fuel_graph::registry::FusedOps;
4409        let dev = Device::cpu();
4410        // n=2, k=4, block_size=2; w_packed [2, 2] U8, absmax [2, 2] F32.
4411        let weight = crate::nf4::nf4_from_bytes(
4412            vec![247_u8, 247, 127, 127],
4413            vec![1.0_f32, 2.0, 10.0, 20.0],
4414            2,
4415            4,
4416            2,
4417            &dev,
4418        )
4419        .expect("nf4_from_bytes");
4420        let act = Tensor::from_graph_tensor(
4421            weight
4422                .w_packed
4423                .graph_tensor()
4424                .const_f32_like(vec![1.0_f32, 2.0, 2.0, 4.0], Shape::from_dims(&[1, 4]))
4425                .unwrap(),
4426        );
4427        let y = weight.matmul(&act);
4428
4429        // Decompose explicitly, then realize the primitive subgraph.
4430        let graph = y.inner.graph().clone();
4431        let id = y.inner.id();
4432        let roots =
4433            fuel_graph::opt::RuleRegistry::lowering_only().optimize_to_fixpoint(&graph, &[id]);
4434        assert_eq!(roots.len(), 1, "lowering should keep a single root");
4435
4436        // Born-red discriminator: no Op::Fused(NF4_MATMUL) reachable from the
4437        // realized root — a self-returning decompose fails exactly here.
4438        {
4439            let g = graph.read().unwrap();
4440            let mut stack = vec![roots[0]];
4441            let mut seen = std::collections::HashSet::new();
4442            while let Some(nid) = stack.pop() {
4443                if !seen.insert(nid) {
4444                    continue;
4445                }
4446                let node = g.node(nid);
4447                assert!(
4448                    !matches!(node.op, Op::Fused(fid, _) if fid == FusedOps::NF4_MATMUL),
4449                    "decomposed graph still contains an Op::Fused(NF4_MATMUL) island",
4450                );
4451                for &inp in &node.inputs {
4452                    stack.push(inp);
4453                }
4454            }
4455        }
4456
4457        let got = crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &dev)
4458            .expect("realize decomposed Nf4Matmul on CPU");
4459        assert_eq!(got.len(), 2);
4460        assert!((got[0] - 10.0).abs() < 1e-4, "out 0: {}", got[0]);
4461        assert!((got[1] - 50.0).abs() < 1e-4, "out 1: {}", got[1]);
4462    }
4463
4464    /// Build a one-output fused-op node directly on `anchor`'s graph, lower it
4465    /// to primitives, realize on CPU, and return the F32 values. The decompose
4466    /// parity tests for backward helpers use this — those ops have no public
4467    /// builder (autograd creates them), so the test constructs the
4468    /// `Op::Fused` node by hand.
4469    fn lower_realize_fused(
4470        anchor: &Tensor,
4471        op: fuel_graph::Op,
4472        inputs: Vec<fuel_graph::NodeId>,
4473        shape: Shape,
4474    ) -> Vec<f32> {
4475        let graph = anchor.inner.graph().clone();
4476        let fused_id = {
4477            let mut g = graph.write().unwrap();
4478            g.push(fuel_graph::Node {
4479                op,
4480                inputs,
4481                shape,
4482                dtype: DType::F32,
4483            })
4484        };
4485        let roots = fuel_graph::opt::RuleRegistry::lowering_only()
4486            .optimize_to_fixpoint(&graph, &[fused_id]);
4487        assert_eq!(roots.len(), 1, "lowering keeps a single root");
4488        crate::pipelined_bridge::realize_one_as::<f32>(&graph, roots[0], &Device::cpu())
4489            .expect("realize decomposed fused op on CPU")
4490    }
4491
4492    #[test]
4493    fn powi_backward_decompose_matches_reference() {
4494        use fuel_graph::registry::{FusedOpParams, FusedOps};
4495        let dev = Device::cpu();
4496        let exp = 3i32;
4497        let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4498        let up_data = vec![1.0f32, 0.5, 2.0, -1.0];
4499        let shape = Shape::from_dims(&[4]);
4500        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4501        let up = x.const_f32_like(up_data.clone(), shape.clone()).unwrap();
4502        let got = lower_realize_fused(
4503            &x,
4504            fuel_graph::Op::Fused(FusedOps::POWI_BACKWARD, FusedOpParams::PowIBackward { exp }),
4505            vec![x.inner.id(), up.inner.id()],
4506            shape,
4507        );
4508        // grad_x = exp · x^(exp-1) · upstream
4509        let expected: Vec<f32> = x_data
4510            .iter()
4511            .zip(&up_data)
4512            .map(|(&x, &u)| exp as f32 * x.powi(exp - 1) * u)
4513            .collect();
4514        assert_eq!(got.len(), expected.len());
4515        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4516            assert!(
4517                (g - e).abs() < 1e-4,
4518                "powi_backward at {i}: got {g}, expected {e}"
4519            );
4520        }
4521    }
4522
4523    /// Increment C — `inplace_affine`'s migrated functional value recipe:
4524    /// `decompose` lowers `Op::Fused(INPLACE_AFFINE, {mul, add})` to
4525    /// `AddScalar(add)(MulScalar(mul)(x))`, which realizes on the CPU backend to
4526    /// the plain affine `mul·x + add`. Bit-exact: the affine kernel pre-casts the
4527    /// f64 scalars to f32 and computes `mul_f32 * x + add_f32`, so the two-op
4528    /// `MulScalar`→`AddScalar` composition matches a hand `(mul as f32)*x + (add
4529    /// as f32)` exactly (the intermediate `* 1.0` / `+ 0.0` are IEEE identities).
4530    #[test]
4531    fn inplace_affine_decompose_matches_affine_reference() {
4532        use fuel_graph::registry::{FusedOpParams, FusedOps};
4533        let dev = Device::cpu();
4534        let (mul, add) = (2.5f64, -1.0f64);
4535        let x_data = vec![1.5f32, -2.0, 0.5, 3.0];
4536        let shape = Shape::from_dims(&[4]);
4537        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4538        let got = lower_realize_fused(
4539            &x,
4540            fuel_graph::Op::Fused(
4541                FusedOps::INPLACE_AFFINE,
4542                FusedOpParams::InplaceAffine { mul, add },
4543            ),
4544            vec![x.inner.id()],
4545            shape,
4546        );
4547        // functional affine: out = mul·x + add (scalars pre-cast to f32).
4548        let expected: Vec<f32> = x_data
4549            .iter()
4550            .map(|&v| (mul as f32) * v + add as f32)
4551            .collect();
4552        assert_eq!(got.len(), expected.len());
4553        for (i, (&g, &e)) in got.iter().zip(&expected).enumerate() {
4554            assert_eq!(g, e, "inplace_affine at {i}: got {g}, expected {e}");
4555        }
4556    }
4557
4558    #[test]
4559    fn softmax_last_dim_backward_decompose_matches_reference() {
4560        use fuel_graph::registry::{FusedOpParams, FusedOps};
4561        let dev = Device::cpu();
4562        let (rows, cols) = (2usize, 3usize);
4563        // s = a real softmax over the last dim; g = arbitrary upstream.
4564        let logits = [[0.5f32, -1.0, 2.0], [1.0, 0.0, -0.5]];
4565        let mut s_data = Vec::new();
4566        for row in &logits {
4567            let m = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4568            let exps: Vec<f32> = row.iter().map(|&v| (v - m).exp()).collect();
4569            let sum: f32 = exps.iter().sum();
4570            s_data.extend(exps.iter().map(|&e| e / sum));
4571        }
4572        let g_data = vec![1.0f32, -0.5, 0.3, 0.2, 1.5, -1.0];
4573        let shape = Shape::from_dims(&[rows, cols]);
4574        let s = Tensor::from_f32(s_data.clone(), shape.clone(), &dev).unwrap();
4575        let g = s.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4576        let got = lower_realize_fused(
4577            &s,
4578            fuel_graph::Op::Fused(
4579                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
4580                FusedOpParams::SoftmaxLastDimBackward,
4581            ),
4582            vec![s.inner.id(), g.inner.id()],
4583            shape,
4584        );
4585        // grad_x = s · (g − sum(g·s, last))
4586        let mut expected = vec![0.0f32; rows * cols];
4587        for r in 0..rows {
4588            let dot: f32 = (0..cols)
4589                .map(|c| g_data[r * cols + c] * s_data[r * cols + c])
4590                .sum();
4591            for c in 0..cols {
4592                expected[r * cols + c] = s_data[r * cols + c] * (g_data[r * cols + c] - dot);
4593            }
4594        }
4595        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4596            assert!(
4597                (gv - ev).abs() < 1e-5,
4598                "softmax_bwd at {i}: got {gv}, expected {ev}"
4599            );
4600        }
4601    }
4602
4603    #[test]
4604    fn rms_norm_last_dim_backward_decompose_matches_reference() {
4605        use fuel_graph::registry::{FusedOpParams, FusedOps};
4606        let dev = Device::cpu();
4607        let (rows, cols) = (2usize, 3usize);
4608        let eps = 1e-5f64;
4609        let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4610        let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4611        let shape = Shape::from_dims(&[rows, cols]);
4612        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4613        let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4614        let got = lower_realize_fused(
4615            &x,
4616            fuel_graph::Op::Fused(
4617                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
4618                FusedOpParams::RmsNormLastDimBackward { eps },
4619            ),
4620            vec![x.inner.id(), g.inner.id()],
4621            shape,
4622        );
4623        // grad_x = r_rms · (g − x·s / (n·(mean_sq + eps)))
4624        let n = cols as f32;
4625        let mut expected = vec![0.0f32; rows * cols];
4626        for r in 0..rows {
4627            let meansq: f32 = (0..cols).map(|c| x_data[r * cols + c].powi(2)).sum::<f32>() / n;
4628            let denom = meansq + eps as f32;
4629            let rrms = 1.0 / denom.sqrt();
4630            let s: f32 = (0..cols)
4631                .map(|c| g_data[r * cols + c] * x_data[r * cols + c])
4632                .sum();
4633            for c in 0..cols {
4634                let term = x_data[r * cols + c] * s / (n * denom);
4635                expected[r * cols + c] = rrms * (g_data[r * cols + c] - term);
4636            }
4637        }
4638        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4639            assert!(
4640                (gv - ev).abs() < 1e-4,
4641                "rms_norm_bwd at {i}: got {gv}, expected {ev}"
4642            );
4643        }
4644    }
4645
4646    #[test]
4647    fn layer_norm_last_dim_backward_decompose_matches_reference() {
4648        use fuel_graph::registry::{FusedOpParams, FusedOps};
4649        let dev = Device::cpu();
4650        let (rows, cols) = (2usize, 3usize);
4651        let eps = 1e-5f64;
4652        let x_data = vec![1.0f32, -2.0, 0.5, 3.0, 0.25, -1.5];
4653        let g_data = vec![0.5f32, 1.0, -0.3, 0.2, -1.0, 0.7];
4654        let shape = Shape::from_dims(&[rows, cols]);
4655        let x = Tensor::from_f32(x_data.clone(), shape.clone(), &dev).unwrap();
4656        let g = x.const_f32_like(g_data.clone(), shape.clone()).unwrap();
4657        let got = lower_realize_fused(
4658            &x,
4659            fuel_graph::Op::Fused(
4660                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
4661                FusedOpParams::LayerNormLastDimBackward { eps },
4662            ),
4663            vec![x.inner.id(), g.inner.id()],
4664            shape,
4665        );
4666        // grad_x = istd · (g − mean(g) − xhat·mean(g·xhat))
4667        let n = cols as f32;
4668        let mut expected = vec![0.0f32; rows * cols];
4669        for r in 0..rows {
4670            let mean_x: f32 = (0..cols).map(|c| x_data[r * cols + c]).sum::<f32>() / n;
4671            let var: f32 = (0..cols)
4672                .map(|c| (x_data[r * cols + c] - mean_x).powi(2))
4673                .sum::<f32>()
4674                / n;
4675            let istd = 1.0 / (var + eps as f32).sqrt();
4676            let xhat: Vec<f32> = (0..cols)
4677                .map(|c| (x_data[r * cols + c] - mean_x) * istd)
4678                .collect();
4679            let mean_g: f32 = (0..cols).map(|c| g_data[r * cols + c]).sum::<f32>() / n;
4680            let mean_gxh: f32 = (0..cols)
4681                .map(|c| g_data[r * cols + c] * xhat[c])
4682                .sum::<f32>()
4683                / n;
4684            for c in 0..cols {
4685                expected[r * cols + c] =
4686                    istd * (g_data[r * cols + c] - mean_g - xhat[c] * mean_gxh);
4687            }
4688        }
4689        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4690            assert!(
4691                (gv - ev).abs() < 1e-4,
4692                "layer_norm_bwd at {i}: got {gv}, expected {ev}"
4693            );
4694        }
4695    }
4696
4697    #[test]
4698    fn reduce_max_to_backward_decompose_matches_reference() {
4699        use fuel_graph::registry::{FusedOpParams, FusedOps};
4700        let dev = Device::cpu();
4701        // row0 has a tie at the max (two 3.0s → share 10/2); row1 unique max.
4702        let x_data = vec![1.0f32, 3.0, 3.0, 2.0, 0.0, 1.0]; // [2,3]
4703        let up_data = vec![10.0f32, 5.0]; // [2,1] — one per reduced row.
4704        let x_shape = Shape::from_dims(&[2, 3]);
4705        let up_shape = Shape::from_dims(&[2, 1]);
4706        let x = Tensor::from_f32(x_data.clone(), x_shape.clone(), &dev).unwrap();
4707        let up = x.const_f32_like(up_data.clone(), up_shape).unwrap();
4708        let got = lower_realize_fused(
4709            &x,
4710            fuel_graph::Op::Fused(
4711                FusedOps::REDUCE_MAX_TO_BACKWARD,
4712                FusedOpParams::ReduceMaxToBackward,
4713            ),
4714            vec![x.inner.id(), up.inner.id()],
4715            x_shape,
4716        );
4717        // row0: max 3.0 tied 2× → 10/2 each; row1: max 2.0 unique → full 5.0.
4718        let expected = vec![0.0f32, 5.0, 5.0, 5.0, 0.0, 0.0];
4719        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4720            assert!(
4721                (gv - ev).abs() < 1e-5,
4722                "reduce_max_bwd at {i}: got {gv}, expected {ev}"
4723            );
4724        }
4725    }
4726
4727    fn causal_conv1d_check(use_silu: bool) {
4728        use fuel_graph::registry::{FusedOpParams, FusedOps};
4729        let dev = Device::cpu();
4730        let (b, c, k, seq) = (1usize, 2usize, 3usize, 2usize);
4731        let x_seq = seq + (k - 1); // caller pre-pads by K-1.
4732        // x [B,C,x_seq], weight [C,1,K], bias [C] — all row-major.
4733        let x_data = vec![0.0f32, 1.0, 2.0, 3.0, 1.0, 0.0, -1.0, -2.0];
4734        let w_data = vec![0.5f32, 1.0, -0.5, 1.0, 0.0, 2.0];
4735        let bias_data = vec![0.1f32, -0.2];
4736        let x = Tensor::from_f32(x_data.clone(), Shape::from_dims(&[b, c, x_seq]), &dev).unwrap();
4737        let w = x
4738            .const_f32_like(w_data.clone(), Shape::from_dims(&[c, 1, k]))
4739            .unwrap();
4740        let bias = x
4741            .const_f32_like(bias_data.clone(), Shape::from_dims(&[c]))
4742            .unwrap();
4743        let got = lower_realize_fused(
4744            &x,
4745            fuel_graph::Op::Fused(
4746                FusedOps::CAUSAL_CONV1D,
4747                FusedOpParams::CausalConv1d { use_silu },
4748            ),
4749            vec![x.inner.id(), w.inner.id(), bias.inner.id()],
4750            Shape::from_dims(&[b, c, seq]),
4751        );
4752        // out[c,t] = Σ_k w[c,k]·x[c,t+k] + bias[c], optional SiLU.
4753        let mut expected = vec![0.0f32; b * c * seq];
4754        for ch in 0..c {
4755            for t in 0..seq {
4756                let mut acc = 0.0f32;
4757                for kk in 0..k {
4758                    acc += w_data[ch * k + kk] * x_data[ch * x_seq + t + kk];
4759                }
4760                acc += bias_data[ch];
4761                if use_silu {
4762                    acc *= 1.0 / (1.0 + (-acc).exp());
4763                }
4764                expected[ch * seq + t] = acc;
4765            }
4766        }
4767        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4768            assert!(
4769                (gv - ev).abs() < 1e-4,
4770                "causal_conv1d (silu={use_silu}) at {i}: got {gv}, expected {ev}",
4771            );
4772        }
4773    }
4774
4775    #[test]
4776    fn causal_conv1d_decompose_matches_reference() {
4777        causal_conv1d_check(false);
4778        causal_conv1d_check(true);
4779    }
4780
4781    #[test]
4782    fn flash_attn_backward_decompose_matches_reference() {
4783        use fuel_graph::registry::{FusedOpParams, FusedOps};
4784        let dev = Device::cpu();
4785        let (sq, sk, d) = (2usize, 2usize, 2usize);
4786        // 4-digit test scale (~1/sqrt(2)), deliberately NOT FRAC_1_SQRT_2 (0.70710678);
4787        // swapping the exact constant would perturb these attention-scale parity tests.
4788        #[allow(clippy::approx_constant)]
4789        let scale = 0.7071f32;
4790        let q_data = vec![0.1f32, -0.2, 0.3, 0.5]; // [Sq,D]
4791        let k_data = vec![0.4f32, 0.1, -0.3, 0.2]; // [Sk,D]
4792        let v_data = vec![1.0f32, 2.0, -1.0, 0.5]; // [Sk,D]
4793        let do_data = vec![0.5f32, -1.0, 0.2, 0.3]; // [Sq,D]
4794        let qshape = Shape::from_dims(&[1, 1, sq, d]);
4795        let kshape = Shape::from_dims(&[1, 1, sk, d]);
4796        let q = Tensor::from_f32(q_data.clone(), qshape.clone(), &dev).unwrap();
4797        let k = q.const_f32_like(k_data.clone(), kshape.clone()).unwrap();
4798        let v = q.const_f32_like(v_data.clone(), kshape.clone()).unwrap();
4799        let dout = q.const_f32_like(do_data.clone(), qshape.clone()).unwrap();
4800        let params = FusedOpParams::FlashAttnBackward {
4801            softmax_scale: scale,
4802            causal: false,
4803            window_size_left: None,
4804            window_size_right: None,
4805            softcap: None,
4806        };
4807        let inputs = vec![q.inner.id(), k.inner.id(), v.inner.id(), dout.inner.id()];
4808        let dq = lower_realize_fused(
4809            &q,
4810            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_Q, params.clone()),
4811            inputs.clone(),
4812            qshape.clone(),
4813        );
4814        let dk = lower_realize_fused(
4815            &q,
4816            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_K, params.clone()),
4817            inputs.clone(),
4818            kshape.clone(),
4819        );
4820        let dv = lower_realize_fused(
4821            &q,
4822            fuel_graph::Op::Fused(FusedOps::FLASH_ATTN_BACKWARD_V, params),
4823            inputs,
4824            kshape,
4825        );
4826
4827        // --- reference SDPA backward (B=1, H=1) ---
4828        let mut p = vec![0.0f32; sq * sk];
4829        for i in 0..sq {
4830            let mut scores = vec![0.0f32; sk];
4831            for j in 0..sk {
4832                let mut s = 0.0f32;
4833                for l in 0..d {
4834                    s += q_data[i * d + l] * k_data[j * d + l];
4835                }
4836                scores[j] = scale * s;
4837            }
4838            let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4839            let mut sum = 0.0f32;
4840            let e: Vec<f32> = scores
4841                .iter()
4842                .map(|&s| {
4843                    let x = (s - m).exp();
4844                    sum += x;
4845                    x
4846                })
4847                .collect();
4848            for j in 0..sk {
4849                p[i * sk + j] = e[j] / sum;
4850            }
4851        }
4852        // dV[j,l] = Σ_i P[i,j]·dO[i,l]
4853        let mut ref_dv = vec![0.0f32; sk * d];
4854        for j in 0..sk {
4855            for l in 0..d {
4856                ref_dv[j * d + l] = (0..sq).map(|i| p[i * sk + j] * do_data[i * d + l]).sum();
4857            }
4858        }
4859        // dP[i,j] = Σ_l dO[i,l]·v[j,l]
4860        let mut dp = vec![0.0f32; sq * sk];
4861        for i in 0..sq {
4862            for j in 0..sk {
4863                dp[i * sk + j] = (0..d).map(|l| do_data[i * d + l] * v_data[j * d + l]).sum();
4864            }
4865        }
4866        // dScores_raw[i,j] = scale · P[i,j]·(dP[i,j] − Σ_j' dP·P)
4867        let mut dsr = vec![0.0f32; sq * sk];
4868        for i in 0..sq {
4869            let rowdot: f32 = (0..sk).map(|j| dp[i * sk + j] * p[i * sk + j]).sum();
4870            for j in 0..sk {
4871                dsr[i * sk + j] = scale * p[i * sk + j] * (dp[i * sk + j] - rowdot);
4872            }
4873        }
4874        // dQ[i,l] = Σ_j dsr[i,j]·k[j,l] ; dK[j,l] = Σ_i dsr[i,j]·q[i,l]
4875        let mut ref_dq = vec![0.0f32; sq * d];
4876        for i in 0..sq {
4877            for l in 0..d {
4878                ref_dq[i * d + l] = (0..sk).map(|j| dsr[i * sk + j] * k_data[j * d + l]).sum();
4879            }
4880        }
4881        let mut ref_dk = vec![0.0f32; sk * d];
4882        for j in 0..sk {
4883            for l in 0..d {
4884                ref_dk[j * d + l] = (0..sq).map(|i| dsr[i * sk + j] * q_data[i * d + l]).sum();
4885            }
4886        }
4887        let check = |name: &str, got: &[f32], exp: &[f32]| {
4888            assert_eq!(got.len(), exp.len(), "{name} length");
4889            for (i, (&gv, &ev)) in got.iter().zip(exp).enumerate() {
4890                assert!(
4891                    (gv - ev).abs() < 1e-4,
4892                    "{name} at {i}: got {gv}, expected {ev}"
4893                );
4894            }
4895        };
4896        check("dQ", &dq, &ref_dq);
4897        check("dK", &dk, &ref_dk);
4898        check("dV", &dv, &ref_dv);
4899    }
4900
4901    #[test]
4902    fn paged_attn_decompose_matches_reference() {
4903        use fuel_graph::registry::{FusedOpParams, FusedOps};
4904        let dev = Device::cpu();
4905        // B=1, Hq=Hkv=1, Sq=1 (decode), D=2; block_size=2, max_blk=2 → kv_len=4.
4906        let block_size = 2usize;
4907        let scale = 1.0f32;
4908        // k_cache / v_cache: [num_blocks=3, block_size=2, Hkv=1, D=2]. Block 1
4909        // is unused (not in the block table) and holds sentinel 9s.
4910        let kc = vec![
4911            1.0f32, 0.0, 0.0, 1.0, 9.0, 9.0, 9.0, 9.0, 1.0, 1.0, 2.0, 0.0,
4912        ];
4913        let vc = vec![
4914            1.0f32, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0, 6.0, 7.0, 8.0,
4915        ];
4916        let q_data = vec![0.5f32, 0.5]; // [1,1,1,2]
4917        let bt = vec![0u32, 2u32]; // block_table [1,2]: sequence uses blocks 0 and 2
4918        let cl = vec![3u32]; // context_lens [1]: only the first 3 keys are valid
4919
4920        let q = Tensor::from_f32(q_data.clone(), Shape::from_dims(&[1, 1, 1, 2]), &dev).unwrap();
4921        let kcache = q
4922            .const_f32_like(kc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4923            .unwrap();
4924        let vcache = q
4925            .const_f32_like(vc.clone(), Shape::from_dims(&[3, 2, 1, 2]))
4926            .unwrap();
4927        let block_table = q.const_u32_like(bt, Shape::from_dims(&[1, 2])).unwrap();
4928        let context_lens = q.const_u32_like(cl, Shape::from_dims(&[1])).unwrap();
4929        let params = FusedOpParams::PagedAttn {
4930            softmax_scale: scale,
4931            block_size,
4932            softcap: None,
4933        };
4934        let inputs = vec![
4935            q.inner.id(),
4936            kcache.inner.id(),
4937            vcache.inner.id(),
4938            block_table.inner.id(),
4939            context_lens.inner.id(),
4940        ];
4941        let got = lower_realize_fused(
4942            &q,
4943            fuel_graph::Op::Fused(FusedOps::PAGED_ATTN, params),
4944            inputs,
4945            Shape::from_dims(&[1, 1, 1, 2]),
4946        );
4947
4948        // reference: gather blocks [0, 2] → k_seq/v_seq[4][2]; mask j ≥ 3;
4949        // softmax; weighted sum of v.
4950        let (kv_len, ctx) = (4usize, 3usize);
4951        let mut k_seq = vec![];
4952        let mut v_seq = vec![];
4953        for &blk in &[0usize, 2usize] {
4954            for p in 0..block_size {
4955                let base = (blk * block_size + p) * 2; // Hkv=1, D=2
4956                k_seq.push([kc[base], kc[base + 1]]);
4957                v_seq.push([vc[base], vc[base + 1]]);
4958            }
4959        }
4960        let mut scores = vec![0.0f32; kv_len];
4961        for j in 0..kv_len {
4962            let s = q_data[0] * k_seq[j][0] + q_data[1] * k_seq[j][1];
4963            scores[j] = if j >= ctx {
4964                f32::NEG_INFINITY
4965            } else {
4966                scale * s
4967            };
4968        }
4969        let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4970        let mut sum = 0.0f32;
4971        let e: Vec<f32> = scores
4972            .iter()
4973            .map(|&s| {
4974                let x = (s - m).exp();
4975                sum += x;
4976                x
4977            })
4978            .collect();
4979        let mut expected = vec![0.0f32; 2];
4980        for j in 0..kv_len {
4981            for l in 0..2 {
4982                expected[l] += (e[j] / sum) * v_seq[j][l];
4983            }
4984        }
4985        for (i, (&gv, &ev)) in got.iter().zip(&expected).enumerate() {
4986            assert!(
4987                (gv - ev).abs() < 1e-4,
4988                "paged_attn at {i}: got {gv}, expected {ev}"
4989            );
4990        }
4991    }
4992
4993    #[test]
4994    #[cfg(feature = "cuda")]
4995    fn cuda_executor_matches_cpu_on_add_mul() {
4996        let a =
4997            Tensor::from_f32(vec![1.0, 2.0, 3.0], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
4998        let b = a
4999            .const_f32_like(vec![4.0, 5.0, 6.0], Shape::from_dims(&[3]))
5000            .unwrap();
5001        let c = a.add(&b).unwrap().mul(&a).unwrap();
5002        let cpu_result = c.realize_f32();
5003        let executor = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5004        let cuda_result = c.realize_f32_cuda(&executor);
5005        assert_eq!(cpu_result, cuda_result);
5006    }
5007
5008    /// END-TO-END SMOKE ONLY — NOT a CUDA-kernel pin. Verifies the lazy
5009    /// realize path produces the NaN-propagating `maximum`/`minimum`
5010    /// convention (pinned 2026-07-08,
5011    /// `docs/architecture/10-decisions-log.md`) and that a CPU realize and
5012    /// a CUDA-device realize of the same graph agree on NaN-ness.
5013    ///
5014    /// CAVEAT (orchestrator sabotage finding, 2026-07-08): cost-based
5015    /// placement may route a tiny elementwise op to CPU on BOTH legs even
5016    /// under `realize_f32_cuda`, so this test does NOT guarantee the CUDA
5017    /// kernel executed — a wrong CUDA binding can pass it. The real
5018    /// CUDA-kernel pin is the direct binding-table invocation test
5019    /// `fuel-dispatch/tests/cuda_dispatch_live.rs::cuda_maximum_minimum_propagate_nan_f32`.
5020    ///
5021    /// Gated `#[cfg(feature = "cuda")]` + `#[ignore]`; skips cleanly if no
5022    /// CUDA device is present. Run:
5023    ///   `cargo test -p fuel-core --features cuda --lib \
5024    ///    maximum_minimum_nan_convention_lazy_realize_smoke -- --ignored --nocapture`
5025    #[test]
5026    #[cfg(feature = "cuda")]
5027    #[ignore = "requires a live CUDA device"]
5028    fn maximum_minimum_nan_convention_lazy_realize_smoke() {
5029        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5030            Ok(d) => d,
5031            Err(e) => {
5032                return fuel_test_support::hardware::skip(
5033                    fuel_test_support::hardware::Hardware::Cuda,
5034                    fuel_test_support::hardware::Missing::device(format!(
5035                        "CudaDevice::new(0): {e:?}"
5036                    )),
5037                );
5038            }
5039        };
5040        let a = Tensor::from_f32(
5041            vec![f32::NAN, -2.0, 3.0, f32::NAN],
5042            Shape::from_dims(&[4]),
5043            &Device::cpu(),
5044        )
5045        .unwrap();
5046        let b = a
5047            .const_f32_like(vec![1.0, f32::NAN, 2.0, f32::NAN], Shape::from_dims(&[4]))
5048            .unwrap();
5049
5050        let max_lazy = a.maximum(&b).unwrap();
5051        let cpu_max = max_lazy.realize_f32();
5052        let cuda_max = max_lazy.realize_f32_cuda(&cuda);
5053        for i in 0..4 {
5054            assert_eq!(
5055                cpu_max[i].is_nan(),
5056                cuda_max[i].is_nan(),
5057                "maximum[{i}] NaN-ness must match: cpu={}, cuda={}",
5058                cpu_max[i],
5059                cuda_max[i],
5060            );
5061            if !cpu_max[i].is_nan() {
5062                assert_eq!(cpu_max[i], cuda_max[i], "maximum[{i}]");
5063            }
5064        }
5065
5066        let min_lazy = a.minimum(&b).unwrap();
5067        let cpu_min = min_lazy.realize_f32();
5068        let cuda_min = min_lazy.realize_f32_cuda(&cuda);
5069        for i in 0..4 {
5070            assert_eq!(
5071                cpu_min[i].is_nan(),
5072                cuda_min[i].is_nan(),
5073                "minimum[{i}] NaN-ness must match: cpu={}, cuda={}",
5074                cpu_min[i],
5075                cuda_min[i],
5076            );
5077            if !cpu_min[i].is_nan() {
5078                assert_eq!(cpu_min[i], cuda_min[i], "minimum[{i}]");
5079            }
5080        }
5081    }
5082
5083    /// END-TO-END SMOKE ONLY — NOT a CUDA-kernel pin. Verifies the lazy
5084    /// realize path produces the NaN-propagating `relu` convention (torch
5085    /// parity, pinned 2026-07-08, `docs/architecture/10-decisions-log.md`)
5086    /// and that a CPU realize and a CUDA-device realize of the same graph
5087    /// agree on NaN-ness. Successor of the transitional-divergence pin
5088    /// `relu_cuda_still_scrubs_nan_pending_alpha76_rebind`, flipped at the
5089    /// alpha.76 `unary_relu_propagating_*` rebind.
5090    ///
5091    /// CAVEAT (orchestrator sabotage finding, 2026-07-08): cost-based
5092    /// placement may route a tiny elementwise op to CPU on BOTH legs even
5093    /// under `realize_f32_cuda`, so this test does NOT guarantee the CUDA
5094    /// kernel executed — it stayed green with the CUDA binding deliberately
5095    /// reverted to the scrubbing stem. The real CUDA-kernel pin (verified
5096    /// born-red against that sabotage) is the direct binding-table
5097    /// invocation test
5098    /// `fuel-dispatch/tests/cuda_dispatch_live.rs::cuda_relu_propagates_nan_f32`
5099    /// (+ its bf16 sibling).
5100    ///
5101    /// Gated `#[cfg(feature = "cuda")]` + `#[ignore]`; skips cleanly if no
5102    /// CUDA device is present. Run:
5103    ///   `cargo test -p fuel-core --features cuda --lib \
5104    ///    relu_nan_convention_lazy_realize_smoke -- --ignored --nocapture`
5105    #[test]
5106    #[cfg(feature = "cuda")]
5107    #[ignore = "requires a live CUDA device"]
5108    fn relu_nan_convention_lazy_realize_smoke() {
5109        let cuda = match fuel_cuda_backend::CudaDevice::new(0) {
5110            Ok(d) => d,
5111            Err(e) => {
5112                return fuel_test_support::hardware::skip(
5113                    fuel_test_support::hardware::Hardware::Cuda,
5114                    fuel_test_support::hardware::Missing::device(format!(
5115                        "CudaDevice::new(0): {e:?}"
5116                    )),
5117                );
5118            }
5119        };
5120        let a = Tensor::from_f32(
5121            vec![f32::NAN, -2.0, 3.0],
5122            Shape::from_dims(&[3]),
5123            &Device::cpu(),
5124        )
5125        .unwrap();
5126        let relu_lazy = a.relu();
5127        let cpu_result = relu_lazy.realize_f32();
5128        let cuda_result = relu_lazy.realize_f32_cuda(&cuda);
5129
5130        for i in 0..3 {
5131            assert_eq!(
5132                cpu_result[i].is_nan(),
5133                cuda_result[i].is_nan(),
5134                "relu[{i}] NaN-ness must match: cpu={}, cuda={}",
5135                cpu_result[i],
5136                cuda_result[i],
5137            );
5138            if !cpu_result[i].is_nan() {
5139                assert_eq!(cpu_result[i], cuda_result[i], "relu[{i}]");
5140            }
5141        }
5142    }
5143
5144    #[test]
5145    #[cfg(feature = "cuda")]
5146    fn cuda_executor_matches_cpu_on_matmul() {
5147        let a = Tensor::from_f32(
5148            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5149            Shape::from_dims(&[2, 3]),
5150            &Device::cpu(),
5151        )
5152        .unwrap();
5153        let b = a
5154            .const_f32_like(
5155                vec![7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
5156                Shape::from_dims(&[3, 2]),
5157            )
5158            .unwrap();
5159        let c = a.matmul(&b).unwrap();
5160        let cpu = c.realize_f32();
5161        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5162        let cuda = c.realize_f32_cuda(&exe);
5163        assert_eq!(cpu.len(), cuda.len());
5164        for (i, (a, b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5165            assert!((a - b).abs() < 1e-3, "matmul[{i}]: cpu={a}, cuda={b}",);
5166        }
5167    }
5168
5169    #[test]
5170    #[cfg(feature = "cuda")]
5171    fn cuda_executor_matches_cpu_on_broadcast_matmul() {
5172        // Rank-3 × rank-2 matmul (what the transformer forward does).
5173        // The graph auto-broadcasts the rank-2 to rank-3.
5174        let x = Tensor::from_f32(
5175            (0..12).map(|i| i as f32 * 0.1).collect::<Vec<_>>(),
5176            Shape::from_dims(&[1, 3, 4]),
5177            &Device::cpu(),
5178        )
5179        .unwrap();
5180        let w = x
5181            .const_f32_like(
5182                (0..8).map(|i| i as f32 * 0.2).collect::<Vec<_>>(),
5183                Shape::from_dims(&[4, 2]),
5184            )
5185            .unwrap();
5186        let y = x.matmul(&w).unwrap();
5187        let cpu = y.realize_f32();
5188        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5189        let cuda = y.realize_f32_cuda(&exe);
5190        assert_eq!(cpu.len(), cuda.len());
5191        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5192            assert!((a - b).abs() < 1e-3, "bcast_mm[{i}]: cpu={a}, cuda={b}");
5193        }
5194    }
5195
5196    #[test]
5197    #[cfg(feature = "cuda")]
5198    fn cuda_executor_matches_cpu_on_permute() {
5199        let x = Tensor::from_f32(
5200            (0..24).map(|i| i as f32).collect::<Vec<_>>(),
5201            Shape::from_dims(&[1, 2, 3, 4]),
5202            &Device::cpu(),
5203        )
5204        .unwrap();
5205        let y = x.permute([0, 2, 1, 3_usize]).unwrap();
5206        let cpu = y.realize_f32();
5207        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5208        let cuda = y.realize_f32_cuda(&exe);
5209        assert_eq!(cpu, cuda, "permute mismatch");
5210    }
5211
5212    #[test]
5213    #[cfg(feature = "cuda")]
5214    fn cuda_executor_matches_cpu_on_softmax() {
5215        let x = Tensor::from_f32(
5216            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
5217            Shape::from_dims(&[2, 3]),
5218            &Device::cpu(),
5219        )
5220        .unwrap();
5221        let y = x.softmax_last_dim().unwrap();
5222        let cpu = y.realize_f32();
5223        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5224        let cuda = y.realize_f32_cuda(&exe);
5225        assert_eq!(cpu.len(), cuda.len());
5226        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5227            assert!((a - b).abs() < 1e-4, "softmax[{i}]: cpu={a}, cuda={b}");
5228        }
5229    }
5230
5231    /// Phase 7.5 PR 3 / 3.5 live CUDA equivalence: realize a graph with
5232    /// `Op::SoftmaxLastDim` through the rule-registry pipeline using
5233    /// `RuleRegistry::lowering_only()` so the executor sees the
5234    /// 7-node lowered subgraph instead of the fused op. The composed
5235    /// CUDA execution path (ReduceMaxTo + BroadcastTo + Sub + Exp +
5236    /// ReduceSumTo + BroadcastTo + Div) must match the fused CPU
5237    /// baseline within tight epsilon.
5238    ///
5239    /// Post PR-3.5 follow-up: ReduceMaxTo / ReduceSumTo run natively
5240    /// on CUDA via the legacy executor's `Op::ReduceXxxTo` arm (which
5241    /// delegates to `backend.reduce` and relabels the result to the
5242    /// keepdim shape), so the lowered subgraph stays GPU-resident
5243    /// end-to-end. Two D2H/H2D round-trips per softmax used to be
5244    /// the cost on the prior commit — both gone now.
5245    #[test]
5246    #[cfg(feature = "cuda")]
5247    fn cuda_executor_matches_cpu_on_softmax_via_lowering() {
5248        // Use a non-trivial input shape so the broadcast paths and
5249        // the ReduceSumTo step both have actual work to do.
5250        let n = 24;
5251        let last = 5;
5252        let data: Vec<f32> = (0..n * last)
5253            .map(|i| ((i as f32) * 0.13).sin() * 2.0 - 0.7)
5254            .collect();
5255        let x = Tensor::from_f32(data, Shape::from_dims(&[n, last]), &Device::cpu()).unwrap();
5256        let y = x.softmax_last_dim().unwrap();
5257
5258        // CPU baseline: fused SoftmaxLastDim through the standard
5259        // realize_f32 path (no rule-registry pipeline involved).
5260        let cpu = y.realize_f32();
5261
5262        // CUDA via the lowered subgraph: run the lowering-only
5263        // rule registry to fixpoint first so fusion can't re-collapse
5264        // the lowered pattern back to Op::SoftmaxLastDim. Then
5265        // realize the remapped target via PipelinedExecutor.
5266        // (Phase 7.6 step 9c E.2: optimizer is caller-composed.)
5267        let graph = y.inner.graph().clone();
5268        let registry = fuel_graph::opt::RuleRegistry::lowering_only();
5269        let remapped = registry.optimize_to_fixpoint(&graph, &[y.inner.id()]);
5270        let dev = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5271        let fc_device: crate::Device = dev.clone().into();
5272        let cuda = crate::pipelined_bridge::realize_one_as::<f32>(&graph, remapped[0], &fc_device)
5273            .expect("realize lowered softmax on CUDA");
5274
5275        assert_eq!(cpu.len(), cuda.len());
5276        let mut max_abs_err = 0.0_f32;
5277        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5278            let err = (a - b).abs();
5279            if err > max_abs_err {
5280                max_abs_err = err;
5281            }
5282            assert!(
5283                err < 1e-5,
5284                "lowered softmax[{i}]: cpu={a} (fused), cuda={b} (composed), err={err}",
5285            );
5286        }
5287        eprintln!("max_abs_err over lowered-vs-fused softmax: {max_abs_err:.3e}");
5288    }
5289
5290    #[test]
5291    #[cfg(feature = "cuda")]
5292    fn cuda_executor_matches_cpu_on_concat_slice() {
5293        let a = Tensor::from_f32(
5294            vec![1.0, 2.0, 3.0, 4.0],
5295            Shape::from_dims(&[2, 2]),
5296            &Device::cpu(),
5297        )
5298        .unwrap();
5299        let b = a
5300            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], Shape::from_dims(&[2, 2]))
5301            .unwrap();
5302        let cat = a.concat(&b, 1).unwrap(); // [2, 4]
5303        let sliced = cat.slice(1, 1, 2).unwrap(); // [2, 2]
5304        let cpu = sliced.realize_f32();
5305        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5306        let cuda = sliced.realize_f32_cuda(&exe);
5307        assert_eq!(cpu, cuda, "concat+slice mismatch");
5308    }
5309
5310    #[test]
5311    #[cfg(feature = "cuda")]
5312    fn cuda_executor_matches_cpu_on_rms_norm() {
5313        let x = Tensor::from_f32(
5314            (0..8).map(|i| i as f32 * 0.5 - 1.5).collect::<Vec<_>>(),
5315            Shape::from_dims(&[2, 4]),
5316            &Device::cpu(),
5317        )
5318        .unwrap();
5319        let y = x.rms_norm_last_dim(1e-5).unwrap();
5320        let cpu = y.realize_f32();
5321        let exe = fuel_cuda_backend::CudaDevice::new(0).unwrap();
5322        let cuda = y.realize_f32_cuda(&exe);
5323        assert_eq!(cpu.len(), cuda.len());
5324        for (i, (&a, &b)) in cpu.iter().zip(cuda.iter()).enumerate() {
5325            assert!((a - b).abs() < 1e-3, "rms_norm[{i}]: cpu={a}, cuda={b}");
5326        }
5327    }
5328
5329    #[test]
5330    fn realize_f64_through_bridge() {
5331        let a =
5332            Tensor::from_f64(vec![1.5, 2.5, 3.5], Shape::from_dims(&[3]), &Device::cpu()).unwrap();
5333        let b = a.mul(&a).unwrap();
5334        assert_eq!(b.realize_f64(), vec![2.25, 6.25, 12.25]);
5335    }
5336
5337    /// GAP-327 regression test (was the born-red probe; now LIVE — the guard has landed).
5338    ///
5339    /// The realize funnel `pipelined_bridge::extract_cpu_bytes_typed` guards the byte
5340    /// reinterpretation on the root's dtype: `realize_one_as::<T>` returns
5341    /// `Error::UnexpectedDType` on a mismatch, and the typed `realize_fNN` accessors (which
5342    /// `.expect` that result) panic. The BYTE VIEW `realize_one_bytes` is the deliberate
5343    /// UNGUARDED escape hatch and still returns raw bytes for any dtype. Measured by probe
5344    /// (GAP-327) before the fix: realize_f32()/realize_one_as::<f32> on an F64 [1.0, 2.0]
5345    /// root returned Ok([0.0, 1.875, 0.0, 2.0]) — silent reinterpretation; this asserts that
5346    /// is now rejected while the byte view is not. See docs/gaps.md GAP-327.
5347    #[test]
5348    fn gap327_realize_f32_on_f64_root_must_reject_not_reinterpret() {
5349        let t =
5350            Tensor::from_f64(vec![1.0_f64, 2.0], Shape::from_dims(&[2]), &Device::cpu()).unwrap();
5351        let graph = t.inner.graph().clone();
5352        let target = t.inner.id();
5353        let device = Device::cpu();
5354
5355        // Silence the panic hook only around the catch_unwind measurements; restore it
5356        // before the assertions so a real failure still prints.
5357        let prev_hook = std::panic::take_hook();
5358        std::panic::set_hook(Box::new(|_| {}));
5359        // Control 1 (RIGHT dtype): realize_f64 on the F64 root succeeds.
5360        let ctl_f64 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f64()));
5361        // Control 2 (guard FIRES): a MISMATCHED guarded accessor panics — proves the harness
5362        // observes guards, so the subject rejection below is real and not a swallowed nothing.
5363        let ctl_f16 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f16()));
5364        // SUBJECT A: realize_f32 on the F64 root must now panic (guard -> Err -> .expect).
5365        let subj_method =
5366            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| t.realize_f32()));
5367        std::panic::set_hook(prev_hook);
5368
5369        // SUBJECT B: realize_one_as::<f32> must return Err(UnexpectedDType) (matched by variant).
5370        let subj_raw = crate::pipelined_bridge::realize_one_as::<f32>(&graph, target, &device);
5371        // BYTE VIEW: the unguarded escape hatch must still return the root's RAW bytes
5372        // (2 x f64 = 16 bytes) — a dtype mismatch is NOT an error for the byte view.
5373        let bytes_view = crate::pipelined_bridge::realize_one_bytes(&graph, target, &device);
5374
5375        assert!(
5376            ctl_f64.is_ok(),
5377            "control: realize_f64 on an F64 root must succeed; got {ctl_f64:?}"
5378        );
5379        assert!(
5380            ctl_f16.is_err(),
5381            "positive control: realize_f16() on an F64 root must panic (guard fires); if it \
5382             does not, the harness is not observing panics and the subject asserts are vacuous"
5383        );
5384        assert!(
5385            subj_method.is_err(),
5386            "realize_f32() on an F64 root must REJECT (panic), not silently reinterpret bytes"
5387        );
5388        assert!(
5389            matches!(subj_raw, Err(fuel_ir::Error::UnexpectedDType { .. })),
5390            "realize_one_as::<f32> on an F64 root must return Err(UnexpectedDType), not \
5391             Ok(reinterpreted bytes); got {subj_raw:?}"
5392        );
5393        assert!(
5394            matches!(&bytes_view, Ok(b) if b.len() == 16),
5395            "byte view realize_one_bytes on an F64 [1.0, 2.0] root must return 16 raw bytes \
5396             (unguarded), not an error; got {bytes_view:?}"
5397        );
5398    }
5399
5400    #[test]
5401    fn lazy_tensor_mini_llama_block_forward() {
5402        // A minimal LLaMA-style attention-only "block" built entirely
5403        // through Tensor. No training, just the forward pass:
5404        //
5405        //   h = x + (RmsNorm(x) @ W_qkv → split Q/K/V → RoPE → attention → out proj)
5406        //
5407        // This is the sanity check that every LLaMA primitive is
5408        // reachable through the bridge's API, and that the bridge's
5409        // realize_f32 call actually runs the whole thing.
5410        let seq = 3;
5411        let d_head = 4; // must be even for RoPE
5412        let num_heads = 2;
5413        let d_model = num_heads * d_head; // 8
5414
5415        // Fake input: [1, seq, d_model]
5416        let x_data: Vec<f32> = (0..seq * d_model).map(|i| i as f32 * 0.01).collect();
5417        let x =
5418            Tensor::from_f32(x_data, Shape::from_dims(&[1, seq, d_model]), &Device::cpu()).unwrap();
5419
5420        // Fake weights (just identities for simplicity — makes the
5421        // test easy to verify output finiteness without needing to
5422        // hand-compute).
5423        let w_q = x
5424            .const_f32_like(
5425                identity_matrix(d_model),
5426                Shape::from_dims(&[d_model, d_model]),
5427            )
5428            .unwrap();
5429        let w_k = x
5430            .const_f32_like(
5431                identity_matrix(d_model),
5432                Shape::from_dims(&[d_model, d_model]),
5433            )
5434            .unwrap();
5435        let w_v = x
5436            .const_f32_like(
5437                identity_matrix(d_model),
5438                Shape::from_dims(&[d_model, d_model]),
5439            )
5440            .unwrap();
5441        let w_o = x
5442            .const_f32_like(
5443                identity_matrix(d_model),
5444                Shape::from_dims(&[d_model, d_model]),
5445            )
5446            .unwrap();
5447
5448        // RmsNorm → Q/K/V projection (auto-broadcasting matmul).
5449        let x_norm = x.rms_norm_last_dim(1e-6).unwrap();
5450        let q = x_norm.matmul(&w_q).unwrap();
5451        let k = x_norm.matmul(&w_k).unwrap();
5452        let v = x_norm.matmul(&w_v).unwrap();
5453
5454        // Split heads: [1, seq, 8] → [1, seq, 2, 4] → [1, 2, seq, 4]
5455        let q_h = q
5456            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5457            .unwrap()
5458            .permute([0, 2, 1, 3_usize])
5459            .unwrap();
5460        let k_h = k
5461            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5462            .unwrap()
5463            .permute([0, 2, 1, 3_usize])
5464            .unwrap();
5465        let v_h = v
5466            .reshape(Shape::from_dims(&[1, seq, num_heads, d_head]))
5467            .unwrap()
5468            .permute([0, 2, 1, 3_usize])
5469            .unwrap();
5470
5471        // RoPE on Q and K.
5472        let q_r = q_h.rope(10000.0, 0).unwrap();
5473        let k_r = k_h.rope(10000.0, 0).unwrap();
5474
5475        // Scaled dot-product attention.
5476        let k_t = k_r.transpose().unwrap();
5477        let scores = q_r.matmul(&k_t).unwrap();
5478        let attn = scores.softmax_last_dim().unwrap();
5479        let attn_v = attn.matmul(&v_h).unwrap();
5480
5481        // Merge heads + output projection.
5482        let merged = attn_v
5483            .permute([0, 2, 1, 3_usize])
5484            .unwrap()
5485            .reshape(Shape::from_dims(&[1, seq, d_model]))
5486            .unwrap();
5487        let attn_out = merged.matmul(&w_o).unwrap();
5488        let h = x.add(&attn_out).unwrap();
5489
5490        // Realize end-to-end through the bridge.
5491        let result = h.realize_f32();
5492        assert_eq!(result.len(), seq * d_model);
5493        for &v in &result {
5494            assert!(
5495                v.is_finite(),
5496                "bridge-based LLaMA block output non-finite: {v}"
5497            );
5498        }
5499    }
5500
5501    /// Build an identity matrix of size `n × n` in row-major layout.
5502    fn identity_matrix(n: usize) -> Vec<f32> {
5503        let mut out = vec![0.0_f32; n * n];
5504        for i in 0..n {
5505            out[i * n + i] = 1.0;
5506        }
5507        out
5508    }
5509}
5510
5511// Helper method on the wrapper that we didn't include above because the
5512// main struct's `impl` block was getting long. Kept in its own small
5513// `impl` for readability.
5514impl Tensor {
5515    /// Build a second const U32 (index) tensor on the same graph.
5516    pub fn const_u32_like(
5517        &self,
5518        data: impl Into<Arc<[u32]>>,
5519        shape: impl Into<Shape>,
5520    ) -> std::result::Result<Self, fuel_ir::Error> {
5521        Ok(Self {
5522            inner: self.inner.const_u32_like(data, shape)?,
5523        })
5524    }
5525
5526    /// Push a [`fuel_graph::Op::Const`] node on the same graph as
5527    /// `self` **without** populating the graph's storage_map. The
5528    /// caller binds the storage Arc into the realize call via
5529    /// [`InferenceContext::insert`](crate::inference_context::InferenceContext::insert).
5530    ///
5531    /// Used by the Phase E.3.3 forward path to bind pre-allocated
5532    /// KV-cache storage Arcs (`Arc<RwLock<fuel_memory::Storage>>`)
5533    /// into a per-step graph — the graph's legacy storage_map only
5534    /// holds `fuel_backend_contract::Storage`, so direct binding isn't
5535    /// possible without a type conversion.
5536    pub fn const_placeholder_like(&self, shape: impl Into<Shape>, dtype: fuel_ir::DType) -> Self {
5537        Self {
5538            inner: self.inner.const_placeholder_like(shape, dtype),
5539        }
5540    }
5541
5542    /// Append an [`fuel_graph::Op::WriteSlice`] node. Copies `source`'s
5543    /// bytes into `self` at the rectangular slab defined by `ranges`
5544    /// and returns a tensor whose Storage Arc is `self`'s — i.e. the
5545    /// post-write reference to the same underlying buffer.
5546    ///
5547    /// Destructive on `self`: after the write, downstream consumers
5548    /// must read the bytes through the returned tensor's NodeId, not
5549    /// `self`'s.
5550    ///
5551    /// **Returns `Result`**: rank/shape/range mismatches surface as a
5552    /// typed error.
5553    pub fn write_slice(&self, source: &Self, ranges: Vec<(usize, usize)>) -> crate::Result<Self> {
5554        let inner = self.inner.write_slice(&source.inner, ranges)?;
5555        Ok(Self { inner })
5556    }
5557
5558    /// Append an [`fuel_graph::Op::WriteSlice`] whose start on `dyn_axis`
5559    /// is a **runtime** value resolved through the per-pass `SymEnv` at
5560    /// realize (Phase D symbolic extents). `ranges[dyn_axis].0` is
5561    /// ignored (the start is dynamic); the slab width
5562    /// `ranges[dyn_axis].1 - ranges[dyn_axis].0` must equal `source`'s
5563    /// `dyn_axis` dim and not exceed the destination capacity. Backs the
5564    /// persistent decode KV-cache write at the per-token `cached_len`.
5565    pub fn write_slice_dyn(
5566        &self,
5567        source: &Self,
5568        ranges: Vec<(usize, usize)>,
5569        dyn_axis: usize,
5570        offset: fuel_ir::DynScalar,
5571    ) -> crate::Result<Self> {
5572        let inner = self
5573            .inner
5574            .write_slice_dyn(&source.inner, ranges, dyn_axis, offset)?;
5575        Ok(Self { inner })
5576    }
5577
5578    /// Append an [`fuel_graph::Op::WriteSliceRotating`] node — like
5579    /// [`Self::write_slice`] but the `axis` axis wraps modulo
5580    /// `modulus`. `position` is a rank-0 U32 tensor whose value (read
5581    /// at realize time) is wrapped modulo `modulus` to determine the
5582    /// dynamic write start on `axis`. `ranges[axis].0` is ignored
5583    /// (the rotating-axis start is dynamic); the slab width
5584    /// `ranges[axis].1 - ranges[axis].0` must equal `source`'s
5585    /// `axis` dim and must not exceed `modulus`.
5586    ///
5587    /// Destructive on `self`: same scheduling as `write_slice`.
5588    /// Backs sliding-window KV caches (Mistral / Phi-3 sliding-
5589    /// window). Returns `Result`: rank / dtype / axis-bound /
5590    /// modulus / range mismatches surface as typed errors at
5591    /// build time.
5592    pub fn write_slice_rotating(
5593        &self,
5594        source: &Self,
5595        position: &Self,
5596        axis: usize,
5597        modulus: usize,
5598        ranges: Vec<(usize, usize)>,
5599    ) -> crate::Result<Self> {
5600        let inner = self.inner.write_slice_rotating(
5601            &source.inner,
5602            &position.inner,
5603            axis,
5604            modulus,
5605            ranges,
5606        )?;
5607        Ok(Self { inner })
5608    }
5609
5610    /// Append a [`fuel_graph::Op::WriteSliceDoff`] node — write `source`
5611    /// into a slab of `self` whose start on `axis` is read from `offset`
5612    /// (a rank-0 `I64` tensor) **device-side** at kernel launch. No
5613    /// modulo wrap: `offset` is the raw start on `axis`.
5614    /// `ranges[axis].0` is ignored; `ranges[axis].1 - ranges[axis].0`
5615    /// is the write width on `axis` and must equal `source`'s `axis`
5616    /// dim. Bounds (`offset + width <= dest_dims[axis]`) are the
5617    /// caller's contract (device-only at build). Destructive on `self`;
5618    /// same scheduling as `write_slice`. Backs the CUDA-graph-
5619    /// capturable KV-cache append (CapturedRun / `DecodeSession`).
5620    /// Returns `Result`: rank / dtype / axis-bound / static-width /
5621    /// offset-dtype mismatches surface as typed errors at build time.
5622    pub fn write_slice_doff(
5623        &self,
5624        source: &Self,
5625        offset: &Self,
5626        axis: usize,
5627        ranges: Vec<(usize, usize)>,
5628    ) -> crate::Result<Self> {
5629        let inner = self
5630            .inner
5631            .write_slice_doff(&source.inner, &offset.inner, axis, ranges)?;
5632        Ok(Self { inner })
5633    }
5634
5635    /// Append a [`fuel_graph::Op::Fused`] node carrying
5636    /// [`fuel_graph::registry::FusedOpParams::Conv2D`]. See `fuel_graph`'s
5637    /// `Tensor::conv2d` for the full shape contract: `self` must be
5638    /// `[N, Cin, H, W]`; `weight` must be `[Cout, Cin/groups, Kh, Kw]`;
5639    /// `bias` is optional and must be `[Cout]` when provided. Returns
5640    /// a rank-4 lazy tensor `[N, Cout, Hout, Wout]`.
5641    ///
5642    /// Rank / channel / `groups` / stride mismatches surface as typed
5643    /// errors at build time rather than panicking inside the inner
5644    /// `fuel_graph` call.
5645    pub fn conv2d(
5646        &self,
5647        weight: &Self,
5648        bias: Option<&Self>,
5649        stride: (usize, usize),
5650        padding: (usize, usize),
5651        groups: usize,
5652    ) -> std::result::Result<Self, fuel_ir::Error> {
5653        if groups < 1 {
5654            return Err(
5655                fuel_ir::Error::Msg(format!("conv2d: groups must be >= 1, got {groups}",)).bt(),
5656            );
5657        }
5658        let x_shape = self.inner.shape();
5659        let x_dims = x_shape.dims();
5660        let w_shape = weight.inner.shape();
5661        let w_dims = w_shape.dims();
5662        if x_dims.len() != 4 {
5663            return Err(fuel_ir::Error::Msg(format!(
5664                "conv2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
5665            ))
5666            .bt());
5667        }
5668        if w_dims.len() != 4 {
5669            return Err(fuel_ir::Error::Msg(format!(
5670                "conv2d: weight must be rank 4 [Cout, Cin/groups, Kh, Kw], got {w_dims:?}",
5671            ))
5672            .bt());
5673        }
5674        let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
5675        let (cout, cin_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
5676        if cin != cin_per_g * groups {
5677            return Err(fuel_ir::Error::Msg(format!(
5678                "conv2d: x has {cin} in-channels but weight expects {} ({cin_per_g}*{groups})",
5679                cin_per_g * groups,
5680            ))
5681            .bt());
5682        }
5683        if cout % groups != 0 {
5684            return Err(fuel_ir::Error::Msg(format!(
5685                "conv2d: Cout={cout} must be divisible by groups={groups}",
5686            ))
5687            .bt());
5688        }
5689        if let Some(b) = bias {
5690            let b_shape = b.inner.shape();
5691            let b_dims = b_shape.dims();
5692            if b_dims != [cout] {
5693                return Err(fuel_ir::Error::Msg(format!(
5694                    "conv2d: bias shape {b_dims:?} must match [Cout={cout}]",
5695                ))
5696                .bt());
5697            }
5698        }
5699        let (stride_h, stride_w) = stride;
5700        let (pad_h, pad_w) = padding;
5701        if stride_h < 1 || stride_w < 1 {
5702            return Err(fuel_ir::Error::Msg(format!(
5703                "conv2d: stride must be >= 1, got ({stride_h}, {stride_w})",
5704            ))
5705            .bt());
5706        }
5707        let h_padded = h_in + 2 * pad_h;
5708        let w_padded = w_in + 2 * pad_w;
5709        if h_padded < kh || w_padded < kw {
5710            return Err(fuel_ir::Error::Msg(format!(
5711                "conv2d: padded input ({h_padded}x{w_padded}) smaller than kernel ({kh}x{kw})",
5712            ))
5713            .bt());
5714        }
5715        Ok(Self {
5716            inner: self.inner.conv2d(
5717                &weight.inner,
5718                bias.map(|b| &b.inner),
5719                stride,
5720                padding,
5721                groups,
5722            ),
5723        })
5724    }
5725
5726    /// Append a [`fuel_graph::Op::Fused`] node carrying
5727    /// [`fuel_graph::registry::FusedOpParams::FlashAttn`]. `self` is `q`
5728    /// of shape `[B, Hq, Sq, D]`; `k` and `v` are `[B, Hkv, Sk, D]`
5729    /// with `Hq` a multiple of `Hkv` (GQA). `alibi_slopes` (optional)
5730    /// is `[Hq]`. Returns the attention output, shape `[B, Hq, Sq, D]`.
5731    ///
5732    /// Rank / batch / GQA-divisibility / head-dim mismatches surface
5733    /// as typed errors at build time rather than panicking inside the
5734    /// inner `fuel_graph` call.
5735    pub fn flash_attn(
5736        &self,
5737        k: &Self,
5738        v: &Self,
5739        alibi_slopes: Option<&Self>,
5740        softmax_scale: f32,
5741        causal: bool,
5742        window_size_left: Option<usize>,
5743        window_size_right: Option<usize>,
5744        softcap: Option<f32>,
5745    ) -> std::result::Result<Self, fuel_ir::Error> {
5746        let q_shape = self.inner.shape();
5747        let q_dims = q_shape.dims();
5748        let k_shape = k.inner.shape();
5749        let k_dims = k_shape.dims();
5750        let v_shape = v.inner.shape();
5751        let v_dims = v_shape.dims();
5752        if q_dims.len() != 4 {
5753            return Err(fuel_ir::Error::Msg(format!(
5754                "flash_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5755            ))
5756            .bt());
5757        }
5758        if k_dims.len() != 4 {
5759            return Err(fuel_ir::Error::Msg(format!(
5760                "flash_attn: k must be rank 4 [B, Hkv, Sk, D], got {k_dims:?}",
5761            ))
5762            .bt());
5763        }
5764        if v_dims.len() != 4 {
5765            return Err(fuel_ir::Error::Msg(format!(
5766                "flash_attn: v must be rank 4 [B, Hkv, Sk, D], got {v_dims:?}",
5767            ))
5768            .bt());
5769        }
5770        let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5771        let (bk, hkv, sk, dk) = (k_dims[0], k_dims[1], k_dims[2], k_dims[3]);
5772        let (bv, hkv_v, sk_v, dv) = (v_dims[0], v_dims[1], v_dims[2], v_dims[3]);
5773        if b != bk || b != bv {
5774            return Err(fuel_ir::Error::Msg(
5775                format!("flash_attn: B mismatch q={b} k={bk} v={bv}",),
5776            )
5777            .bt());
5778        }
5779        if hkv != hkv_v {
5780            return Err(fuel_ir::Error::Msg(format!(
5781                "flash_attn: Hkv mismatch k={hkv} vs v={hkv_v}",
5782            ))
5783            .bt());
5784        }
5785        if sk != sk_v {
5786            return Err(fuel_ir::Error::Msg(
5787                format!("flash_attn: Sk mismatch k={sk} vs v={sk_v}",),
5788            )
5789            .bt());
5790        }
5791        if d != dk || d != dv {
5792            return Err(fuel_ir::Error::Msg(format!(
5793                "flash_attn: head_dim mismatch q={d} k={dk} v={dv}",
5794            ))
5795            .bt());
5796        }
5797        if hkv == 0 || hq % hkv != 0 {
5798            return Err(fuel_ir::Error::Msg(format!(
5799                "flash_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5800            ))
5801            .bt());
5802        }
5803        if let Some(a) = alibi_slopes {
5804            let a_shape = a.inner.shape();
5805            let a_dims = a_shape.dims();
5806            if a_dims != [hq] {
5807                return Err(fuel_ir::Error::Msg(format!(
5808                    "flash_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5809                ))
5810                .bt());
5811            }
5812        }
5813        Ok(Self {
5814            inner: self.inner.flash_attn(
5815                &k.inner,
5816                &v.inner,
5817                alibi_slopes.map(|t| &t.inner),
5818                softmax_scale,
5819                causal,
5820                window_size_left,
5821                window_size_right,
5822                softcap,
5823            ),
5824        })
5825    }
5826
5827    /// Append a [`fuel_graph::Op::Fused`] node carrying
5828    /// [`fuel_graph::registry::FusedOpParams::PagedAttn`]. `self` is the Q
5829    /// tensor `[B, Hq, Sq, D]`. `k_cache` / `v_cache` are paged caches
5830    /// `[num_blocks, block_size, Hkv, D]`. `block_table` is `[B,
5831    /// max_blocks]` u32; `context_lens` is `[B]` u32.
5832    ///
5833    /// Rank / batch / GQA-divisibility / block-size / dtype mismatches
5834    /// surface as typed errors at build time rather than panicking
5835    /// inside the inner `fuel_graph` call.
5836    pub fn paged_attn(
5837        &self,
5838        k_cache: &Self,
5839        v_cache: &Self,
5840        block_table: &Self,
5841        context_lens: &Self,
5842        alibi_slopes: Option<&Self>,
5843        softmax_scale: f32,
5844        block_size: usize,
5845        softcap: Option<f32>,
5846    ) -> std::result::Result<Self, fuel_ir::Error> {
5847        if block_size < 1 {
5848            return Err(fuel_ir::Error::Msg("paged_attn: block_size must be >= 1".into()).bt());
5849        }
5850        let q_shape = self.inner.shape();
5851        let q_dims = q_shape.dims();
5852        let kc_shape = k_cache.inner.shape();
5853        let kc_dims = kc_shape.dims();
5854        let vc_shape = v_cache.inner.shape();
5855        let vc_dims = vc_shape.dims();
5856        let bt_shape = block_table.inner.shape();
5857        let bt_dims = bt_shape.dims();
5858        let cl_shape = context_lens.inner.shape();
5859        let cl_dims = cl_shape.dims();
5860        if q_dims.len() != 4 {
5861            return Err(fuel_ir::Error::Msg(format!(
5862                "paged_attn: q must be rank 4 [B, Hq, Sq, D], got {q_dims:?}",
5863            ))
5864            .bt());
5865        }
5866        if kc_dims.len() != 4 {
5867            return Err(fuel_ir::Error::Msg(format!(
5868                "paged_attn: k_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {kc_dims:?}",
5869            )).bt());
5870        }
5871        if vc_dims.len() != 4 {
5872            return Err(fuel_ir::Error::Msg(format!(
5873                "paged_attn: v_cache must be rank 4 [num_blocks, block_size, Hkv, D], got {vc_dims:?}",
5874            )).bt());
5875        }
5876        if bt_dims.len() != 2 {
5877            return Err(fuel_ir::Error::Msg(format!(
5878                "paged_attn: block_table must be rank 2 [B, max_blocks], got {bt_dims:?}",
5879            ))
5880            .bt());
5881        }
5882        if cl_dims.len() != 1 {
5883            return Err(fuel_ir::Error::Msg(format!(
5884                "paged_attn: context_lens must be rank 1 [B], got {cl_dims:?}",
5885            ))
5886            .bt());
5887        }
5888        let (b, hq, _sq, d) = (q_dims[0], q_dims[1], q_dims[2], q_dims[3]);
5889        if kc_dims[1] != block_size {
5890            return Err(fuel_ir::Error::Msg(format!(
5891                "paged_attn: k_cache block dim {} != block_size {block_size}",
5892                kc_dims[1],
5893            ))
5894            .bt());
5895        }
5896        if vc_dims[1] != block_size {
5897            return Err(fuel_ir::Error::Msg(format!(
5898                "paged_attn: v_cache block dim {} != block_size {block_size}",
5899                vc_dims[1],
5900            ))
5901            .bt());
5902        }
5903        let hkv = kc_dims[2];
5904        if vc_dims[2] != hkv {
5905            return Err(fuel_ir::Error::Msg(format!(
5906                "paged_attn: Hkv mismatch k_cache={hkv} vs v_cache={}",
5907                vc_dims[2],
5908            ))
5909            .bt());
5910        }
5911        if kc_dims[3] != d || vc_dims[3] != d {
5912            return Err(fuel_ir::Error::Msg(format!(
5913                "paged_attn: D mismatch q={d} k={} v={}",
5914                kc_dims[3], vc_dims[3],
5915            ))
5916            .bt());
5917        }
5918        if hkv == 0 || hq % hkv != 0 {
5919            return Err(fuel_ir::Error::Msg(format!(
5920                "paged_attn: Hq={hq} must be a positive multiple of Hkv={hkv}",
5921            ))
5922            .bt());
5923        }
5924        if bt_dims[0] != b {
5925            return Err(fuel_ir::Error::Msg(format!(
5926                "paged_attn: block_table batch dim {} != B={b}",
5927                bt_dims[0],
5928            ))
5929            .bt());
5930        }
5931        if cl_dims[0] != b {
5932            return Err(fuel_ir::Error::Msg(format!(
5933                "paged_attn: context_lens len {} != B={b}",
5934                cl_dims[0],
5935            ))
5936            .bt());
5937        }
5938        if block_table.inner.dtype() != fuel_ir::DType::U32 {
5939            return Err(fuel_ir::Error::Msg(format!(
5940                "paged_attn: block_table must be U32, got {:?}",
5941                block_table.inner.dtype(),
5942            ))
5943            .bt());
5944        }
5945        if context_lens.inner.dtype() != fuel_ir::DType::U32 {
5946            return Err(fuel_ir::Error::Msg(format!(
5947                "paged_attn: context_lens must be U32, got {:?}",
5948                context_lens.inner.dtype(),
5949            ))
5950            .bt());
5951        }
5952        if let Some(a) = alibi_slopes {
5953            let a_shape = a.inner.shape();
5954            let a_dims = a_shape.dims();
5955            if a_dims != [hq] {
5956                return Err(fuel_ir::Error::Msg(format!(
5957                    "paged_attn: alibi_slopes must be [Hq={hq}], got {a_dims:?}",
5958                ))
5959                .bt());
5960            }
5961        }
5962        Ok(Self {
5963            inner: self.inner.paged_attn(
5964                &k_cache.inner,
5965                &v_cache.inner,
5966                &block_table.inner,
5967                &context_lens.inner,
5968                alibi_slopes.map(|t| &t.inner),
5969                softmax_scale,
5970                block_size,
5971                softcap,
5972            ),
5973        })
5974    }
5975
5976    /// Append a [`fuel_graph::Op::Fused`] node carrying
5977    /// [`fuel_graph::registry::FusedOpParams::ConvTranspose2D`]. `self` must
5978    /// be `[N, Cin, H, W]`; `weight` must be `[Cin, Cout/groups, Kh, Kw]`
5979    /// (note transposed channel order vs `conv2d`). Returns a rank-4
5980    /// lazy tensor `[N, Cout, Hout, Wout]`.
5981    ///
5982    /// Rank / channel / `groups` / stride / dilation mismatches surface
5983    /// as typed errors at build time rather than panicking inside the
5984    /// inner `fuel_graph` call.
5985    pub fn conv_transpose2d(
5986        &self,
5987        weight: &Self,
5988        stride: (usize, usize),
5989        padding: (usize, usize),
5990        output_padding: (usize, usize),
5991        dilation: (usize, usize),
5992        groups: usize,
5993    ) -> std::result::Result<Self, fuel_ir::Error> {
5994        if groups < 1 {
5995            return Err(fuel_ir::Error::Msg(format!(
5996                "conv_transpose2d: groups must be >= 1, got {groups}",
5997            ))
5998            .bt());
5999        }
6000        let x_shape = self.inner.shape();
6001        let x_dims = x_shape.dims();
6002        let w_shape = weight.inner.shape();
6003        let w_dims = w_shape.dims();
6004        if x_dims.len() != 4 {
6005            return Err(fuel_ir::Error::Msg(format!(
6006                "conv_transpose2d: x must be rank 4 [N, Cin, H, W], got {x_dims:?}",
6007            ))
6008            .bt());
6009        }
6010        if w_dims.len() != 4 {
6011            return Err(fuel_ir::Error::Msg(format!(
6012                "conv_transpose2d: weight must be rank 4 [Cin, Cout/groups, Kh, Kw], got {w_dims:?}",
6013            )).bt());
6014        }
6015        let (cin, h_in, w_in) = (x_dims[1], x_dims[2], x_dims[3]);
6016        let (cin_w, cout_per_g, kh, kw) = (w_dims[0], w_dims[1], w_dims[2], w_dims[3]);
6017        if cin != cin_w {
6018            return Err(fuel_ir::Error::Msg(format!(
6019                "conv_transpose2d: x has {cin} in-channels but weight has {cin_w}",
6020            ))
6021            .bt());
6022        }
6023        if cin % groups != 0 {
6024            return Err(fuel_ir::Error::Msg(format!(
6025                "conv_transpose2d: Cin={cin} must be divisible by groups={groups}",
6026            ))
6027            .bt());
6028        }
6029        let (stride_h, stride_w) = stride;
6030        let (pad_h, pad_w) = padding;
6031        let (out_pad_h, out_pad_w) = output_padding;
6032        let (dil_h, dil_w) = dilation;
6033        if stride_h < 1 || stride_w < 1 {
6034            return Err(fuel_ir::Error::Msg(format!(
6035                "conv_transpose2d: stride must be >= 1, got ({stride_h}, {stride_w})",
6036            ))
6037            .bt());
6038        }
6039        if dil_h < 1 || dil_w < 1 {
6040            return Err(fuel_ir::Error::Msg(format!(
6041                "conv_transpose2d: dilation must be >= 1, got ({dil_h}, {dil_w})",
6042            ))
6043            .bt());
6044        }
6045        let h_out = h_in.saturating_sub(1) * stride_h + dil_h * (kh - 1) + out_pad_h + 1;
6046        let w_out = w_in.saturating_sub(1) * stride_w + dil_w * (kw - 1) + out_pad_w + 1;
6047        if h_out <= 2 * pad_h || w_out <= 2 * pad_w {
6048            return Err(fuel_ir::Error::Msg(format!(
6049                "conv_transpose2d: padding ({pad_h}x{pad_w}) is larger than the produced output dims ({h_out}x{w_out})",
6050            )).bt());
6051        }
6052        let _ = cout_per_g;
6053        Ok(Self {
6054            inner: self.inner.conv_transpose2d(
6055                &weight.inner,
6056                stride,
6057                padding,
6058                output_padding,
6059                dilation,
6060                groups,
6061            ),
6062        })
6063    }
6064
6065    /// Append a transposed 1D convolution. `self` is
6066    /// `[N, Cin, Lin]`; `weight` is `[Cin, Cout/groups, K]`
6067    /// (PyTorch channel order). Returns `[N, Cout, Lout]`.
6068    ///
6069    /// Internally lifts to rank-4 and dispatches through
6070    /// `conv_transpose2d` — there is no separate 1D op in the
6071    /// IR; the lift is transparent to the executor (which sees
6072    /// the same `Op::Fused(CONV_TRANSPOSE2D, _)` it already
6073    /// dispatches CPU kernels for).
6074    ///
6075    /// Unblocks audio codec decoders (DAC, EnCodec, SNAC, Mimi,
6076    /// Parler-TTS, MetaVoice, CSM) which all upsample quantized
6077    /// latents to waveform via strided transposed convs.
6078    pub fn conv_transpose1d(
6079        &self,
6080        weight: &Self,
6081        stride: usize,
6082        padding: usize,
6083        output_padding: usize,
6084        dilation: usize,
6085        groups: usize,
6086    ) -> std::result::Result<Self, fuel_ir::Error> {
6087        if groups < 1 {
6088            return Err(fuel_ir::Error::Msg(format!(
6089                "conv_transpose1d: groups must be >= 1, got {groups}",
6090            ))
6091            .bt());
6092        }
6093        let x_shape = self.inner.shape();
6094        let x_dims = x_shape.dims();
6095        let w_shape = weight.inner.shape();
6096        let w_dims = w_shape.dims();
6097        if x_dims.len() != 3 {
6098            return Err(fuel_ir::Error::Msg(format!(
6099                "conv_transpose1d: x must be rank 3 [N, Cin, Lin], got {x_dims:?}",
6100            ))
6101            .bt());
6102        }
6103        if w_dims.len() != 3 {
6104            return Err(fuel_ir::Error::Msg(format!(
6105                "conv_transpose1d: weight must be rank 3 [Cin, Cout/groups, K], got {w_dims:?}",
6106            ))
6107            .bt());
6108        }
6109        if stride < 1 {
6110            return Err(fuel_ir::Error::Msg(format!(
6111                "conv_transpose1d: stride must be >= 1, got {stride}",
6112            ))
6113            .bt());
6114        }
6115        if dilation < 1 {
6116            return Err(fuel_ir::Error::Msg(format!(
6117                "conv_transpose1d: dilation must be >= 1, got {dilation}",
6118            ))
6119            .bt());
6120        }
6121        let cin = x_dims[1];
6122        let cin_w = w_dims[0];
6123        if cin != cin_w {
6124            return Err(fuel_ir::Error::Msg(format!(
6125                "conv_transpose1d: x has {cin} in-channels but weight has {cin_w}",
6126            ))
6127            .bt());
6128        }
6129        if !cin.is_multiple_of(groups) {
6130            return Err(fuel_ir::Error::Msg(format!(
6131                "conv_transpose1d: Cin={cin} must be divisible by groups={groups}",
6132            ))
6133            .bt());
6134        }
6135        Ok(Self {
6136            inner: self.inner.conv_transpose1d(
6137                &weight.inner,
6138                stride,
6139                padding,
6140                output_padding,
6141                dilation,
6142                groups,
6143            ),
6144        })
6145    }
6146}
6147
6148// ============================================================================
6149// Phase A.1 — wrapper additions (eager-`Tensor` retirement program).
6150//
6151// Methods on `fuel_graph::NodeHandle` that weren't previously surfaced through
6152// `Tensor`. Pure delegation; no new graph ops. See
6153// `docs/session-prompts/eager-tensor-retirement-master-plan.md`.
6154// ============================================================================
6155
6156impl Tensor {
6157    // ---- shape ops: unsqueeze (Result + Dim) + Result-returning siblings ----
6158
6159    /// Append a size-1 dimension at position `dim`. Inverse of
6160    /// [`Self::squeeze`]. Accepts any [`Dim`] (`usize`, `D::Minus1`,
6161    /// etc.). Bad `dim` surfaces as a typed error at build time.
6162    pub fn unsqueeze<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6163        let shape = self.inner.shape();
6164        let dim = dim.to_index_plus_one(&shape, "unsqueeze")?;
6165        Ok(Self {
6166            inner: self.inner.try_unsqueeze(dim)?,
6167        })
6168    }
6169
6170    // ---- triangular masking (canonical attention masks) ----
6171
6172    /// Upper-triangular mask along the last two dims. `diagonal = 0`
6173    /// keeps the main diagonal and above; positive shifts higher.
6174    pub fn triu(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6175        Ok(Self {
6176            inner: self.inner.triu(diagonal)?,
6177        })
6178    }
6179
6180    /// Lower-triangular mask along the last two dims. `tril(0)` is the
6181    /// canonical causal-attention mask.
6182    pub fn tril(&self, diagonal: i64) -> std::result::Result<Self, fuel_ir::Error> {
6183        Ok(Self {
6184            inner: self.inner.tril(diagonal)?,
6185        })
6186    }
6187
6188    // ---- additional reductions / activations ----
6189
6190    /// `log(softmax(self))` along the last dim, fused into one op.
6191    pub fn log_softmax_last_dim(&self) -> std::result::Result<Self, fuel_ir::Error> {
6192        Ok(Self {
6193            inner: self.inner.log_softmax_last_dim()?,
6194        })
6195    }
6196
6197    /// Numerically-stable softmax along an arbitrary axis. Accepts any
6198    /// [`Dim`]. Decomposes into `max_keepdim` / `broadcast_sub` / `exp` /
6199    /// `sum_keepdim` / `broadcast_div`, all of which already accept
6200    /// `D: Dim`, so this is a pure composition with no new graph op.
6201    ///
6202    /// When `dim` resolves to the last axis, prefer
6203    /// [`Self::softmax_last_dim`], which dispatches to the fused
6204    /// `SoftmaxLastDim` op (single kernel rather than five graph nodes).
6205    pub fn softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6206        let shape = self.inner.shape();
6207        // Resolve once to a concrete `usize` so we can pass it to each
6208        // composed call (the `Dim` trait doesn't require `Copy`, so we
6209        // can't reuse the generic `D` across multiple calls).
6210        let axis: usize = dim.to_index(&shape, "softmax")?;
6211        let m = self.max_keepdim(axis)?;
6212        let shifted = self.broadcast_sub(&m)?;
6213        let e = shifted.exp();
6214        let s = e.sum_keepdim(axis)?;
6215        e.broadcast_div(&s)
6216    }
6217
6218    /// Numerically-stable `log(softmax(self))` along an arbitrary axis.
6219    /// Accepts any [`Dim`]. Computes `x - max - log(sum(exp(x - max)))`
6220    /// — the standard log-sum-exp form, which avoids the explicit
6221    /// `softmax`-then-`log` underflow path. Pure composition over
6222    /// existing primitives.
6223    ///
6224    /// When `dim` resolves to the last axis, prefer
6225    /// [`Self::log_softmax_last_dim`], which dispatches to the fused
6226    /// `LogSoftmaxLastDim` op.
6227    pub fn log_softmax<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6228        let shape = self.inner.shape();
6229        let axis: usize = dim.to_index(&shape, "log_softmax")?;
6230        let m = self.max_keepdim(axis)?;
6231        let shifted = self.broadcast_sub(&m)?;
6232        let lse = shifted.exp().sum_keepdim(axis)?.log();
6233        shifted.broadcast_sub(&lse)
6234    }
6235
6236    /// Argmin along `dim`, returning a U32 tensor with the reduced dim
6237    /// removed. Non-differentiable. Bad `dim` surfaces as a typed
6238    /// error at build time. Accepts any [`Dim`].
6239    pub fn argmin_dim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6240        let shape = self.inner.shape();
6241        let dim = dim.to_index(&shape, "argmin_dim")?;
6242        Ok(Self {
6243            inner: self.inner.argmin_dim(dim),
6244        })
6245    }
6246
6247    // ---- masking / scatter ----
6248
6249    /// Fill every position where `mask != 0` with `value`; pass `self`
6250    /// through everywhere `mask == 0`. `mask` must be U8 with the same
6251    /// shape as `self`; `value`'s dtype must match `self`.
6252    pub fn masked_fill(
6253        &self,
6254        mask: &Self,
6255        value: fuel_ir::Scalar,
6256    ) -> std::result::Result<Self, fuel_ir::Error> {
6257        Ok(Self {
6258            inner: self.inner.masked_fill(&mask.inner, value)?,
6259        })
6260    }
6261
6262    /// `self + scatter(indices, src, dim=dim)` — accumulate `src` rows
6263    /// at positions named by `indices` along `dim`. `indices` is rank-1
6264    /// U32 with length equal to `src.dims()[dim]`. Accepts any [`Dim`].
6265    /// Dim bounds / index dtype / shape / dtype-parity mismatches
6266    /// surface as typed errors at build time.
6267    pub fn index_add<D: Dim>(
6268        &self,
6269        dim: D,
6270        indices: &Self,
6271        src: &Self,
6272    ) -> std::result::Result<Self, fuel_ir::Error> {
6273        let shape = self.inner.shape();
6274        let dim = dim.to_index(&shape, "index_add")?;
6275        if indices.inner.dtype() != fuel_ir::DType::U32 {
6276            return Err(fuel_ir::Error::Msg(format!(
6277                "index_add: index must be U32, got {:?}",
6278                indices.inner.dtype(),
6279            ))
6280            .bt());
6281        }
6282        if self.inner.dtype() != src.inner.dtype() {
6283            return Err(fuel_ir::Error::Msg(format!(
6284                "index_add: base and src dtypes must match, got {:?} vs {:?}",
6285                self.inner.dtype(),
6286                src.inner.dtype(),
6287            ))
6288            .bt());
6289        }
6290        let base_dims = shape.dims();
6291        let src_shape = src.inner.shape();
6292        let src_dims = src_shape.dims();
6293        if base_dims.len() != src_dims.len() {
6294            return Err(fuel_ir::Error::Msg(format!(
6295                "index_add: base and src must have the same rank, got {} vs {}",
6296                base_dims.len(),
6297                src_dims.len(),
6298            ))
6299            .bt());
6300        }
6301        let idx_shape = indices.inner.shape();
6302        let idx_dims = idx_shape.dims();
6303        if idx_dims.len() != 1 {
6304            return Err(fuel_ir::Error::Msg(format!(
6305                "index_add: index must be rank 1, got {idx_dims:?}",
6306            ))
6307            .bt());
6308        }
6309        if src_dims[dim] != idx_dims[0] {
6310            return Err(fuel_ir::Error::Msg(format!(
6311                "index_add: src dim {dim} ({}) must match index length ({})",
6312                src_dims[dim], idx_dims[0],
6313            ))
6314            .bt());
6315        }
6316        Ok(Self {
6317            inner: self.inner.index_add(dim, &indices.inner, &src.inner),
6318        })
6319    }
6320
6321    /// Functional inverse of [`Self::gather`]. Accumulates `src` into
6322    /// `self` at positions given by `indices` (substituted at `dim`).
6323    /// Accepts any [`Dim`]. Dim bounds / index dtype / shape / dtype-
6324    /// parity mismatches surface as typed errors at build time.
6325    pub fn scatter_add<D: Dim>(
6326        &self,
6327        dim: D,
6328        indices: &Self,
6329        src: &Self,
6330    ) -> std::result::Result<Self, fuel_ir::Error> {
6331        let shape = self.inner.shape();
6332        let dim = dim.to_index(&shape, "scatter_add")?;
6333        if indices.inner.dtype() != fuel_ir::DType::U32 {
6334            return Err(fuel_ir::Error::Msg(format!(
6335                "scatter_add: index must be U32, got {:?}",
6336                indices.inner.dtype(),
6337            ))
6338            .bt());
6339        }
6340        if self.inner.dtype() != src.inner.dtype() {
6341            return Err(fuel_ir::Error::Msg(format!(
6342                "scatter_add: base and src dtypes must match, got {:?} vs {:?}",
6343                self.inner.dtype(),
6344                src.inner.dtype(),
6345            ))
6346            .bt());
6347        }
6348        let idx_shape = indices.inner.shape();
6349        let src_shape = src.inner.shape();
6350        if idx_shape.dims() != src_shape.dims() {
6351            return Err(fuel_ir::Error::Msg(format!(
6352                "scatter_add: index and src must have the same shape, got {:?} vs {:?}",
6353                idx_shape.dims(),
6354                src_shape.dims(),
6355            ))
6356            .bt());
6357        }
6358        Ok(Self {
6359            inner: self.inner.scatter_add(dim, &indices.inner, &src.inner),
6360        })
6361    }
6362
6363    // ---- in-place activations (Phase 4-5 infrastructure, now surfaced) ----
6364    //
6365    // These mutate `self`'s storage in place. Safe to call on
6366    // tape-tracked tensors after Phase 4's view-aware ordering pass and
6367    // Phase 5's auto-copy pass. See `project_inplace_ops_complete`
6368    // memory entry.
6369
6370    /// In-place `max(0, self)`. See [`Self::relu`] for the functional
6371    /// variant.
6372    pub fn relu_inplace(&self) -> Self {
6373        Self {
6374            inner: self.inner.relu_inplace(),
6375        }
6376    }
6377
6378    /// In-place `self * sigmoid(self)`. See [`Self::silu`] for the
6379    /// functional variant.
6380    pub fn silu_inplace(&self) -> Self {
6381        Self {
6382            inner: self.inner.silu_inplace(),
6383        }
6384    }
6385
6386    /// In-place tanh-approximation GELU. See [`Self::gelu_tanh`] for the
6387    /// functional variant.
6388    pub fn gelu_tanh_inplace(&self) -> Self {
6389        Self {
6390            inner: self.inner.gelu_tanh_inplace(),
6391        }
6392    }
6393
6394    /// In-place `tanh(self)`. See [`Self::tanh`] for the functional
6395    /// variant.
6396    pub fn tanh_inplace(&self) -> Self {
6397        Self {
6398            inner: self.inner.tanh_inplace(),
6399        }
6400    }
6401
6402    /// In-place `sigmoid(self)`. See [`Self::sigmoid`] for the
6403    /// functional variant.
6404    pub fn sigmoid_inplace(&self) -> Self {
6405        Self {
6406            inner: self.inner.sigmoid_inplace(),
6407        }
6408    }
6409
6410    /// In-place `self = mul · self + add`. Single fused-op equivalent
6411    /// of `self.mul_scalar(mul).add_scalar(add)` plus reassignment.
6412    pub fn affine_inplace(&self, mul: f64, add: f64) -> Self {
6413        Self {
6414            inner: self.inner.affine_inplace(mul, add),
6415        }
6416    }
6417
6418    // ---- additional const_*_like factories ----
6419
6420    /// Build a sibling F64 `Const` on the same graph as `self`.
6421    pub fn const_f64_like(
6422        &self,
6423        data: impl Into<Arc<[f64]>>,
6424        shape: impl Into<Shape>,
6425    ) -> std::result::Result<Self, fuel_ir::Error> {
6426        Ok(Self {
6427            inner: self.inner.const_f64_like(data, shape)?,
6428        })
6429    }
6430
6431    /// Build a sibling I64 `Const` on the same graph. Used by integer-
6432    /// target ops (e.g. cross-entropy with PyTorch-convention class
6433    /// indices).
6434    pub fn const_i64_like(
6435        &self,
6436        data: impl Into<Arc<[i64]>>,
6437        shape: impl Into<Shape>,
6438    ) -> std::result::Result<Self, fuel_ir::Error> {
6439        Ok(Self {
6440            inner: self.inner.const_i64_like(data, shape)?,
6441        })
6442    }
6443
6444    // ---- device residency control ----
6445
6446    /// Pin this tensor's realized storage to `device`. Consumes `self`
6447    /// because the placement is a graph-level annotation tied to the
6448    /// node id rather than a side-effecting operation.
6449    pub fn on_device(self, device: &Device) -> Self {
6450        Self {
6451            inner: self.inner.on_device(device.location()),
6452        }
6453    }
6454
6455    /// Append an `Op::Release` node — explicitly drop this tensor's
6456    /// device-resident storage once the ordering pass has scheduled
6457    /// every reader before it.
6458    pub fn release(&self) -> Self {
6459        Self {
6460            inner: self.inner.release(),
6461        }
6462    }
6463
6464    /// Move bytes to `device`, destroying the source. Use when the
6465    /// source is genuinely dead after the transfer.
6466    pub fn move_to_device(&self, device: &Device) -> Self {
6467        Self {
6468            inner: self.inner.move_to_device(device.location()),
6469        }
6470    }
6471
6472    /// Copy bytes to `device`, leaving the source resident. Use when
6473    /// other ops still need the source.
6474    pub fn copy_to_device(&self, device: &Device) -> Self {
6475        Self {
6476            inner: self.inner.copy_to_device(device.location()),
6477        }
6478    }
6479
6480    // ---- autograd ----
6481
6482    /// Run reverse-mode autograd from this tensor as the loss, returning
6483    /// a [`fuel_graph::GradMap`] keyed by every input tensor reached.
6484    /// The gradient nodes extend the same graph; realizing a gradient
6485    /// re-executes the forward dependencies.
6486    pub fn backward(&self) -> fuel_graph::GradMap {
6487        self.inner.backward()
6488    }
6489}
6490
6491// ============================================================================
6492// Phase A.2 — composite primitives expressible from existing ops.
6493//
6494// Each method here is implemented in terms of `Tensor`'s existing
6495// surface (reshape, permute, concat, unsqueeze, etc.). No new graph ops.
6496// ============================================================================
6497
6498impl Tensor {
6499    /// Transpose the last two dims as a Result-returning convenience —
6500    /// rank < 2 surfaces as an error rather than the panic the
6501    /// no-arg [`Self::transpose`] would produce. Alias for the eager
6502    /// `transpose_last_two`.
6503    pub fn transpose_last_two(&self) -> std::result::Result<Self, fuel_ir::Error> {
6504        self.transpose()
6505    }
6506
6507    /// Eager-API alias of [`Self::transpose_last_two`]. Matches PyTorch's
6508    /// `.t()` short form and the existing eager [`Tensor::t`] method.
6509    pub fn t(&self) -> std::result::Result<Self, fuel_ir::Error> {
6510        self.transpose()
6511    }
6512
6513    /// Two-argument transpose: swap dims `dim1` and `dim2`, leaving the
6514    /// rest in place. Implemented via [`fuel_graph::NodeHandle::try_permute`]; matches the
6515    /// eager `transpose(d1, d2)` two-arg form. Accepts any [`Dim`]
6516    /// (`usize`, `D::Minus1`, etc.).
6517    pub fn transpose_dims<D1: Dim, D2: Dim>(
6518        &self,
6519        dim1: D1,
6520        dim2: D2,
6521    ) -> std::result::Result<Self, fuel_ir::Error> {
6522        let shape = self.shape();
6523        let dim1 = dim1.to_index(&shape, "transpose_dims")?;
6524        let dim2 = dim2.to_index(&shape, "transpose_dims")?;
6525        if dim1 == dim2 {
6526            return Ok(self.clone());
6527        }
6528        let rank = shape.dims().len();
6529        let mut axes: Vec<usize> = (0..rank).collect();
6530        axes.swap(dim1, dim2);
6531        self.permute(axes.as_slice())
6532    }
6533
6534    /// Collapse dims `[start_dim, end_dim]` (inclusive) into a single
6535    /// dimension. Returns `Result` so out-of-bounds surfaces as a typed
6536    /// error rather than a panic. Accepts any [`Dim`] for either arg
6537    /// (`D::Minus1` for the last axis works).
6538    pub fn flatten<D1: Dim, D2: Dim>(
6539        &self,
6540        start_dim: D1,
6541        end_dim: D2,
6542    ) -> std::result::Result<Self, fuel_ir::Error> {
6543        let shape = self.shape();
6544        let rank = shape.dims().len();
6545        if rank == 0 {
6546            return Ok(self.clone());
6547        }
6548        let start_dim = start_dim.to_index(&shape, "flatten")?;
6549        let end_dim = end_dim.to_index(&shape, "flatten")?;
6550        if start_dim > end_dim {
6551            return Err(fuel_ir::Error::Msg(format!(
6552                "flatten: start_dim={start_dim} > end_dim={end_dim}",
6553            ))
6554            .bt());
6555        }
6556        let dims = shape.dims();
6557        let merged: usize = dims[start_dim..=end_dim].iter().product();
6558        let mut new_dims: Vec<usize> = Vec::with_capacity(rank - (end_dim - start_dim));
6559        new_dims.extend_from_slice(&dims[..start_dim]);
6560        new_dims.push(merged);
6561        new_dims.extend_from_slice(&dims[end_dim + 1..]);
6562        self.reshape(new_dims)
6563    }
6564
6565    /// Flatten dims `[0, end_dim]` (inclusive) into one.
6566    pub fn flatten_to<D: Dim>(&self, end_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6567        self.flatten(0_usize, end_dim)
6568    }
6569
6570    /// Flatten dims `[start_dim, rank-1]` into one.
6571    pub fn flatten_from<D: Dim>(&self, start_dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6572        let rank = self.shape().dims().len();
6573        if rank == 0 {
6574            return Ok(self.clone());
6575        }
6576        self.flatten(start_dim, rank - 1)
6577    }
6578
6579    /// Flatten the tensor to rank-1 (single dim containing every element).
6580    pub fn flatten_all(&self) -> std::result::Result<Self, fuel_ir::Error> {
6581        let rank = self.shape().dims().len();
6582        if rank == 0 {
6583            return Ok(self.clone());
6584        }
6585        self.flatten(0, rank - 1)
6586    }
6587
6588    /// Stack tensors along a new dim at position `dim`. Each input is
6589    /// `unsqueeze`d at `dim` then concatenated. All inputs must have
6590    /// identical shape; `dim` may equal `rank` (append a new trailing
6591    /// dim). Accepts any [`Dim`].
6592    pub fn stack<D: Dim>(args: &[&Self], dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6593        if args.is_empty() {
6594            return Err(fuel_ir::Error::Msg("stack: requires at least one tensor".into()).bt());
6595        }
6596        let reference_shape = args[0].shape();
6597        let reference_dims = reference_shape.dims().to_vec();
6598        let dim = dim.to_index_plus_one(&reference_shape, "stack")?;
6599        for (idx, t) in args.iter().enumerate().skip(1) {
6600            if t.shape().dims() != reference_dims.as_slice() {
6601                return Err(fuel_ir::Error::Msg(format!(
6602                    "stack: tensor {idx} shape {:?} != reference shape {:?}",
6603                    t.shape().dims(),
6604                    reference_dims,
6605                ))
6606                .bt());
6607            }
6608        }
6609        // unsqueeze every input at the new dim, then concat.
6610        let mut iter = args.iter();
6611        let first = iter.next().unwrap().unsqueeze(dim)?;
6612        let mut acc = first;
6613        for t in iter {
6614            let u = t.unsqueeze(dim)?;
6615            acc = acc.concat(&u, dim)?;
6616        }
6617        Ok(acc)
6618    }
6619
6620    // ---- keepdim reductions ----
6621    //
6622    // Each keepdim variant is the squeezed reduction post-composed with
6623    // `unsqueeze` at the same dim. The graph optimizer can fuse these
6624    // back into a single op when it's profitable; until then, the cost
6625    // is one extra view-only node.
6626
6627    /// Sum along `dim`, keeping the reduced dim as size 1. Accepts any
6628    /// [`Dim`]. Returns Result because of the cascade from [`Self::unsqueeze`].
6629    pub fn sum_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6630        let shape = self.shape();
6631        let dim = dim.to_index(&shape, "sum_keepdim")?;
6632        self.sum_dim(dim).unwrap().unsqueeze(dim)
6633    }
6634
6635    /// Mean along `dim`, keeping the reduced dim as size 1.
6636    pub fn mean_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6637        let shape = self.shape();
6638        let dim = dim.to_index(&shape, "mean_keepdim")?;
6639        self.mean_dim(dim).unwrap().unsqueeze(dim)
6640    }
6641
6642    /// Max along `dim`, keeping the reduced dim as size 1.
6643    pub fn max_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6644        let shape = self.shape();
6645        let dim = dim.to_index(&shape, "max_keepdim")?;
6646        self.max_dim(dim).unwrap().unsqueeze(dim)
6647    }
6648
6649    /// Min along `dim`, keeping the reduced dim as size 1.
6650    pub fn min_keepdim<D: Dim>(&self, dim: D) -> std::result::Result<Self, fuel_ir::Error> {
6651        let shape = self.shape();
6652        let dim = dim.to_index(&shape, "min_keepdim")?;
6653        // sum_dim/mean_dim/max_dim/min_dim return Self today (A.8b.9 will
6654        // flip them to Result); chain through `.unsqueeze(dim)?` which now
6655        // owns the build-time dim validation.
6656        self.min_dim(dim).unwrap().unsqueeze(dim)
6657    }
6658
6659    /// Variance along `dim`, keeping the reduced dim as size 1. Divides
6660    /// squared deviations by `n - correction` (numpy/PyTorch-2.x
6661    /// `correction` convention: `0.0` is the **population** variance
6662    /// — KISS-Ops §6.13's default, and numpy's own default — `1.0` is
6663    /// Bessel's (sample/unbiased) correction, matching PyTorch's *older*
6664    /// default and the eager [`Tensor::var_keepdim`]'s prior behavior.
6665    ///
6666    /// **Not a default-argument convenience**: KISS-Ops §6.13 requires
6667    /// Bessel's correction to be an EXPLICIT attribute, not an implicit
6668    /// torch-style default silently baked into the divisor — this
6669    /// parameter exists so a caller cannot get Bessel's correction by
6670    /// omission. The divisor is clamped at zero, `max(0, n - correction)`
6671    /// (the torch rule), so the result is never negative and never a panic:
6672    /// `correction == n` is `0/0 = NaN`; `correction > n` is `x/0 = inf`
6673    /// (`NaN` if the sum of squared deviations is 0, e.g. a single element).
6674    /// Before 2026-11-25 only `correction == n` was non-finite and
6675    /// `correction > n` returned a finite, possibly NEGATIVE variance.
6676    pub fn var_keepdim<D: Dim>(
6677        &self,
6678        dim: D,
6679        correction: f64,
6680    ) -> std::result::Result<Self, fuel_ir::Error> {
6681        // A NaN correction is a caller error: `f64::max` returns the non-NaN operand, so it would otherwise be
6682        // clamped to a zero divisor and silently turn a NaN result into `inf` (PIP #715 L2).
6683        if correction.is_nan() {
6684            return Err(fuel_ir::Error::Msg(
6685                "var_keepdim: correction must not be NaN".to_string(),
6686            ));
6687        }
6688        let shape = self.shape();
6689        let dim = dim.to_index(&shape, "var_keepdim")?;
6690        let dims = shape.dims();
6691        let n = dims[dim];
6692        let mean = self.mean_keepdim(dim)?;
6693        let deviation = self.broadcast_sub(&mean).unwrap();
6694        let squares = deviation.sqr();
6695        // sum_keepdim then divide by (n - correction); leaves the reduced dim as 1.
6696        let summed = squares.sum_keepdim(dim)?;
6697        let divisor = (n as f64 - correction).max(0.0);
6698        Ok(summed.mul_scalar(1.0 / divisor))
6699    }
6700
6701    /// Variance along `dim`, squeezing the reduced dim. See
6702    /// [`Self::var_keepdim`] for the `correction` parameter's meaning.
6703    pub fn var<D: Dim>(
6704        &self,
6705        dim: D,
6706        correction: f64,
6707    ) -> std::result::Result<Self, fuel_ir::Error> {
6708        let shape = self.shape();
6709        let dim = dim.to_index(&shape, "var")?;
6710        self.var_keepdim(dim, correction)?.squeeze(dim)
6711    }
6712
6713    // ---- composite scalar / binary ops (Phase A.4) ----
6714
6715    /// `y = mul * self + add` element-wise. Two-op composite of
6716    /// [`Self::mul_scalar`] then [`Self::add_scalar`]; a fused `Op::Affine`
6717    /// can collapse this into a single op later (see the in-place
6718    /// counterpart [`Self::affine_inplace`]).
6719    pub fn affine(&self, mul: f64, add: f64) -> Self {
6720        self.mul_scalar(mul).add_scalar(add)
6721    }
6722
6723    /// `y = scale * self + shift`. Alias of [`Self::affine`] with
6724    /// descriptive parameter names; matches eager's
6725    /// `Tensor::scale_and_shift`.
6726    pub fn scale_and_shift(&self, scale: f64, shift: f64) -> Self {
6727        self.affine(scale, shift)
6728    }
6729
6730    /// Exponential Linear Unit: `self` where `self > 0`,
6731    /// `alpha * (exp(self) - 1)` otherwise. Composite of `where_cond`,
6732    /// `gt`, `exp`, `affine`.
6733    pub fn elu(&self, alpha: f64) -> Self {
6734        // Negative-branch value: alpha * (exp(self) - 1) = alpha * exp(self) - alpha
6735        let neg_branch = self.exp().affine(alpha, -alpha);
6736        // Mask: self > 0. Build a zero on the same graph.
6737        // GAP-003 carve-out. THE PROOF IS LOCAL AND ON THIS LINE: the buffer is
6738        // `vec![0.0; self.elem_count()]` and the shape is `self.shape()`, whose
6739        // elem_count IS that number. Both from `self`; no caller supplies either.
6740        let zero = self
6741            .const_f32_like(vec![0.0; self.elem_count()], self.shape())
6742            .expect("elu: vec![_; self.elem_count()] against self.shape() -- same source");
6743        let mask = self.gt(&zero).unwrap();
6744        mask.where_cond(self, &neg_branch).unwrap()
6745    }
6746
6747    /// Inner product of two rank-1 tensors. Composite of `mul` +
6748    /// `sum_all`; matches eager's [`Tensor::dot`].
6749    pub fn dot(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6750        let a = self.shape().dims().to_vec();
6751        let b = rhs.shape().dims().to_vec();
6752        if a.len() != 1 || b.len() != 1 {
6753            return Err(fuel_ir::Error::Msg(format!(
6754                "dot: requires rank-1 inputs, got lhs={a:?} rhs={b:?}",
6755            ))
6756            .bt());
6757        }
6758        if a[0] != b[0] {
6759            return Err(fuel_ir::Error::Msg(format!(
6760                "dot: length mismatch lhs={} rhs={}",
6761                a[0], b[0],
6762            ))
6763            .bt());
6764        }
6765        Ok(self.mul(rhs).unwrap().sum_all())
6766    }
6767
6768    /// Matrix × vector: `[m, n] · [n] -> [m]`. No broadcasting. Composite
6769    /// of `unsqueeze` + `matmul` + `squeeze`. Matches eager's
6770    /// [`Tensor::mv`].
6771    pub fn mv(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6772        let a = self.shape().dims().to_vec();
6773        let b = rhs.shape().dims().to_vec();
6774        if a.len() != 2 || b.len() != 1 || a[1] != b[0] {
6775            return Err(fuel_ir::Error::Msg(format!(
6776                "mv: shape mismatch lhs={a:?} rhs={b:?} (need [m,n] · [n])",
6777            ))
6778            .bt());
6779        }
6780        // unsqueeze rhs to [n,1], matmul -> [m,1], squeeze trailing dim.
6781        let rhs_col = rhs.unsqueeze(1_usize)?;
6782        let prod = self.matmul(&rhs_col).unwrap();
6783        prod.squeeze(1_usize)
6784    }
6785
6786    /// Alias of [`Self::mv`] with a more descriptive name. Matches
6787    /// eager's [`Tensor::matvec`].
6788    pub fn matvec(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6789        self.mv(rhs)
6790    }
6791
6792    /// Broadcast-aware matmul. Lazy's [`Self::matmul`] already accepts
6793    /// broadcast-compatible operands; this method is exposed for
6794    /// signature compatibility with eager's `Tensor::broadcast_matmul`.
6795    pub fn broadcast_matmul(&self, rhs: &Self) -> std::result::Result<Self, fuel_ir::Error> {
6796        self.matmul(rhs)
6797    }
6798
6799    // ---- Phase A.5 factory family ----
6800    //
6801    // Instance methods derive shape + dtype from `self` and place the new
6802    // tensor on the same graph via `const_*_like`. Static methods build
6803    // a fresh graph anchored on a host-allocated buffer.
6804
6805    /// New tensor with the same shape, dtype, and graph as `self`, filled
6806    /// with ones. Returns Err for unsupported dtypes (anything outside
6807    /// F32/F64/BF16/F16/U32/I64) — matches eager `Tensor::ones_like` parity.
6808    pub fn ones_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6809        let n = self.elem_count();
6810        let shape = self.shape();
6811        match self.dtype() {
6812            DType::F32 => self.const_f32_like(vec![1.0_f32; n], shape),
6813            DType::F64 => self.const_f64_like(vec![1.0_f64; n], shape),
6814            DType::BF16 => self.const_bf16_like(vec![half::bf16::ONE; n], shape),
6815            DType::F16 => self.const_f16_like(vec![half::f16::ONE; n], shape),
6816            DType::U32 => self.const_u32_like(vec![1_u32; n], shape),
6817            DType::I64 => self.const_i64_like(vec![1_i64; n], shape),
6818            other => {
6819                Err(fuel_ir::Error::Msg(format!("ones_like: unsupported dtype {other:?}",)).bt())
6820            }
6821        }
6822    }
6823
6824    /// New tensor with the same shape, dtype, and graph as `self`, filled
6825    /// with zeros. Returns Err for unsupported dtypes (anything outside
6826    /// F32/F64/BF16/F16/U32/I64) — matches eager `Tensor::zeros_like` parity.
6827    pub fn zeros_like(&self) -> std::result::Result<Self, fuel_ir::Error> {
6828        let n = self.elem_count();
6829        let shape = self.shape();
6830        match self.dtype() {
6831            DType::F32 => self.const_f32_like(vec![0.0_f32; n], shape),
6832            DType::F64 => self.const_f64_like(vec![0.0_f64; n], shape),
6833            DType::BF16 => self.const_bf16_like(vec![half::bf16::ZERO; n], shape),
6834            DType::F16 => self.const_f16_like(vec![half::f16::ZERO; n], shape),
6835            DType::U32 => self.const_u32_like(vec![0_u32; n], shape),
6836            DType::I64 => self.const_i64_like(vec![0_i64; n], shape),
6837            other => {
6838                Err(fuel_ir::Error::Msg(format!("zeros_like: unsupported dtype {other:?}",)).bt())
6839            }
6840        }
6841    }
6842
6843    /// New tensor with `shape`/`dtype`/`device`, every element set to `1`.
6844    /// Static factory equivalent of eager's `Tensor::ones`. Returns Err for
6845    /// dtypes outside F32/F64/BF16/F16/U32.
6846    pub fn ones(
6847        shape: impl Into<Shape>,
6848        dtype: DType,
6849        device: &Device,
6850    ) -> std::result::Result<Self, fuel_ir::Error> {
6851        let shape = shape.into();
6852        let n = shape.elem_count();
6853        match dtype {
6854            DType::F32 => Self::from_f32(vec![1.0_f32; n], shape, device),
6855            DType::F64 => Self::from_f64(vec![1.0_f64; n], shape, device),
6856            DType::BF16 => Self::from_bf16(vec![half::bf16::ONE; n], shape, device),
6857            DType::F16 => Self::from_f16(vec![half::f16::ONE; n], shape, device),
6858            DType::U32 => Self::from_u32(vec![1_u32; n], shape, device),
6859            other => Err(fuel_ir::Error::Msg(format!("ones: unsupported dtype {other:?}",)).bt()),
6860        }
6861    }
6862
6863    /// New tensor with `shape`/`dtype`/`device`, every element set to `0`.
6864    /// Static factory equivalent of eager's `Tensor::zeros`. Returns Err for
6865    /// dtypes outside F32/F64/BF16/F16/U32.
6866    ///
6867    /// **Mints a NEW graph** — it delegates to the `from_*` constructors, so
6868    /// the tensor it returns cannot be combined with one built elsewhere. To
6869    /// add a zero tensor to an existing graph, use
6870    /// [`zeros_like`](Self::zeros_like) or a `const_*_like` builder. See
6871    /// [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
6872    pub fn zeros(
6873        shape: impl Into<Shape>,
6874        dtype: DType,
6875        device: &Device,
6876    ) -> std::result::Result<Self, fuel_ir::Error> {
6877        let shape = shape.into();
6878        let n = shape.elem_count();
6879        match dtype {
6880            DType::F32 => Self::from_f32(vec![0.0_f32; n], shape, device),
6881            DType::F64 => Self::from_f64(vec![0.0_f64; n], shape, device),
6882            DType::BF16 => Self::from_bf16(vec![half::bf16::ZERO; n], shape, device),
6883            DType::F16 => Self::from_f16(vec![half::f16::ZERO; n], shape, device),
6884            DType::U32 => Self::from_u32(vec![0_u32; n], shape, device),
6885            other => Err(fuel_ir::Error::Msg(format!("zeros: unsupported dtype {other:?}",)).bt()),
6886        }
6887    }
6888
6889    /// New tensor of `shape`/`device` filled with `value`. The scalar's
6890    /// dtype determines the tensor's dtype. Returns Err for scalar dtypes
6891    /// outside F32/F64/BF16/F16/U32.
6892    ///
6893    /// **Mints a NEW graph** — it delegates to the `from_*` constructors, so
6894    /// the tensor it returns cannot be combined with one built elsewhere. To
6895    /// add a filled tensor to an existing graph, use a `const_*_like` builder.
6896    /// See [graph affinity](Self#tensors-are-graph-affine--read-this-before-building-anything).
6897    pub fn full(
6898        shape: impl Into<Shape>,
6899        value: fuel_ir::Scalar,
6900        device: &Device,
6901    ) -> std::result::Result<Self, fuel_ir::Error> {
6902        let shape = shape.into();
6903        let n = shape.elem_count();
6904        match value {
6905            fuel_ir::Scalar::F32(v) => Self::from_f32(vec![v; n], shape, device),
6906            fuel_ir::Scalar::F64(v) => Self::from_f64(vec![v; n], shape, device),
6907            fuel_ir::Scalar::BF16(v) => Self::from_bf16(vec![v; n], shape, device),
6908            fuel_ir::Scalar::F16(v) => Self::from_f16(vec![v; n], shape, device),
6909            fuel_ir::Scalar::U32(v) => Self::from_u32(vec![v; n], shape, device),
6910            other => Err(fuel_ir::Error::Msg(format!(
6911                "full: unsupported scalar dtype {:?}",
6912                other.dtype(),
6913            ))
6914            .bt()),
6915        }
6916    }
6917
6918    /// Identity matrix `[n, n]` with the given dtype on the given device.
6919    /// Built host-side as a flat Vec; no graph-layer arange dependency.
6920    pub fn eye(n: usize, dtype: DType, device: &Device) -> Self {
6921        let mut data = vec![0.0_f32; n * n];
6922        for i in 0..n {
6923            data[i * n + i] = 1.0;
6924        }
6925        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
6926        // saying it CAN would be a false claim in the signature -- `eye` would
6927        // return a `Result` that is never `Err`, and every caller would write a
6928        // `?` for an error that does not exist.
6929        //
6930        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
6931        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
6932        // in this function; no caller supplies either, so they cannot disagree.
6933        let base = Self::from_f32(data, vec![n, n], device).expect(
6934            "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",
6935        );
6936        if dtype == DType::F32 {
6937            base
6938        } else {
6939            base.to_dtype(dtype).unwrap()
6940        }
6941    }
6942
6943    /// Split a `(B, N, num_heads * head_dim)` projection into the
6944    /// multi-head attention layout `(B, num_heads, N, head_dim)`.
6945    /// Equivalent to `reshape(B, N, num_heads, head_dim).permute([0, 2, 1, 3])`
6946    /// — promoted to a method to retire the per-port reimplementations
6947    /// of this same composite.
6948    pub fn split_heads(
6949        &self,
6950        num_heads: usize,
6951        head_dim: usize,
6952    ) -> std::result::Result<Self, fuel_ir::Error> {
6953        let dims = self.inner.shape().dims().to_vec();
6954        debug_assert_eq!(
6955            dims.len(),
6956            3,
6957            "split_heads: input must be rank 3 (B, N, embed), got {dims:?}"
6958        );
6959        debug_assert_eq!(
6960            dims[2],
6961            num_heads * head_dim,
6962            "split_heads: trailing dim ({}) != num_heads * head_dim ({} * {} = {})",
6963            dims[2],
6964            num_heads,
6965            head_dim,
6966            num_heads * head_dim
6967        );
6968        let b = dims[0];
6969        let n = dims[1];
6970        self.reshape(Shape::from_dims(&[b, n, num_heads, head_dim]))?
6971            .permute([0, 2, 1, 3_usize])
6972    }
6973
6974    /// Merge a `(B, num_heads, N, head_dim)` attention result back
6975    /// into the projection layout `(B, N, num_heads * head_dim)`.
6976    /// Inverse of [`Self::split_heads`].
6977    pub fn merge_heads(&self) -> std::result::Result<Self, fuel_ir::Error> {
6978        let dims = self.inner.shape().dims().to_vec();
6979        debug_assert_eq!(
6980            dims.len(),
6981            4,
6982            "merge_heads: input must be rank 4 (B, heads, N, head_dim), got {dims:?}"
6983        );
6984        let b = dims[0];
6985        let num_heads = dims[1];
6986        let n = dims[2];
6987        let head_dim = dims[3];
6988        self.permute([0, 2, 1, 3_usize])?
6989            .reshape(Shape::from_dims(&[b, n, num_heads * head_dim]))
6990    }
6991
6992    /// Add a length-`bias.len()` bias vector to the trailing dim
6993    /// of `self`, broadcasting across all leading dims. The bias
6994    /// is materialized fresh on `self`'s graph from the supplied
6995    /// `Arc<[f32]>`.
6996    ///
6997    /// Common pattern after `WeightStorage::apply_linear` when the
6998    /// linear has a bias term but the activation tensor is on a
6999    /// different anchor than where the bias was originally
7000    /// allocated. Several lazy ports inlined this same 3-line
7001    /// helper as `bias_add` — promoted here to a method.
7002    pub fn add_trailing_bias(
7003        &self,
7004        bias: std::sync::Arc<[f32]>,
7005    ) -> std::result::Result<Self, fuel_ir::Error> {
7006        let n = bias.len();
7007        // Build the bias const in `self`'s dtype rather than hardcoding
7008        // f32: under BF16-throughout decode (Phase D increment A) the
7009        // activation stream is BF16 and `broadcast_add` asserts dtype
7010        // equality, so an f32 bias would panic. No-op for f32 activations
7011        // (every other caller today).
7012        let bias_t = self.const_like_dtype(&bias, Shape::from_dims(&[n]), self.dtype())?;
7013        self.broadcast_add(&bias_t)
7014    }
7015
7016    /// Embed `tokens` against an `[vocab_size, hidden]` embedding
7017    /// table held as `Arc<[f32]>`. Returns `(1, seq, hidden)`
7018    /// rank-3 hidden states ready to feed into a decoder backbone.
7019    ///
7020    /// Bootstraps a fresh graph anchored on a new const-f32 node.
7021    /// For composition with an already-built tensor (e.g.,
7022    /// multimodal models that need text embeddings on the audio
7023    /// graph), use [`Self::embed_tokens_anchored`] instead.
7024    ///
7025    /// Retires the 7-line `from_f32 + const_u32_like + index_select
7026    /// + reshape` ceremony every LLM port carried.
7027    pub fn embed_tokens(
7028        embed_table: std::sync::Arc<[f32]>,
7029        vocab_size: usize,
7030        hidden: usize,
7031        tokens: &[u32],
7032        device: &crate::Device,
7033    ) -> std::result::Result<Self, fuel_ir::Error> {
7034        let seq = tokens.len();
7035        if seq == 0 {
7036            return Err(fuel_ir::Error::Msg("embed_tokens: tokens must be non-empty".into()).bt());
7037        }
7038        let embed = Self::from_f32(embed_table, Shape::from_dims(&[vocab_size, hidden]), device)?;
7039        let token_ids = embed.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7040        embed
7041            .index_select(0_usize, &token_ids)?
7042            .reshape(Shape::from_dims(&[1, seq, hidden]))
7043    }
7044
7045    /// Variant of [`Self::embed_tokens`] that anchors the embedding
7046    /// table and token-id constants on the receiver's graph, so the
7047    /// resulting embeddings can compose with `self` and other
7048    /// tensors already on that graph. Used by multimodal models
7049    /// (vision + text, audio + text) where the text embeddings must
7050    /// live on the modality encoder's graph for cross-substitution
7051    /// to work.
7052    pub fn embed_tokens_anchored(
7053        &self,
7054        embed_table: std::sync::Arc<[f32]>,
7055        vocab_size: usize,
7056        hidden: usize,
7057        tokens: &[u32],
7058    ) -> std::result::Result<Self, fuel_ir::Error> {
7059        let seq = tokens.len();
7060        if seq == 0 {
7061            return Err(fuel_ir::Error::Msg(
7062                "embed_tokens_anchored: tokens must be non-empty".into(),
7063            )
7064            .bt());
7065        }
7066        let embed = self.const_f32_like(embed_table, Shape::from_dims(&[vocab_size, hidden]))?;
7067        let token_ids = self.const_u32_like(tokens.to_vec(), Shape::from_dims(&[seq]))?;
7068        embed
7069            .index_select(0_usize, &token_ids)?
7070            .reshape(Shape::from_dims(&[1, seq, hidden]))
7071    }
7072
7073    /// Build the standard (non-interleaved) RoPE cos/sin tables for
7074    /// `seq` positions starting at `start_pos`, anchored on the
7075    /// receiver's graph. Returns `(cos, sin)`, each with shape
7076    /// `[seq, head_dim]`.
7077    ///
7078    /// Delegates the actual `(theta, position) → (cos, sin)` host
7079    /// computation to [`fuel_graph::build_rope_tables`] (the canonical
7080    /// reference); only the const-tensor materialization is folded
7081    /// into one method to retire the per-port 4-line ceremony every
7082    /// LLM port did before calling `rope_with_tables`.
7083    pub fn rope_tables_const(
7084        &self,
7085        theta: f64,
7086        start_pos: usize,
7087        seq: usize,
7088        head_dim: usize,
7089    ) -> (Self, Self) {
7090        let (cos_data, sin_data) = fuel_graph::build_rope_tables(theta, start_pos, seq, head_dim);
7091        let rope_shape = Shape::from_dims(&[seq, head_dim]);
7092        // ⚠️ GAP-003 category 2: the proof EXISTS but is NOT LOCAL --
7093        // `build_rope_tables` owns the length and its `-> (Vec<f32>, Vec<f32>)`
7094        // signature does not carry it. The message names WHERE the guarantee
7095        // lives rather than claiming one. `-> (Self, Self)` has no error channel;
7096        // giving it one is a signature change, a different obligation. See #157.
7097        let rope_cos = self
7098            .const_f32_like(cos_data, rope_shape.clone())
7099            .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7100        let rope_sin = self
7101            .const_f32_like(sin_data, rope_shape)
7102            .expect("rope tables: build_rope_tables must return seq*head_dim elements");
7103        (rope_cos, rope_sin)
7104    }
7105
7106    /// Constant-position RoPE cos/sin tables `[rows, head_dim]` where EVERY row
7107    /// is the *same* θ·`delta` rotation — the rung-2 delta-rotation tables. A
7108    /// cached prefix's keys, already rotated for their original positions, are
7109    /// shifted to `+delta` by applying this uniform rotation (RoPE composes
7110    /// additively per pair: `R(delta)·R(p) = R(p+delta)`).
7111    ///
7112    /// This is the position-`delta` row repeated `rows` times — NOT
7113    /// `rope_tables_const(theta, delta, rows, head_dim)`, which would give the
7114    /// *incrementing* progression `delta, delta+1, …` (the standard RoPE sweep).
7115    /// Routed through the canonical `fuel_graph::build_rope_tables` so it inherits
7116    /// the model's inv-freq/scaling exactly.
7117    pub fn rope_delta_tables_const(
7118        &self,
7119        theta: f64,
7120        delta: usize,
7121        rows: usize,
7122        head_dim: usize,
7123    ) -> (Self, Self) {
7124        let (c1, s1) = fuel_graph::build_rope_tables(theta, delta, 1, head_dim);
7125        let mut cos = Vec::with_capacity(rows * head_dim);
7126        let mut sin = Vec::with_capacity(rows * head_dim);
7127        for _ in 0..rows {
7128            cos.extend_from_slice(&c1);
7129            sin.extend_from_slice(&s1);
7130        }
7131        let shape = Shape::from_dims(&[rows, head_dim]);
7132        // ⚠️ GAP-003, HALF LOCAL. LOCAL: the loop appends `c1` exactly `rows`
7133        // times against a `[rows, head_dim]` shape. NOT LOCAL: that `c1` has
7134        // `head_dim` elements comes from `build_rope_tables`. Stated as both.
7135        (
7136            self.const_f32_like(cos, shape.clone()).expect(
7137                "rope tables: rows appends of c1 (local); c1 has head_dim elements (not local)",
7138            ),
7139            self.const_f32_like(sin, shape).expect(
7140                "rope tables: rows appends of s1 (local); s1 has head_dim elements (not local)",
7141            ),
7142        )
7143    }
7144
7145    /// Uniformly delta-rotate one cached (post-RoPE) K block by θ·`delta`,
7146    /// returning the shifted block in the SAME pool layout. Reuses the model's
7147    /// exact `rope_with_tables_decomposed` (rotate-half) rather than a hand-rolled
7148    /// rotation, so it inherits the model's RoPE convention + scaling and stays
7149    /// byte-exact with a direct rope-at-shifted-position. A single uniform
7150    /// rotation is correct for the whole block even though it holds `block_size`
7151    /// distinct original positions — the delta is the same for every position.
7152    ///
7153    /// `k_block` is the pool block layout, row-major `[block_size, n_kv_heads,
7154    /// head_dim]` (positions-major, as `DeviceKvPool::read_block` returns). RoPE
7155    /// wants `(position, dim)` as the last two axes, so heads are brought forward
7156    /// to the `project_qkv_roped` layout `[1, n_kv_heads, block_size, head_dim]`,
7157    /// rotated, and returned to `[block_size, n_kv_heads, head_dim]`. The rung-2
7158    /// numeric core, realized on `dev`.
7159    pub fn rope_delta_rotate_block_f32(
7160        dev: &crate::Device,
7161        k_block: &[f32],
7162        theta: f64,
7163        delta: usize,
7164        block_size: usize,
7165        n_kv_heads: usize,
7166        head_dim: usize,
7167    ) -> Vec<f32> {
7168        let pool_shape = Shape::from_dims(&[block_size, n_kv_heads, head_dim]);
7169        // ⚠️ GAP-003: NOT a carve-out and NOT a propagation, and the reason is
7170        // this function's SIGNATURE rather than anything about the operands.
7171        // `k_block` and the pool dims are BOTH caller-supplied, so there is no
7172        // local proof and the message below deliberately does not claim one.
7173        // `-> Vec<f32>` has no error channel, and the two `.expect`s already on
7174        // this same expression (permute, reshape) are the same pre-existing
7175        // condition -- converting one of three would be less honest, not more.
7176        //
7177        // The fix is this function returning `Result`, which is a DIFFERENT
7178        // obligation from the constructor-family ruling and is not in its scope.
7179        let k = Tensor::from_f32(k_block.to_vec(), pool_shape, dev).expect(
7180            "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)",
7181        );
7182        let k4 = k
7183            .permute([1, 0, 2])
7184            .expect("rope_delta_rotate_block_f32: permute [bs,Hkv,D]->[Hkv,bs,D]")
7185            .reshape(Shape::from_dims(&[1, n_kv_heads, block_size, head_dim]))
7186            .expect("rope_delta_rotate_block_f32: reshape to [1,Hkv,bs,D]");
7187        let (cos, sin) = k4.rope_delta_tables_const(theta, delta, block_size, head_dim);
7188        k4.rope_with_tables_decomposed(&cos, &sin)
7189            .expect("rope_delta_rotate_block_f32: rope_with_tables_decomposed")
7190            .reshape(Shape::from_dims(&[n_kv_heads, block_size, head_dim]))
7191            .expect("rope_delta_rotate_block_f32: reshape back to [Hkv,bs,D]")
7192            .permute([1, 0, 2])
7193            .expect("rope_delta_rotate_block_f32: permute [Hkv,bs,D]->[bs,Hkv,D]")
7194            .realize_f32()
7195    }
7196
7197    /// `[B, 1, 1, head_dim]` RoPE cos/sin tables, row `b` at absolute position
7198    /// `positions[b]` — the per-row generalization of [`Self::rope_tables_const`]
7199    /// (which carries one shared position). Built as a **single** const from `B`
7200    /// calls to `fuel_graph::build_rope_tables` (the canonical `(theta, position)
7201    /// → (cos, sin)` math), concatenated host-side — no `Op::Concat` chain. At
7202    /// `B == 1` the emitted data is bit-identical to `rope_tables_const`'s
7203    /// `[1, head_dim]` const (same builder call), so
7204    /// [`Self::rope_batched`] reduces to the single-position decomposed RoPE.
7205    ///
7206    /// This is the mechanism that lets a decode batch carry sessions at
7207    /// *different* positions (continuous batching) rather than requiring
7208    /// equal-length rows. `anchor` (`self`) supplies the graph.
7209    pub fn rope_tables_const_batched(
7210        &self,
7211        theta: f64,
7212        positions: &[usize],
7213        head_dim: usize,
7214    ) -> (Self, Self) {
7215        let b = positions.len();
7216        let mut cos_data = Vec::with_capacity(b * head_dim);
7217        let mut sin_data = Vec::with_capacity(b * head_dim);
7218        for &pos in positions {
7219            let (c, s) = fuel_graph::build_rope_tables(theta, pos, 1, head_dim);
7220            cos_data.extend_from_slice(&c);
7221            sin_data.extend_from_slice(&s);
7222        }
7223        let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7224        // ⚠️ GAP-003, and the proof is HALF local -- worth stating as such rather
7225        // than rounding to either category. LOCAL: `b` IS `positions.len()` (six
7226        // lines up) and the loop appends once per position, so the buffer has
7227        // `positions.len() * head_dim` elements against a `[b, 1, 1, head_dim]`
7228        // shape. NOT LOCAL: that each `build_rope_tables(_, _, 1, head_dim)` call
7229        // yields exactly `head_dim` elements lives in that function.
7230        let rope_cos = self
7231            .const_f32_like(cos_data, shape.clone())
7232            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7233        let rope_sin = self
7234            .const_f32_like(sin_data, shape)
7235            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables must yield head_dim per position (not local)");
7236        (rope_cos, rope_sin)
7237    }
7238
7239    /// [`Self::rope_tables_const`] with caller-supplied inverse frequencies
7240    /// (`inv_freq.len() == head_dim / 2`) in place of the ones derived from
7241    /// `theta` -- the scaled-RoPE (llama3 / yarn / linear) entry. Delegates the
7242    /// host math to [`fuel_graph::build_rope_tables_with_inv_freq`].
7243    pub fn rope_tables_const_with_inv_freq(
7244        &self,
7245        inv_freq: &[f64],
7246        start_pos: usize,
7247        seq: usize,
7248        head_dim: usize,
7249    ) -> (Self, Self) {
7250        let (cos_data, sin_data) =
7251            fuel_graph::build_rope_tables_with_inv_freq(inv_freq, start_pos, seq, head_dim);
7252        let rope_shape = Shape::from_dims(&[seq, head_dim]);
7253        // GAP-003: same non-local proof as `rope_tables_const` -- the length
7254        // lives in `build_rope_tables_with_inv_freq`, which has no error channel.
7255        let rope_cos = self.const_f32_like(cos_data, rope_shape.clone()).expect(
7256            "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7257        );
7258        let rope_sin = self.const_f32_like(sin_data, rope_shape).expect(
7259            "rope tables: build_rope_tables_with_inv_freq must return seq*head_dim elements",
7260        );
7261        (rope_cos, rope_sin)
7262    }
7263
7264    /// [`Self::rope_tables_const_batched`] with caller-supplied inverse
7265    /// frequencies (`inv_freq.len() == head_dim / 2`).
7266    pub fn rope_tables_const_batched_with_inv_freq(
7267        &self,
7268        inv_freq: &[f64],
7269        positions: &[usize],
7270        head_dim: usize,
7271    ) -> (Self, Self) {
7272        let b = positions.len();
7273        let mut cos_data = Vec::with_capacity(b * head_dim);
7274        let mut sin_data = Vec::with_capacity(b * head_dim);
7275        for &pos in positions {
7276            let (c, s) = fuel_graph::build_rope_tables_with_inv_freq(inv_freq, pos, 1, head_dim);
7277            cos_data.extend_from_slice(&c);
7278            sin_data.extend_from_slice(&s);
7279        }
7280        let shape = Shape::from_dims(&[b, 1, 1, head_dim]);
7281        // GAP-003: `b` IS `positions.len()` (local); the per-position length
7282        // lives in `build_rope_tables_with_inv_freq` (not local).
7283        let rope_cos = self
7284            .const_f32_like(cos_data, shape.clone())
7285            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7286        let rope_sin = self
7287            .const_f32_like(sin_data, shape)
7288            .expect("batched rope tables: b IS positions.len() (local); build_rope_tables_with_inv_freq must yield head_dim per position (not local)");
7289        (rope_cos, rope_sin)
7290    }
7291
7292    /// Rotary position embedding with **per-batch-row** tables.
7293    ///
7294    /// `self` is `[B, H, 1, D]`; `cos`/`sin` are `[B, 1, 1, D]` (row `b` holds the
7295    /// table for sequence `b`'s own position — see [`Self::rope_tables_const_batched`]).
7296    /// Broadcasting the `[B, 1, 1, D]` tables over the head axis is what lets one
7297    /// table row serve all of that sequence's heads.
7298    ///
7299    /// This is `fuel_graph::NodeHandle::rope_with_tables_decomposed`'s body
7300    /// (`fuel-graph/src/lib.rs` ~6931-6954) with the table shape generalized from
7301    /// one shared position to one-per-row — **same ops, same order, same
7302    /// associativity** (`y = x·cos + concat(-x[…,D/2..], x[…,..D/2])·sin`), so at
7303    /// `B == 1` it is bit-identical to `rope_with_tables_decomposed`. Built on the
7304    /// public `Tensor` surface (not a new `fuel-graph` op) deliberately: the
7305    /// single-position [`Self::rope_with_tables_decomposed`] hard-requires
7306    /// `cos.dims() == [seq, d]`, so it cannot carry per-row tables, and rebuilding
7307    /// the lowering here avoids re-entering the `fuel-graph` rope op.
7308    ///
7309    /// (Adopted from the Lightbulb consumer's verified `rope_batched`; the
7310    /// mechanism belongs in Fuel, not the consumer.)
7311    pub fn rope_batched(
7312        &self,
7313        cos: &Self,
7314        sin: &Self,
7315    ) -> std::result::Result<Self, fuel_ir::Error> {
7316        let dims: Vec<usize> = self.inner.shape().dims().to_vec();
7317        let rank = dims.len();
7318        if rank < 2 {
7319            return Err(fuel_ir::Error::Msg(format!(
7320                "rope_batched: expected rank >= 2, got {dims:?}",
7321            ))
7322            .bt());
7323        }
7324        let d = dims[rank - 1];
7325        if !d.is_multiple_of(2) {
7326            return Err(
7327                fuel_ir::Error::Msg(format!("rope_batched: head_dim {d} must be even",)).bt(),
7328            );
7329        }
7330        let half = d / 2;
7331        let target = Shape::from_dims(&dims);
7332
7333        let cos_b = cos.broadcast_to(target.clone())?;
7334        let sin_b = sin.broadcast_to(target)?;
7335
7336        let first = self.slice(rank - 1, 0, half)?;
7337        let second = self.slice(rank - 1, half, half)?;
7338        let rotated = second.neg().concat(&first, rank - 1)?;
7339
7340        let left = self.mul(&cos_b)?;
7341        let right = rotated.mul(&sin_b)?;
7342        left.add(&right)
7343    }
7344
7345    /// Apply RoPE to the first `rope_dim` entries of each head and
7346    /// pass the remaining `head_dim - rope_dim` features through
7347    /// unchanged. `head_dim` is derived from the receiver's last-dim
7348    /// size. When `rope_dim == head_dim` this reduces to
7349    /// [`Self::rope_with_tables`].
7350    ///
7351    /// Implements the partial-rotary convention used by StableLM,
7352    /// Phi, Persimmon, MixFormer, RecurrentGemma, and Gemma-4 text —
7353    /// all the ports that carried an identical 5-line `slice + rope +
7354    /// concat` helper before this method.
7355    pub fn rope_partial(
7356        &self,
7357        rope_cos: &Self,
7358        rope_sin: &Self,
7359        rope_dim: usize,
7360    ) -> std::result::Result<Self, fuel_ir::Error> {
7361        let dims = self.inner.shape();
7362        let dims = dims.dims();
7363        let head_dim = *dims.last().ok_or_else(|| {
7364            fuel_ir::Error::Msg("rope_partial: receiver must have at least one dimension".into())
7365                .bt()
7366        })?;
7367        if rope_dim == head_dim {
7368            return self.rope_with_tables(rope_cos, rope_sin);
7369        }
7370        if rope_dim > head_dim {
7371            return Err(fuel_ir::Error::Msg(format!(
7372                "rope_partial: rope_dim={rope_dim} exceeds head_dim={head_dim}",
7373            ))
7374            .bt());
7375        }
7376        let last = dims.len() - 1;
7377        let pass_dim = head_dim - rope_dim;
7378        let rot = self.slice(last, 0, rope_dim)?;
7379        let pass = self.slice(last, rope_dim, pass_dim)?;
7380        let rot_rotated = rot.rope_with_tables(rope_cos, rope_sin)?;
7381        rot_rotated.concat(&pass, last)
7382    }
7383
7384    /// `Option<Arc<[f32]>>` variant of [`Self::add_trailing_bias`]: if
7385    /// `bias.is_none()`, return `self` unchanged; else apply
7386    /// `add_trailing_bias`. Models the `linear_b` / `linear_no_bias`
7387    /// branch every per-port `optional_bias` / `opt_bias` helper does.
7388    pub fn add_optional_trailing_bias(
7389        &self,
7390        bias: Option<&std::sync::Arc<[f32]>>,
7391    ) -> std::result::Result<Self, fuel_ir::Error> {
7392        match bias {
7393            None => Ok(self.clone()),
7394            Some(b) => self.add_trailing_bias(std::sync::Arc::clone(b)),
7395        }
7396    }
7397
7398    /// Logit-softcap: `cap · tanh(self / cap)`. Used by the Gemma-2 /
7399    /// Gemma-3 attention-logit and final-logit softcap branches. The
7400    /// math is identical regardless of where the cap is applied;
7401    /// retired the two per-port `softcap` / `apply_softcap` helpers in
7402    /// favor of this method.
7403    pub fn softcap(&self, cap: f64) -> Self {
7404        self.mul_scalar(1.0 / cap).tanh().mul_scalar(cap)
7405    }
7406
7407    /// `Option<f64>` variant of [`Self::softcap`]: when `cap.is_none()`
7408    /// or `cap <= 0.0`, return `self` unchanged; else apply
7409    /// [`Self::softcap`]. Mirrors the optional-bias pattern.
7410    pub fn softcap_optional(&self, cap: Option<f64>) -> Self {
7411        match cap {
7412            Some(c) if c > 0.0 => self.softcap(c),
7413            _ => self.clone(),
7414        }
7415    }
7416
7417    /// Apply RMSNorm along the last dim with `(gain + offset) · x`.
7418    /// Equivalent to [`Self::rms_norm_affine`] after adding a scalar
7419    /// to every gain element — used by Gemma-family ports where
7420    /// the stored gain represents `gain - 1` and the runtime path
7421    /// must reconstruct `gain + 1`.
7422    ///
7423    /// Materializes the shifted gain on the receiver's graph; one
7424    /// allocation per call.
7425    pub fn rms_norm_affine_with_offset(
7426        &self,
7427        gain: &[f32],
7428        offset: f32,
7429        eps: f64,
7430    ) -> std::result::Result<Self, fuel_ir::Error> {
7431        let shifted: std::sync::Arc<[f32]> =
7432            std::sync::Arc::from(gain.iter().map(|g| *g + offset).collect::<Vec<_>>());
7433        self.rms_norm_affine(shifted, eps)
7434    }
7435
7436    /// Apply RMSNorm along the last dim with an affine `gain · x`
7437    /// post-step (no bias — RMSNorm has no β term). `gain` is a
7438    /// length-`gain.len()` vector materialized fresh on the
7439    /// receiver's graph and broadcast across all leading dims.
7440    pub fn rms_norm_affine(
7441        &self,
7442        gain: std::sync::Arc<[f32]>,
7443        eps: f64,
7444    ) -> std::result::Result<Self, fuel_ir::Error> {
7445        let hidden = gain.len();
7446        let normed = self.rms_norm_last_dim(eps)?;
7447        let gain_t = self.const_f32_like(gain, Shape::from_dims(&[hidden]))?;
7448        normed.broadcast_mul(&gain_t)
7449    }
7450
7451    /// Global average pool over the spatial dims of a rank-4
7452    /// `(B, C, H, W)` tensor: reduces dims 2 and 3, returning
7453    /// `(B, C)`. For the keepdim variant (`(B, C, 1, 1)`, used by
7454    /// SE blocks), follow with `.reshape(Shape::from_dims(&[B, C, 1, 1]))`.
7455    ///
7456    /// Backs the classification heads of every conv vision port
7457    /// (ResNet, EfficientNet, ConvMixer, FastViT, MobileNetV4,
7458    /// MobileOne, RepVGG, ConvNeXt, EfficientViT, etc.) plus the
7459    /// pre-projection pool inside each squeeze-excite block.
7460    pub fn global_avg_pool_2d(&self) -> std::result::Result<Self, fuel_ir::Error> {
7461        let dims = self.inner.shape().dims().to_vec();
7462        debug_assert_eq!(
7463            dims.len(),
7464            4,
7465            "global_avg_pool_2d: input must be rank 4 (B, C, H, W), got {dims:?}"
7466        );
7467        // Reduce W first (dim 3), then H (dim 2 of the H-reduced (B, C, H) tensor).
7468        self.mean_dim(3_usize)?.mean_dim(2_usize)
7469    }
7470
7471    /// Apply a per-channel affine `gain · x + bias` to a rank-4
7472    /// `(B, C, H, W)` tensor. Both `gain` and `bias` are length-`C`
7473    /// vectors materialized fresh on the receiver's graph and
7474    /// broadcast across the spatial axes.
7475    ///
7476    /// Equivalent to fused-affine BatchNorm at inference time:
7477    /// the running mean / running var / eps are absorbed at load
7478    /// time into `gain = γ / sqrt(var + eps)` and
7479    /// `bias = β - μ · γ / sqrt(var + eps)`, so the runtime forward
7480    /// is just this multiply-add. Used by inference-only conv
7481    /// vision ports (ResNet, EfficientNet, FastViT, etc.).
7482    pub fn channel_affine_4d(
7483        &self,
7484        gain: std::sync::Arc<[f32]>,
7485        bias: std::sync::Arc<[f32]>,
7486    ) -> std::result::Result<Self, fuel_ir::Error> {
7487        let dims = self.inner.shape().dims().to_vec();
7488        debug_assert_eq!(
7489            dims.len(),
7490            4,
7491            "channel_affine_4d: input must be rank 4 (B, C, H, W), got {dims:?}"
7492        );
7493        let channels = dims[1];
7494        debug_assert_eq!(
7495            gain.len(),
7496            channels,
7497            "channel_affine_4d: gain len ({}) != C ({})",
7498            gain.len(),
7499            channels
7500        );
7501        debug_assert_eq!(
7502            bias.len(),
7503            channels,
7504            "channel_affine_4d: bias len ({}) != C ({})",
7505            bias.len(),
7506            channels
7507        );
7508        let w_t = self
7509            .const_f32_like(gain, Shape::from_dims(&[channels]))?
7510            .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7511        let b_t = self
7512            .const_f32_like(bias, Shape::from_dims(&[channels]))?
7513            .reshape(Shape::from_dims(&[1, channels, 1, 1]))?;
7514        self.broadcast_mul(&w_t)?.broadcast_add(&b_t)
7515    }
7516
7517    /// Build the strict additive causal mask `(seq_len, seq_len)`
7518    /// anchored on `anchor`'s graph: 0 on and below the diagonal,
7519    /// `f32::NEG_INFINITY` above it. Add to attention scores before
7520    /// softmax to enforce strict causality (position `i` cannot
7521    /// attend to position `j > i`).
7522    ///
7523    /// Equivalent to the `(T, T)` mask several ports build inline
7524    /// — promoted here so call sites stop drifting.
7525    pub fn additive_causal_mask_like(anchor: &Tensor, seq_len: usize) -> Self {
7526        let mut data = vec![0.0_f32; seq_len * seq_len];
7527        for i in 0..seq_len {
7528            for j in (i + 1)..seq_len {
7529                data[i * seq_len + j] = f32::NEG_INFINITY;
7530            }
7531        }
7532        // GAP-003 carve-out, PROOF LOCAL: `data` is `vec![_; seq_len * seq_len]`
7533        // six lines up and the loop only writes IN PLACE -- it cannot change the
7534        // length -- against a `[seq_len, seq_len]` shape. Both from `seq_len`.
7535        anchor
7536            .const_f32_like(
7537                std::sync::Arc::from(data),
7538                Shape::from_dims(&[seq_len, seq_len]),
7539            )
7540            .expect(
7541                "additive_causal_mask_like: vec![_; seq_len*seq_len] against [seq_len, seq_len]",
7542            )
7543    }
7544
7545    /// Lower-triangular ones matrix `[n, n]`. `tril2(n).to_dtype(dtype)` is
7546    /// the causal-attention-mask building block.
7547    pub fn tril2(n: usize, dtype: DType, device: &Device) -> Self {
7548        let mut data = vec![0.0_f32; n * n];
7549        for i in 0..n {
7550            for j in 0..=i {
7551                data[i * n + j] = 1.0;
7552            }
7553        }
7554        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
7555        // saying it CAN would be a false claim in the signature -- `tril2` would
7556        // return a `Result` that is never `Err`, and every caller would write a
7557        // `?` for an error that does not exist.
7558        //
7559        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
7560        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
7561        // in this function; no caller supplies either, so they cannot disagree.
7562        let base = Self::from_f32(data, vec![n, n], device).expect(
7563            "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",
7564        );
7565        if dtype == DType::F32 {
7566            base
7567        } else {
7568            base.to_dtype(dtype).unwrap()
7569        }
7570    }
7571
7572    /// Upper-triangular ones matrix `[n, n]`.
7573    pub fn triu2(n: usize, dtype: DType, device: &Device) -> Self {
7574        let mut data = vec![0.0_f32; n * n];
7575        for i in 0..n {
7576            for j in i..n {
7577                data[i * n + j] = 1.0;
7578            }
7579        }
7580        // GAP-003 carve-out: `.expect` and NOT `?`, because this cannot fail and
7581        // saying it CAN would be a false claim in the signature -- `triu2` would
7582        // return a `Result` that is never `Err`, and every caller would write a
7583        // `?` for an error that does not exist.
7584        //
7585        // THE PROOF IS LOCAL, two lines up: `data` is `vec![_; n * n]`, and the
7586        // shape `[n, n]` has `elem_count() == n * n`. Both are computed from `n`
7587        // in this function; no caller supplies either, so they cannot disagree.
7588        let base = Self::from_f32(data, vec![n, n], device).expect(
7589            "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",
7590        );
7591        if dtype == DType::F32 {
7592            base
7593        } else {
7594            base.to_dtype(dtype).unwrap()
7595        }
7596    }
7597
7598    // ---- additional deferred-Phase-A items: indexing / multi-dim / RNG ----
7599
7600    /// Eager-API alias of [`Self::slice`] (PyTorch / Candle naming).
7601    /// `narrow(dim, start, len)` is `slice(dim, start, len)` —
7602    /// produces a view of `[start, start+len)` along `dim`. Bad input
7603    /// surfaces as a typed error at build time. Accepts any [`Dim`].
7604    pub fn narrow<D: Dim>(
7605        &self,
7606        dim: D,
7607        start: usize,
7608        len: usize,
7609    ) -> std::result::Result<Self, fuel_ir::Error> {
7610        self.slice(dim, start, len)
7611    }
7612
7613    /// Split into `chunks` views along `dim`. The split distributes the
7614    /// `chunk_size = ceil(dim_size / chunks)` extra slot to the leading
7615    /// chunks so every chunk's size differs by at most 1. If `dim_size
7616    /// < chunks`, returns `dim_size` singleton chunks instead of
7617    /// `chunks` chunks (matches eager / PyTorch). Accepts any [`Dim`].
7618    pub fn chunk<D: Dim>(
7619        &self,
7620        chunks: usize,
7621        dim: D,
7622    ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
7623        let shape = self.shape();
7624        let dim = dim.to_index(&shape, "chunk")?;
7625        if chunks == 0 {
7626            return Err(fuel_ir::Error::Msg("chunk: chunks must be > 0".into()).bt());
7627        }
7628        let dims = shape.dims();
7629        let size = dims[dim];
7630        if size < chunks {
7631            return Ok((0..size).map(|i| self.slice(dim, i, 1).unwrap()).collect());
7632        }
7633        let base = size / chunks;
7634        let extra = size % chunks;
7635        let mut out = Vec::with_capacity(chunks);
7636        let mut start = 0;
7637        for i in 0..chunks {
7638            let len = if i < extra { base + 1 } else { base };
7639            out.push(self.slice(dim, start, len).unwrap());
7640            start += len;
7641        }
7642        Ok(out)
7643    }
7644
7645    /// Sub-tensor at index `i` along dim 0. Equivalent to
7646    /// `self.slice(0, i, 1).unwrap().squeeze(0)`. Matches eager's `crate::Tensor::get`.
7647    pub fn get(&self, i: usize) -> std::result::Result<Self, fuel_ir::Error> {
7648        let dims = self.shape().dims().to_vec();
7649        if dims.is_empty() {
7650            return Ok(self.clone());
7651        }
7652        self.slice(0, i, 1).unwrap().squeeze(0)
7653    }
7654
7655    /// Sub-tensor at index along an arbitrary dim. Equivalent to
7656    /// `self.slice(dim, index, 1).unwrap().squeeze(dim)`. Matches eager's
7657    /// `crate::Tensor::get_on_dim`. Accepts any [`Dim`].
7658    pub fn get_on_dim<D: Dim>(
7659        &self,
7660        dim: D,
7661        index: usize,
7662    ) -> std::result::Result<Self, fuel_ir::Error> {
7663        let shape = self.shape();
7664        let dim = dim.to_index(&shape, "get_on_dim")?;
7665        self.slice(dim, index, 1).unwrap().squeeze(dim)
7666    }
7667
7668    /// Multi-dim sum: reduce over every dim in `dims`, squeezing each.
7669    /// Reduces from the highest dim down so the lower dim indices stay
7670    /// valid throughout the reduction.
7671    pub fn sum_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7672        let shape = self.shape();
7673        let mut sorted = dims.to_indexes(&shape, "sum_dims")?;
7674        sorted.sort_by(|a, b| b.cmp(a));
7675        sorted.dedup();
7676        let mut acc = self.clone();
7677        for d in sorted {
7678            acc = acc.sum_dim(d)?;
7679        }
7680        Ok(acc)
7681    }
7682
7683    /// Multi-dim mean: reduce over every dim in `dims`, squeezing each.
7684    /// Reduces from the highest dim down. Accepts any [`Dims`].
7685    pub fn mean_dims<D: Dims>(&self, dims: D) -> std::result::Result<Self, fuel_ir::Error> {
7686        let shape = self.shape();
7687        let mut sorted = dims.to_indexes(&shape, "mean_dims")?;
7688        sorted.sort_by(|a, b| b.cmp(a));
7689        sorted.dedup();
7690        let mut acc = self.clone();
7691        for d in sorted {
7692            acc = acc.mean_dim(d)?;
7693        }
7694        Ok(acc)
7695    }
7696
7697    /// Multi-dim sum with keepdim: every named dim becomes size 1
7698    /// instead of being squeezed out. Reduce-order-invariant (every
7699    /// keepdim preserves indices). Returns Result because of cascade
7700    /// from [`Self::sum_keepdim`].
7701    pub fn sum_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7702        let mut sorted: Vec<usize> = dims.to_vec();
7703        sorted.sort();
7704        sorted.dedup();
7705        let mut acc = self.clone();
7706        for d in sorted {
7707            acc = acc.sum_keepdim(d)?;
7708        }
7709        Ok(acc)
7710    }
7711
7712    /// Multi-dim mean with keepdim.
7713    pub fn mean_dims_keepdim(&self, dims: &[usize]) -> std::result::Result<Self, fuel_ir::Error> {
7714        let mut sorted: Vec<usize> = dims.to_vec();
7715        sorted.sort();
7716        sorted.dedup();
7717        let mut acc = self.clone();
7718        for d in sorted {
7719            acc = acc.mean_keepdim(d)?;
7720        }
7721        Ok(acc)
7722    }
7723
7724    /// Uniform random tensor in `[lo, up)` with shape/dtype/device matching `self`.
7725    /// Backed by [`rand::rng`]. Returns Err for unsupported dtypes.
7726    pub fn rand_like(&self, lo: f64, up: f64) -> std::result::Result<Self, fuel_ir::Error> {
7727        Self::rand(self.shape(), lo, up, self.dtype(), &Device::cpu())
7728    }
7729
7730    /// Normal random tensor with shape/dtype/device matching `self`.
7731    /// Returns Err for unsupported dtypes or invalid stdev.
7732    pub fn randn_like(&self, mean: f64, stdev: f64) -> std::result::Result<Self, fuel_ir::Error> {
7733        Self::randn(self.shape(), mean, stdev, self.dtype(), &Device::cpu())
7734    }
7735
7736    /// Uniform random tensor in `[lo, up)`. Static factory.
7737    /// Supported dtypes: F32, F64, BF16, F16. F32 is the typical
7738    /// initialization target. Returns Err for any other dtype.
7739    pub fn rand(
7740        shape: impl Into<Shape>,
7741        lo: f64,
7742        up: f64,
7743        dtype: DType,
7744        device: &Device,
7745    ) -> std::result::Result<Self, fuel_ir::Error> {
7746        use rand::RngExt;
7747        let shape = shape.into();
7748        let n = shape.elem_count();
7749        let mut rng = rand::rng();
7750        match dtype {
7751            DType::F32 => {
7752                let data: Vec<f32> = (0..n).map(|_| rng.random_range(lo..up) as f32).collect();
7753                Self::from_f32(data, shape, device)
7754            }
7755            DType::F64 => {
7756                let data: Vec<f64> = (0..n).map(|_| rng.random_range(lo..up)).collect();
7757                Self::from_f64(data, shape, device)
7758            }
7759            DType::BF16 => {
7760                let data: Vec<half::bf16> = (0..n)
7761                    .map(|_| fuel_ir::round::bf16_from_f64(rng.random_range(lo..up)))
7762                    .collect();
7763                Self::from_bf16(data, shape, device)
7764            }
7765            DType::F16 => {
7766                let data: Vec<half::f16> = (0..n)
7767                    .map(|_| fuel_ir::round::f16_from_f64(rng.random_range(lo..up)))
7768                    .collect();
7769                Self::from_f16(data, shape, device)
7770            }
7771            other => {
7772                Err(fuel_ir::Error::Msg(format!("Tensor::rand: unsupported dtype {other:?}",)).bt())
7773            }
7774        }
7775    }
7776
7777    /// Normal random tensor with given `mean` and `stdev`. Static factory.
7778    /// Supported dtypes: F32, F64, BF16, F16. Returns Err on any other
7779    /// dtype, or if `stdev` is not finite / not positive.
7780    pub fn randn(
7781        shape: impl Into<Shape>,
7782        mean: f64,
7783        stdev: f64,
7784        dtype: DType,
7785        device: &Device,
7786    ) -> std::result::Result<Self, fuel_ir::Error> {
7787        use rand_distr::{Distribution, Normal};
7788        let shape = shape.into();
7789        let n = shape.elem_count();
7790        let normal = Normal::new(mean, stdev).map_err(|e| {
7791            fuel_ir::Error::Msg(format!("Tensor::randn: invalid stdev={stdev}: {e}",)).bt()
7792        })?;
7793        let mut rng = rand::rng();
7794        match dtype {
7795            DType::F32 => {
7796                let data: Vec<f32> = (0..n).map(|_| normal.sample(&mut rng) as f32).collect();
7797                Self::from_f32(data, shape, device)
7798            }
7799            DType::F64 => {
7800                let data: Vec<f64> = (0..n).map(|_| normal.sample(&mut rng)).collect();
7801                Self::from_f64(data, shape, device)
7802            }
7803            DType::BF16 => {
7804                let data: Vec<half::bf16> = (0..n)
7805                    .map(|_| fuel_ir::round::bf16_from_f64(normal.sample(&mut rng)))
7806                    .collect();
7807                Self::from_bf16(data, shape, device)
7808            }
7809            DType::F16 => {
7810                let data: Vec<half::f16> = (0..n)
7811                    .map(|_| fuel_ir::round::f16_from_f64(normal.sample(&mut rng)))
7812                    .collect();
7813                Self::from_f16(data, shape, device)
7814            }
7815            other => Err(fuel_ir::Error::Msg(format!(
7816                "Tensor::randn: unsupported dtype {other:?}",
7817            ))
7818            .bt()),
7819        }
7820    }
7821
7822    /// `arange(start, end, device)`: a rank-1 tensor of `[start, end)` in
7823    /// step 1, dtype F32. Matches NumPy / PyTorch convention.
7824    pub fn arange(start: f32, end: f32, device: &Device) -> Self {
7825        Self::arange_step(start, end, 1.0, device)
7826    }
7827
7828    /// `arange_step(start, end, step, device)`: a rank-1 tensor of
7829    /// `[start, end)` with constant step. F32 only for the static
7830    /// factory; cast for other dtypes. Errors at runtime if `step ==
7831    /// 0`.
7832    pub fn arange_step(start: f32, end: f32, step: f32, device: &Device) -> Self {
7833        assert!(step != 0.0, "arange_step: step must be non-zero");
7834        let mut data = Vec::new();
7835        let mut current = start;
7836        if step > 0.0 {
7837            while current < end {
7838                data.push(current);
7839                current += step;
7840            }
7841        } else {
7842            while current > end {
7843                data.push(current);
7844                current += step;
7845            }
7846        }
7847        let n = data.len();
7848        // GAP-003 carve-out. `.expect`, NOT `?`: this cannot fail, and a `Result`
7849        // here would be one that is never `Err` -- a false claim in the signature
7850        // that every caller would then write a `?` for.
7851        //
7852        // THE PROOF IS LOCAL AND ONE LINE UP: `n` IS `data.len()`, and the shape
7853        // is `[n]`. The shape is derived FROM the buffer, so they cannot disagree.
7854        Self::from_f32(data, vec![n], device).expect(
7855            "arange_step: shape is [n] where n IS data.len(), computed one line              above from that same buffer -- the lengths cannot disagree",
7856        )
7857    }
7858
7859    /// Linearly-spaced 1D tensor with `n` points from `start` to `end`
7860    /// (inclusive on both ends). Matches NumPy's `linspace`.
7861    pub fn linspace(start: f32, end: f32, n: usize, device: &Device) -> Self {
7862        assert!(n >= 1, "linspace: n must be >= 1");
7863        if n == 1 {
7864            // GAP-003 carve-out: a one-element vec with shape [1], on one line.
7865            return Self::from_f32(vec![start], vec![1], device)
7866                .expect("linspace: vec![start] has exactly 1 element and the shape is [1]");
7867        }
7868        let step = (end - start) / ((n - 1) as f32);
7869        let data: Vec<f32> = (0..n).map(|i| start + step * (i as f32)).collect();
7870        // GAP-003 carve-out: `data` is a `(0..n)` map -- exactly `n` elements --
7871        // and the shape is `[n]`. Both from the same `n`, two lines apart.
7872        Self::from_f32(data, vec![n], device).expect(
7873            "linspace: data is (0..n).map(..).collect() so it has exactly n              elements, and the shape is [n] -- both from the same `n`",
7874        )
7875    }
7876
7877    /// Frobenius norm: `sqrt(sum(self * self))`. Returns a scalar tensor.
7878    pub fn norm(&self) -> Self {
7879        self.sqr().sum_all().sqrt()
7880    }
7881
7882    /// General 1-D cross-correlation. Shapes:
7883    /// - `self`: `[N, Cin, T]`
7884    /// - `weight`: `[Cout, Cin/groups, K]`
7885    /// - `bias` (optional): `[Cout]`
7886    /// - returns: `[N, Cout, Tout]` where `Tout = (T + 2·padding - K) /
7887    ///   stride + 1`
7888    ///
7889    /// Implemented as a composite via Conv2D: unsqueeze the spatial dim
7890    /// to make a unit `H = 1`, run `Conv2D` with `Kh = 1, stride.0 = 1,
7891    /// padding.0 = 0`, then squeeze the dim back out. Works through
7892    /// every backend's Conv2D dispatch (CPU, CUDA via baracuda,
7893    /// Vulkan, AOCL, MKL). The future fused `Op::Conv1D` will collapse
7894    /// the unsqueeze/squeeze pair when a high-volume Conv1D consumer
7895    /// materializes.
7896    pub fn conv1d(
7897        &self,
7898        weight: &Self,
7899        bias: Option<&Self>,
7900        stride: usize,
7901        padding: usize,
7902        groups: usize,
7903    ) -> std::result::Result<Self, fuel_ir::Error> {
7904        let x_dims = self.shape().dims().to_vec();
7905        let w_dims = weight.shape().dims().to_vec();
7906        if x_dims.len() != 3 {
7907            return Err(fuel_ir::Error::Msg(format!(
7908                "conv1d: x must be rank 3 [N, Cin, T], got {x_dims:?}",
7909            ))
7910            .bt());
7911        }
7912        if w_dims.len() != 3 {
7913            return Err(fuel_ir::Error::Msg(format!(
7914                "conv1d: weight must be rank 3 [Cout, Cin/groups, K], got {w_dims:?}",
7915            ))
7916            .bt());
7917        }
7918        if groups < 1 {
7919            return Err(fuel_ir::Error::Msg("conv1d: groups must be ≥ 1".into()).bt());
7920        }
7921        if stride < 1 {
7922            return Err(fuel_ir::Error::Msg("conv1d: stride must be ≥ 1".into()).bt());
7923        }
7924        // Add a unit H dim at index 2 → [N, Cin, 1, T] and [Cout, Cin/g, 1, K].
7925        let x_4d = self.unsqueeze(2_usize)?;
7926        let w_4d = weight.unsqueeze(2_usize)?;
7927        let out_4d = x_4d.conv2d(&w_4d, bias, (1, stride), (0, padding), groups)?;
7928        out_4d.squeeze(2)
7929    }
7930
7931    /// Eager-API parity for `conv1d_with_algo`. The `_algo` selector is
7932    /// ignored on the lazy path — algorithm selection happens at
7933    /// backend dispatch time, not at graph construction. Reduces to
7934    /// [`Self::conv1d`].
7935    pub fn conv1d_with_algo<A>(
7936        &self,
7937        weight: &Self,
7938        bias: Option<&Self>,
7939        stride: usize,
7940        padding: usize,
7941        groups: usize,
7942        _algo: A,
7943    ) -> std::result::Result<Self, fuel_ir::Error> {
7944        self.conv1d(weight, bias, stride, padding, groups)
7945    }
7946
7947    /// 2-D average pooling. Input `[N, C, H, W]`, output
7948    /// `[N, C, H_out, W_out]` where
7949    /// `H_out = (H + 2·padding.0 - kernel.0) / stride.0 + 1`.
7950    ///
7951    /// Implemented as a **depthwise Conv2D** with a constant
7952    /// `1/(kh·kw)` kernel: one graph node + the kernel const. Works
7953    /// through every backend's Conv2D dispatch and inherits Conv2D's
7954    /// gradient. Composite supports arbitrary kernel / stride /
7955    /// padding.
7956    pub fn avg_pool2d(
7957        &self,
7958        kernel: (usize, usize),
7959        stride: (usize, usize),
7960        padding: (usize, usize),
7961        count_include_pad: bool,
7962    ) -> std::result::Result<Self, fuel_ir::Error> {
7963        let dims = self.shape().dims().to_vec();
7964        if dims.len() != 4 {
7965            return Err(fuel_ir::Error::Msg(format!(
7966                "avg_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
7967            ))
7968            .bt());
7969        }
7970        let (c, h, w) = (dims[1], dims[2], dims[3]);
7971        let (kh, kw) = kernel;
7972        if kh == 0 || kw == 0 {
7973            return Err(
7974                fuel_ir::Error::Msg("avg_pool2d: kernel sizes must be positive".into()).bt(),
7975            );
7976        }
7977
7978        // KISS-Ops §6.13: count_include_pad must be an EXPLICIT choice, not
7979        // an implicit torch-style default silently baked into the divisor.
7980        // With no padding the two modes coincide (every window is full),
7981        // so the uniform-divisor path below is exact either way.
7982        if count_include_pad || padding == (0, 0) {
7983            let inv = 1.0_f32 / ((kh * kw) as f32);
7984            // Depthwise kernel: one filter per input channel, each filter
7985            // is a constant 1/(kh·kw). Shape [C, 1, kh, kw] with groups=C
7986            // makes Conv2D compute one independent kernel per channel.
7987            let weight =
7988                self.const_f32_like(vec![inv; c * kh * kw], Shape::from_dims(&[c, 1, kh, kw]))?;
7989            return self.conv2d(&weight, None, stride, padding, c);
7990        }
7991
7992        // count_include_pad = false with real padding: a uniform divisor is
7993        // WRONG at every border window (it silently averages in the padded
7994        // zeros as if they were real taps, undercounting the true mean by
7995        // exactly the fraction of the window that's padding). The correct
7996        // divisor is the per-position COUNT of valid (non-padded) taps, which
7997        // varies by output position — sum-pool (an all-ones depthwise kernel)
7998        // then divide by that count map instead of a constant.
7999        //
8000        // A window can have ZERO valid taps (e.g. a 1x1 input with padding
8001        // >= kernel size): every tap it covers is padding. The count map
8002        // would then be zero at that position and `broadcast_div` would
8003        // silently emit NaN/inf instead of a defined average. Refuse up
8004        // front rather than let that propagate -- computed host-side from
8005        // (H, W, kernel, stride, padding) alone, no graph ops needed.
8006        if let Some((axis, out_idx)) = first_zero_tap_output_index(h, kh, stride.0, padding.0)
8007            .map(|i| ("H", i))
8008            .or_else(|| first_zero_tap_output_index(w, kw, stride.1, padding.1).map(|i| ("W", i)))
8009        {
8010            return Err(fuel_ir::Error::Msg(format!(
8011                "avg_pool2d: count_include_pad=false has no valid (non-padded) \
8012                 taps for output position {out_idx} on the {axis} axis \
8013                 (kernel={kernel:?}, stride={stride:?}, padding={padding:?}, \
8014                 input H×W={h}×{w}) — the average would divide by zero",
8015            ))
8016            .bt());
8017        }
8018
8019        let sum_weight = self.const_f32_like(
8020            vec![1.0_f32; c * kh * kw],
8021            Shape::from_dims(&[c, 1, kh, kw]),
8022        )?;
8023        let summed = self.conv2d(&sum_weight, None, stride, padding, c)?;
8024
8025        // The valid-tap count depends only on (H, W, kernel, stride,
8026        // padding) -- not on N or C -- so it's computed once at minimal
8027        // [1, 1, H, W] size and broadcast-divided into every (n, c) plane.
8028        let ones_hw = self.const_f32_like(vec![1.0_f32; h * w], Shape::from_dims(&[1, 1, h, w]))?;
8029        let count_weight =
8030            self.const_f32_like(vec![1.0_f32; kh * kw], Shape::from_dims(&[1, 1, kh, kw]))?;
8031        let count = ones_hw.conv2d(&count_weight, None, stride, padding, 1)?;
8032
8033        summed.broadcast_div(&count)
8034    }
8035
8036    /// Eager-API parity for `avg_pool2d_with_stride`. Same shape as
8037    /// [`Self::avg_pool2d`] but the stride is passed explicitly rather
8038    /// than inferred from kernel.
8039    pub fn avg_pool2d_with_stride(
8040        &self,
8041        kernel: (usize, usize),
8042        stride: (usize, usize),
8043    ) -> std::result::Result<Self, fuel_ir::Error> {
8044        // No padding, so count_include_pad is a don't-care (both modes
8045        // coincide — see avg_pool2d's own short-circuit for this case).
8046        self.avg_pool2d(kernel, stride, (0, 0), true)
8047    }
8048
8049    /// 2-D max pooling. Input `[N, C, H, W]`, output
8050    /// `[N, C, H_out, W_out]` where
8051    /// `H_out = (H + 2·padding.0 - kernel.0) / stride.0 + 1`.
8052    ///
8053    /// Composite via slice + maximum: pad the input, then for every
8054    /// `(ky, kx)` in `[0..kh, 0..kw]` slice the strided grid of taps
8055    /// (one tap per output position) and take the elementwise max.
8056    /// Produces `kh·kw` nodes per call plus padding — cheap for the
8057    /// common 2×2 / 3×3 cases.
8058    ///
8059    /// Strided-slice trick: for stride `sh`, reshape the padded H from
8060    /// `(H_out · sh)` to `(H_out, sh)`, then slice the inner `sh`-dim
8061    /// at the tap index. Requires `H_padded == H_out · sh` exactly.
8062    /// Inputs that don't divide cleanly will be padded so they do.
8063    pub fn max_pool2d(
8064        &self,
8065        kernel: (usize, usize),
8066        stride: (usize, usize),
8067        padding: (usize, usize),
8068    ) -> std::result::Result<Self, fuel_ir::Error> {
8069        // KISS-Ops §6.13 / PyTorch-correct semantics: a padded slot must
8070        // never win the max — zero padding silently wins every all-negative
8071        // window (e.g. post-activation feature maps dominated by negative
8072        // values at the border), which is a real correctness bug, not a
8073        // style choice. `f32::NEG_INFINITY` padding is the fix; use
8074        // [`Self::max_pool2d_with_pad_value`] directly for any OTHER pad
8075        // value (there is no implicit torch-style default here anymore).
8076        self.max_pool2d_with_pad_value(kernel, stride, padding, f32::NEG_INFINITY)
8077    }
8078
8079    /// `max_pool2d` variant where the boundary padding is filled with an
8080    /// explicit `pad_value` instead of `0.0`. Pass `f32::NEG_INFINITY`
8081    /// for PyTorch-correct semantics (padded slots can never win the
8082    /// max). All other constraints match [`Self::max_pool2d`]; the only
8083    /// difference is the constant value the implicit boundary pad uses.
8084    pub fn max_pool2d_with_pad_value(
8085        &self,
8086        kernel: (usize, usize),
8087        stride: (usize, usize),
8088        padding: (usize, usize),
8089        pad_value: f32,
8090    ) -> std::result::Result<Self, fuel_ir::Error> {
8091        let dims = self.shape().dims().to_vec();
8092        if dims.len() != 4 {
8093            return Err(fuel_ir::Error::Msg(format!(
8094                "max_pool2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8095            ))
8096            .bt());
8097        }
8098        let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8099        let (kh, kw) = kernel;
8100        let (sh, sw) = stride;
8101        let (ph, pw) = padding;
8102        if kh == 0 || kw == 0 {
8103            return Err(
8104                fuel_ir::Error::Msg("max_pool2d: kernel sizes must be positive".into()).bt(),
8105            );
8106        }
8107        if sh == 0 || sw == 0 {
8108            return Err(fuel_ir::Error::Msg("max_pool2d: strides must be positive".into()).bt());
8109        }
8110        let h_padded_min = h + 2 * ph;
8111        let w_padded_min = w + 2 * pw;
8112        if h_padded_min < kh || w_padded_min < kw {
8113            return Err(fuel_ir::Error::Msg(format!(
8114                "max_pool2d: padded input ({h_padded_min}×{w_padded_min}) smaller than kernel ({kh}×{kw})",
8115            )).bt());
8116        }
8117        let h_out = (h_padded_min - kh) / sh + 1;
8118        let w_out = (w_padded_min - kw) / sw + 1;
8119        // Pad H/W to be exactly (h_out · sh + (kh - sh)) and (w_out · sw + (kw - sw)),
8120        // i.e., enough to contain every (ky, kx) tap for every output.
8121        let h_total = h_out * sh + (kh - 1);
8122        let w_total = w_out * sw + (kw - 1);
8123        let extra_h = h_total.saturating_sub(h_padded_min);
8124        let extra_w = w_total.saturating_sub(w_padded_min);
8125        let padded = self
8126            .pad_with_value(2, ph, ph + extra_h, pad_value)?
8127            .pad_with_value(3, pw, pw + extra_w, pad_value)?;
8128        // For each (ky, kx) collect the strided tap.
8129        let mut acc: Option<Tensor> = None;
8130        for ky in 0..kh {
8131            // Slice H starting at ky, length h_out · sh, then reshape
8132            // to [N, C, h_out, sh, w_total] and slice the sh-dim at 0
8133            // (we'll handle stride > 1 by reshape).
8134            let row_slice = padded.slice(2, ky, h_out * sh).unwrap();
8135            // Reshape H dim of length `h_out · sh` into (h_out, sh),
8136            // then take dim 3 at offset 0 (the tap on the sh axis).
8137            let row_reshaped = row_slice.reshape(vec![n, c, h_out, sh, w_total])?;
8138            let row_tap = row_reshaped.slice(3, 0, 1).unwrap().squeeze(3)?;
8139            for kx in 0..kw {
8140                let col_slice = row_tap.slice(3, kx, w_out * sw).unwrap();
8141                let col_reshaped = col_slice.reshape(vec![n, c, h_out, w_out, sw])?;
8142                let win = col_reshaped.slice(4, 0, 1).unwrap().squeeze(4)?;
8143                acc = Some(match acc {
8144                    None => win,
8145                    Some(a) => a.maximum(&win).unwrap(),
8146                });
8147            }
8148        }
8149        acc.ok_or_else(|| fuel_ir::Error::Msg("max_pool2d: empty kernel".into()).bt())
8150    }
8151
8152    /// Eager-API parity for `max_pool2d_with_stride`.
8153    pub fn max_pool2d_with_stride(
8154        &self,
8155        kernel: (usize, usize),
8156        stride: (usize, usize),
8157    ) -> std::result::Result<Self, fuel_ir::Error> {
8158        self.max_pool2d(kernel, stride, (0, 0))
8159    }
8160
8161    /// Nearest-neighbor upsample by integer factor `scale` along the
8162    /// last two spatial dims. Input `[N, C, H, W]` → output
8163    /// `[N, C, H·scale, W·scale]`.
8164    ///
8165    /// Composite via reshape + concat + reshape: insert a unit dim
8166    /// after each spatial dim, concat `scale` copies of the tensor on
8167    /// each new dim, then collapse the inflated dims back. Same shape
8168    /// as the `upsample_nearest_2x` helper in `fuel_transformers::models::lazy_yolov8`
8169    /// and `fuel_transformers::models::lazy_sd_unet`, generalized to arbitrary scale.
8170    pub fn upsample_nearest2d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8171        if scale == 0 {
8172            return Err(
8173                fuel_ir::Error::Msg("upsample_nearest2d: scale must be positive".into()).bt(),
8174            );
8175        }
8176        let dims = self.shape().dims().to_vec();
8177        if dims.len() != 4 {
8178            return Err(fuel_ir::Error::Msg(format!(
8179                "upsample_nearest2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8180            ))
8181            .bt());
8182        }
8183        if scale == 1 {
8184            return Ok(self.clone());
8185        }
8186        let (n, c, h, w) = (dims[0], dims[1], dims[2], dims[3]);
8187        // [N, C, H, 1, W, 1]
8188        let expanded = self.reshape(vec![n, c, h, 1, w, 1])?;
8189        // Replicate along the new unit dims by concatenating scale copies.
8190        let h_expanded = (0..scale)
8191            .fold(None, |acc: Option<Tensor>, _| {
8192                Some(match acc {
8193                    None => expanded.clone(),
8194                    Some(a) => a.concat(&expanded, 3).unwrap(),
8195                })
8196            })
8197            .unwrap();
8198        let h_then_w = (0..scale)
8199            .fold(None, |acc: Option<Tensor>, _| {
8200                Some(match acc {
8201                    None => h_expanded.clone(),
8202                    Some(a) => a.concat(&h_expanded, 5).unwrap(),
8203                })
8204            })
8205            .unwrap();
8206        h_then_w.reshape(vec![n, c, h * scale, w * scale])
8207    }
8208
8209    /// Nearest-neighbor upsample for 1-D signals `[N, C, T]` by integer
8210    /// `scale`. Reshape to insert a unit dim, concat scale copies,
8211    /// reshape back.
8212    pub fn upsample_nearest1d(&self, scale: usize) -> std::result::Result<Self, fuel_ir::Error> {
8213        if scale == 0 {
8214            return Err(
8215                fuel_ir::Error::Msg("upsample_nearest1d: scale must be positive".into()).bt(),
8216            );
8217        }
8218        let dims = self.shape().dims().to_vec();
8219        if dims.len() != 3 {
8220            return Err(fuel_ir::Error::Msg(format!(
8221                "upsample_nearest1d: input must be rank 3 [N, C, T], got {dims:?}",
8222            ))
8223            .bt());
8224        }
8225        if scale == 1 {
8226            return Ok(self.clone());
8227        }
8228        let (n, c, t) = (dims[0], dims[1], dims[2]);
8229        let expanded = self.reshape(vec![n, c, t, 1])?;
8230        let replicated = (0..scale)
8231            .fold(None, |acc: Option<Tensor>, _| {
8232                Some(match acc {
8233                    None => expanded.clone(),
8234                    Some(a) => a.concat(&expanded, 3).unwrap(),
8235                })
8236            })
8237            .unwrap();
8238        replicated.reshape(vec![n, c, t * scale])
8239    }
8240
8241    /// 2-D nearest interpolation to an explicit target size.
8242    /// Arbitrary ratios (non-integer, non-uniform between H and
8243    /// W) supported via an `index_select`-based composite. The
8244    /// indexing convention matches PyTorch / the eager kernel:
8245    /// `src_h[oi] = min(H - 1, floor(oi * H / H_out))`.
8246    ///
8247    /// Used by DepthAnythingV2's DPT head and similar dense
8248    /// prediction heads that resize feature maps to arbitrary
8249    /// targets.
8250    pub fn interpolate2d(
8251        &self,
8252        target_h: usize,
8253        target_w: usize,
8254    ) -> std::result::Result<Self, fuel_ir::Error> {
8255        let dims = self.shape().dims().to_vec();
8256        if dims.len() != 4 {
8257            return Err(fuel_ir::Error::Msg(format!(
8258                "interpolate2d: input must be rank 4 [N, C, H, W], got {dims:?}",
8259            ))
8260            .bt());
8261        }
8262        let h = dims[2];
8263        let w = dims[3];
8264        if h == 0 || w == 0 || target_h == 0 || target_w == 0 {
8265            return Err(fuel_ir::Error::Msg(
8266                "interpolate2d: input + target spatial dims must be positive".into(),
8267            )
8268            .bt());
8269        }
8270        // Fast-path: identity.
8271        if target_h == h && target_w == w {
8272            return Ok(self.clone());
8273        }
8274        // Fast-path: integer-multiple uniform scale → existing
8275        // `upsample_nearest2d` (more cache-friendly than the
8276        // index_select composite for the common 2× / 4× case).
8277        if target_h.is_multiple_of(h) && target_w.is_multiple_of(w) && target_h / h == target_w / w
8278        {
8279            return self.upsample_nearest2d(target_h / h);
8280        }
8281        // General case: build per-axis source-index tensors and
8282        // index_select. Matches the eager UpsampleNearest2D
8283        // kernel's convention: src_idx = min(src - 1, floor(out * src / target)).
8284        let h_idx: Vec<u32> = (0..target_h)
8285            .map(|oi| ((oi * h) / target_h).min(h - 1) as u32)
8286            .collect();
8287        let w_idx: Vec<u32> = (0..target_w)
8288            .map(|oj| ((oj * w) / target_w).min(w - 1) as u32)
8289            .collect();
8290        let h_idx_tensor = self.const_u32_like(h_idx, fuel_ir::Shape::from_dims(&[target_h]))?;
8291        let w_idx_tensor = self.const_u32_like(w_idx, fuel_ir::Shape::from_dims(&[target_w]))?;
8292        let after_h = self.index_select(2_usize, &h_idx_tensor)?;
8293        after_h.index_select(3_usize, &w_idx_tensor)
8294    }
8295
8296    /// 1-D nearest interpolation to an explicit target size. Same
8297    /// constraints as [`Self::interpolate2d`]: integer-multiple targets
8298    /// only.
8299    pub fn interpolate1d(&self, target_t: usize) -> std::result::Result<Self, fuel_ir::Error> {
8300        let dims = self.shape().dims().to_vec();
8301        if dims.len() != 3 {
8302            return Err(fuel_ir::Error::Msg(format!(
8303                "interpolate1d: input must be rank 3 [N, C, T], got {dims:?}",
8304            ))
8305            .bt());
8306        }
8307        let t = dims[2];
8308        if t == 0 {
8309            return Err(
8310                fuel_ir::Error::Msg("interpolate1d: input length must be positive".into()).bt(),
8311            );
8312        }
8313        if !target_t.is_multiple_of(t) {
8314            return Err(fuel_ir::Error::Msg(format!(
8315                "interpolate1d: target {target_t} must be integer multiple of input {t}; non-integer ratios are future work",
8316            )).bt());
8317        }
8318        self.upsample_nearest1d(target_t / t)
8319    }
8320
8321    /// Pad with zeros along `dim`: `left` zeros before, `right` zeros
8322    /// after. Thin wrapper over [`Self::pad_with_value`] with `value = 0.0`.
8323    /// Composite — no new graph op. Accepts any [`Dim`].
8324    pub fn pad_with_zeros<D: Dim>(
8325        &self,
8326        dim: D,
8327        left: usize,
8328        right: usize,
8329    ) -> std::result::Result<Self, fuel_ir::Error> {
8330        self.pad_with_value(dim, left, right, 0.0)
8331    }
8332
8333    /// Pad with a constant `value` along `dim`: `before` slots before,
8334    /// `after` slots after. Wraps [`Self::pad`] with `PadMode::Constant`
8335    /// for the named dim (other dims get `(0, 0)`); the `f32` value is
8336    /// widened to the graph op's `f64` param. Useful for `-inf` padding
8337    /// around max-reductions (e.g. PyTorch-style `max_pool2d`, where
8338    /// padded positions must never win the max). Accepts any [`Dim`].
8339    pub fn pad_with_value<D: Dim>(
8340        &self,
8341        dim: D,
8342        before: usize,
8343        after: usize,
8344        value: f32,
8345    ) -> std::result::Result<Self, fuel_ir::Error> {
8346        let shape = self.shape();
8347        let dim = dim.to_index(&shape, "pad_with_value")?;
8348        let rank = shape.dims().len();
8349        if before == 0 && after == 0 {
8350            return Ok(self.clone());
8351        }
8352        let mut padding: Vec<(usize, usize)> = vec![(0, 0); rank];
8353        padding[dim] = (before, after);
8354        self.pad(padding, fuel_graph::PadMode::Constant, value as f64)
8355    }
8356
8357    /// Coordinate grids from rank-1 inputs. Matches PyTorch's
8358    /// `torch.meshgrid` and eager's `crate::Tensor::meshgrid`:
8359    ///
8360    /// - `xy_indexing = true` (Cartesian, NumPy default): the first
8361    ///   two inputs are swapped before broadcasting and the resulting
8362    ///   grids reversed back, so for `(x, y)` the grids carry shape
8363    ///   `[len(y), len(x)]` (image-coordinate convention).
8364    /// - `xy_indexing = false` (matrix / ij): grids carry the input
8365    ///   cardinalities in input order.
8366    ///
8367    /// Implemented as `reshape` + `repeat`. All inputs must share the
8368    /// same dtype and live on the same graph.
8369    pub fn meshgrid(
8370        args: &[&Self],
8371        xy_indexing: bool,
8372    ) -> std::result::Result<Vec<Self>, fuel_ir::Error> {
8373        if args.len() < 2 {
8374            return Err(fuel_ir::Error::Msg(
8375                "meshgrid: requires at least two rank-1 tensors".into(),
8376            )
8377            .bt());
8378        }
8379        let ordered: Vec<&Self> = if xy_indexing {
8380            args.iter().rev().copied().collect()
8381        } else {
8382            args.to_vec()
8383        };
8384        let mut lens = Vec::with_capacity(ordered.len());
8385        for (i, t) in ordered.iter().enumerate() {
8386            let dims = t.shape().dims().to_vec();
8387            if dims.len() != 1 {
8388                return Err(fuel_ir::Error::Msg(format!(
8389                    "meshgrid: input {i} must be rank 1, got shape {dims:?}",
8390                ))
8391                .bt());
8392            }
8393            lens.push(dims[0]);
8394        }
8395        let mut grids = Vec::with_capacity(ordered.len());
8396        for (idx, t) in ordered.iter().enumerate() {
8397            let mut shape = vec![1_usize; ordered.len()];
8398            shape[idx] = lens[idx];
8399            let placed = t.reshape(shape)?;
8400            let mut repeats = lens.clone();
8401            repeats[idx] = 1;
8402            let grid = placed.repeat(repeats)?;
8403            grids.push(grid);
8404        }
8405        if xy_indexing {
8406            grids.reverse();
8407        }
8408        Ok(grids)
8409    }
8410
8411    /// Repeat the tensor along each dim `repeats[i]` times. If `repeats`
8412    /// has more dims than `self`, `self` is implicitly left-padded with
8413    /// size-1 dims to match. Matches PyTorch's `Tensor.repeat`.
8414    pub fn repeat(&self, repeats: impl Into<Shape>) -> std::result::Result<Self, fuel_ir::Error> {
8415        let repeats = repeats.into();
8416        let repeats: Vec<usize> = repeats.dims().to_vec();
8417        let self_rank = self.shape().dims().len();
8418        let target_rank = repeats.len();
8419        let mut work = if self_rank < target_rank {
8420            let pad_count = target_rank - self_rank;
8421            let mut new_shape: Vec<usize> = vec![1; pad_count];
8422            new_shape.extend_from_slice(self.shape().dims());
8423            self.reshape(new_shape)?
8424        } else if self_rank > target_rank {
8425            return Err(fuel_ir::Error::Msg(format!(
8426                "repeat: repeats rank {target_rank} smaller than tensor rank {self_rank}",
8427            ))
8428            .bt());
8429        } else {
8430            self.clone()
8431        };
8432        for (axis, &n) in repeats.iter().enumerate() {
8433            if n == 0 {
8434                return Err(fuel_ir::Error::Msg(format!(
8435                    "repeat: zero repeat count at axis {axis} not supported",
8436                ))
8437                .bt());
8438            }
8439            if n == 1 {
8440                continue;
8441            }
8442            // n copies concatenated along `axis`.
8443            let base = work.clone();
8444            for _ in 1..n {
8445                work = work.concat(&base, axis)?;
8446            }
8447        }
8448        Ok(work)
8449    }
8450}
8451
8452/// For a single pooling axis, the first output index (if any) whose window
8453/// has zero valid (non-padded) taps — every tap it covers lies outside
8454/// `[0, dim)`. Used by [`Tensor::avg_pool2d`]'s `count_include_pad = false`
8455/// path to refuse a divide-by-zero divisor instead of emitting NaN/inf.
8456///
8457/// Pure host-side arithmetic over the pooling shape parameters; computes no
8458/// tensor, builds no graph. `out_dim` matches the formula in
8459/// [`Tensor::avg_pool2d`]'s doc comment: `(dim + 2*pad - kernel) / stride + 1`.
8460fn first_zero_tap_output_index(
8461    dim: usize,
8462    kernel: usize,
8463    stride: usize,
8464    pad: usize,
8465) -> Option<usize> {
8466    let out_dim = (dim + 2 * pad).saturating_sub(kernel) / stride + 1;
8467    (0..out_dim).find(|&o| {
8468        let start = o as isize * stride as isize - pad as isize;
8469        let end = start + kernel as isize;
8470        let valid_start = start.max(0);
8471        let valid_end = end.min(dim as isize);
8472        valid_end <= valid_start
8473    })
8474}
8475
8476// ---- safetensors integration -----------------------------------------------
8477
8478impl Tensor {
8479    /// Build a `Tensor` from raw little-endian bytes as they appear
8480    /// in a safetensors file, plus a dtype and shape. Row-major layout
8481    /// is assumed. The byte count must match `shape.elem_count() *
8482    /// dtype_bytes`.
8483    ///
8484    /// This is the low-level loader. Prefer [`Self::from_safetensors_view`]
8485    /// if you already have a `safetensors::TensorView` in hand.
8486    ///
8487    /// Supported dtypes today: `F32`, `F64`, `BF16`, `F16`, `U32`.
8488    /// Integer types other than `U32` are rejected to keep the
8489    /// surface small; add them when a real model needs them.
8490    pub fn from_safetensors_bytes(
8491        bytes: &[u8],
8492        dtype: safetensors::Dtype,
8493        shape: &[usize],
8494        device: &Device,
8495    ) -> crate::Result<Self> {
8496        use safetensors::Dtype;
8497        let shape_obj = Shape::from_dims(shape);
8498        let elem_count = shape_obj.elem_count();
8499
8500        let check_len = |expected: usize| -> crate::Result<()> {
8501            if bytes.len() != expected {
8502                crate::bail!(
8503                    "from_safetensors_bytes: expected {expected} bytes for dtype {dtype:?} \
8504                     and shape {shape:?}, got {}",
8505                    bytes.len(),
8506                );
8507            }
8508            Ok(())
8509        };
8510
8511        match dtype {
8512            Dtype::F32 => {
8513                check_len(elem_count * 4)?;
8514                let mut data = Vec::with_capacity(elem_count);
8515                for chunk in bytes.as_chunks::<4>().0.iter() {
8516                    data.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8517                }
8518                Self::from_f32(data, shape_obj, device)
8519            }
8520            Dtype::F64 => {
8521                check_len(elem_count * 8)?;
8522                let mut data = Vec::with_capacity(elem_count);
8523                for chunk in bytes.as_chunks::<8>().0.iter() {
8524                    let arr: [u8; 8] = *chunk;
8525                    data.push(f64::from_le_bytes(arr));
8526                }
8527                Self::from_f64(data, shape_obj, device)
8528            }
8529            Dtype::BF16 => {
8530                check_len(elem_count * 2)?;
8531                let mut data = Vec::with_capacity(elem_count);
8532                for chunk in bytes.as_chunks::<2>().0.iter() {
8533                    let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8534                    data.push(half::bf16::from_bits(raw));
8535                }
8536                Self::from_bf16(data, shape_obj, device)
8537            }
8538            Dtype::F16 => {
8539                check_len(elem_count * 2)?;
8540                let mut data = Vec::with_capacity(elem_count);
8541                for chunk in bytes.as_chunks::<2>().0.iter() {
8542                    let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
8543                    data.push(half::f16::from_bits(raw));
8544                }
8545                Self::from_f16(data, shape_obj, device)
8546            }
8547            Dtype::U32 => {
8548                check_len(elem_count * 4)?;
8549                let mut data = Vec::with_capacity(elem_count);
8550                for chunk in bytes.as_chunks::<4>().0.iter() {
8551                    data.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
8552                }
8553                Self::from_u32(data, shape_obj, device)
8554            }
8555            other => crate::bail!(
8556                "from_safetensors_bytes: unsupported dtype {other:?} — extend Tensor's \
8557                 safetensors loader to handle it",
8558            ),
8559        }
8560    }
8561
8562    /// Build a `Tensor` from a `safetensors::TensorView`. This is
8563    /// the most natural entry point when iterating over a
8564    /// [`fuel_formats::safetensors::MmapedSafetensors`] or similar.
8565    pub fn from_safetensors_view(
8566        view: &safetensors::tensor::TensorView<'_>,
8567        device: &Device,
8568    ) -> crate::Result<Self> {
8569        Self::from_safetensors_bytes(view.data(), view.dtype(), view.shape(), device)
8570    }
8571}
8572
8573/// A LayerNorm's learned `(gain, bias)`, both length `[dim]`. Wrapped in
8574/// `Option` at sites where the norm is conditional — present only on layer 0
8575/// (RWKV `pre_ln`), or only when a config flag is set (Persimmon QK-LN).
8576pub type LayerNormPair = (Arc<[f32]>, Arc<[f32]>);
8577
8578/// A convolution's `(weight, bias)`: the flattened `[out, in, kh, kw]` kernel
8579/// and its `[out]` bias. Distinct from [`LayerNormPair`] despite the identical
8580/// shape — the two are not interchangeable and naming them apart is the point.
8581pub type ConvWeightBias = (Arc<[f32]>, Arc<[f32]>);
8582
8583/// Weight tensor storage that preserves source precision.
8584///
8585/// Projection weights (Q/K/V/O for attention, gate/up/down for FFN,
8586/// and the output `lm_head` matrix) stay in whatever dtype the
8587/// source checkpoint used — f32 when that's how it was saved, bf16
8588/// for modern HF checkpoints that ship bf16 to halve weight memory.
8589/// Activations are usually f32, but LlamaModel's cached decode path
8590/// (Phase D increment A, "BF16-throughout decode") threads the KV
8591/// cache's dtype through the whole activation stream — when that's
8592/// BF16, weights must ALSO be BF16 (`matmul`'s dtype gate only allows
8593/// same-dtype homogeneous or `(lhs=F32, rhs=BF16)`; a BF16-activation ×
8594/// F32-weight matmul is rejected, the opposite direction from the
8595/// classic f32-activation-over-bf16-weight quantized-serving case).
8596/// F32 activations still route the mixed `(A:F32, B:BF16) → F32`
8597/// precision via `VulkanBackend::matmul` unchanged.
8598///
8599/// Norm gains and biases are NOT covered by this enum — they're
8600/// small and precision-sensitive, so they stay `Arc<[f32]>`.
8601///
8602/// Cloning is cheap (Arc bump) for both variants. Use
8603/// [`WeightStorage::const_like`] to emit a [`Tensor`] `Const`
8604/// node with the right dtype.
8605#[derive(Debug, Clone)]
8606pub enum WeightStorage {
8607    F32(Arc<[f32]>),
8608    BF16(Arc<[half::bf16]>),
8609    /// GGML Q4_0 blocks (raw byte stream), laid out as `[out_features,
8610    /// in_features / 32]` blocks (18 bytes each, llama.cpp convention).
8611    /// Stored as `Arc<[u32]>` — the byte stream reinterpreted as u32
8612    /// words so subsequent forward passes just Arc-clone (cheap) rather
8613    /// than recopying the bytes. The graph sees this directly as a U32
8614    /// tensor; matmul dispatch goes through `Op::QMatMul`.
8615    ///
8616    /// `bytes_len` is the original byte count (u32_len * 4) so the
8617    /// const_like shape computation doesn't accidentally round up.
8618    Q4_0 {
8619        words: Arc<[u32]>,
8620        bytes_len: usize,
8621        in_features: usize,
8622        out_features: usize,
8623    },
8624    /// Any other GGML block format that `Op::QMatMul` has a kernel for (Q8_0, Q4_K, Q6_K, ...),
8625    /// kept in its on-disk block layout `[out_features, in_features / block]` so a GGUF tensor
8626    /// stays quantized from load to the matmul (ROADMAP row 124). Same representation as
8627    /// [`Self::Q4_0`] (the byte stream as `u32` words, a 1-D `U32` const in the graph, applied
8628    /// through `qmatmul`), plus the block format.
8629    Ggml {
8630        qtype: fuel_graph::QuantType,
8631        words: Arc<[u32]>,
8632        bytes_len: usize,
8633        in_features: usize,
8634        out_features: usize,
8635    },
8636    /// An AWQ 4-bit linear (HuggingFace `*-AWQ`, GEMM version) in the
8637    /// `AWQ_MATMUL` kernel layout, as graph-independent host buffers. The
8638    /// graph sees it through `NodeHandle::awq_matmul` operands
8639    /// built in `apply_linear`; it has no plain `const_like` form.
8640    Awq(Arc<crate::awq::AwqHostWeight>),
8641    /// Base weight wrapped with a trainable LoRA (Low-Rank Adaptation)
8642    /// update: effective weight `W_eff = base + (alpha / rank) · A · B`
8643    /// where `A` has shape `[in_features, rank]` and `B` has shape
8644    /// `[rank, out_features]` (both stored in the same layout
8645    /// convention as F32 weights — `[in, out]`).
8646    ///
8647    /// Used for PEFT-style inference with frozen base weights (which
8648    /// can be F32, BF16, or Q4_0) plus small trainable adapter matrices.
8649    /// The adapter is cheap to apply — for a 2560×2560 projection at
8650    /// rank 8 the LoRA path is ~0.5% of the base matmul cost.
8651    WithLoRA {
8652        base: Box<WeightStorage>,
8653        /// `[in_features, rank]` adapter A (HF's `lora_A` transposed).
8654        lora_a: Arc<[f32]>,
8655        /// `[rank, out_features]` adapter B (HF's `lora_B` transposed).
8656        lora_b: Arc<[f32]>,
8657        rank: usize,
8658        /// LoRA scaling factor; effective scale is `alpha / rank`.
8659        alpha: f32,
8660        in_features: usize,
8661        out_features: usize,
8662    },
8663}
8664
8665impl WeightStorage {
8666    /// Keep a GGUF weight tensor quantized (ROADMAP row 124): `bytes` is the tensor's block
8667    /// stream in GGUF's native `[out_features, in_features]` order. Returns `None` when the
8668    /// tensor must take the dequantize-to-f32 path instead: the format has no `QMatMul` kernel
8669    /// here (Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL, IQ4_XS and IQ3_S are admitted; `Q4_0` has its
8670    /// own variant; every other `GgmlDType` is declined BY NAME in the match below, so a new dtype is a
8671    /// compile error until someone decides), or
8672    /// `in_features` is not a whole number of blocks (32 for Q8_0, 256 for the K-quants), or the
8673    /// byte count is not `out_features * in_features / block * bytes_per_block`. A caller that
8674    /// 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.
8675    ///
8676    ///
8677    /// Every admitted type has a `QMatMul` arm on CPU and on Vulkan (ROADMAP row 119 wired Q3_K, Q5_K,
8678    /// IQ4_NL, IQ4_XS and IQ3_S there); the test `ggml_kept_types_are_wired` fails if a kept type is not
8679    /// listed by `fuel_vulkan_dispatch::vulkan_dispatch::qmatmul::qmatmul_wired`.
8680    pub fn from_ggml_bytes(
8681        dtype: fuel_ir::quantized::GgmlDType,
8682        bytes: &[u8],
8683        in_features: usize,
8684        out_features: usize,
8685    ) -> Option<Self> {
8686        use fuel_ir::quantized::GgmlDType;
8687        let qtype = match dtype {
8688            GgmlDType::Q8_0 => fuel_graph::QuantType::Q8_0,
8689            GgmlDType::Q4K => fuel_graph::QuantType::Q4_K_M,
8690            GgmlDType::Q6K => fuel_graph::QuantType::Q6K,
8691            GgmlDType::Q3K => fuel_graph::QuantType::Q3K,
8692            GgmlDType::Q5K => fuel_graph::QuantType::Q5K,
8693            GgmlDType::Iq4Nl => fuel_graph::QuantType::Iq4Nl,
8694            GgmlDType::Iq4Xs => fuel_graph::QuantType::Iq4Xs,
8695            GgmlDType::Iq3S => fuel_graph::QuantType::Iq3S,
8696            // Declined, each by name: no `QMatMul` kernel on any backend, or (Q4_0) a variant of its own.
8697            // No wildcard: a new `GgmlDType` must be admitted or declined here before this compiles.
8698            GgmlDType::F32
8699            | GgmlDType::F16
8700            | GgmlDType::BF16
8701            | GgmlDType::Q4_0
8702            | GgmlDType::Q4_1
8703            | GgmlDType::Q5_0
8704            | GgmlDType::Q5_1
8705            | GgmlDType::Q8_1
8706            | GgmlDType::Q2K
8707            | GgmlDType::Q8K
8708            | GgmlDType::Iq2Xxs
8709            | GgmlDType::Iq2Xs
8710            | GgmlDType::Iq3Xxs
8711            | GgmlDType::Iq1S
8712            | GgmlDType::Iq2S
8713            | GgmlDType::Iq1M
8714            | GgmlDType::Tq1_0
8715            | GgmlDType::Tq2_0
8716            | GgmlDType::Mxfp4
8717            | GgmlDType::Nvfp4 => return None,
8718        };
8719        let block = qtype.elements_per_block();
8720        if in_features == 0 || !in_features.is_multiple_of(block) {
8721            return None;
8722        }
8723        if bytes.len() != out_features * (in_features / block) * qtype.bytes_per_block() {
8724            return None;
8725        }
8726        // The graph const is U32 words; pad the tail to a whole word.
8727        let mut padded = bytes.to_vec();
8728        padded.resize(bytes.len().div_ceil(4) * 4, 0);
8729        let words: Vec<u32> = padded
8730            .as_chunks::<4>()
8731            .0
8732            .iter()
8733            .map(|c| u32::from_le_bytes(*c))
8734            .collect();
8735        Some(Self::Ggml {
8736            qtype,
8737            words: Arc::from(words),
8738            bytes_len: bytes.len(),
8739            in_features,
8740            out_features,
8741        })
8742    }
8743
8744    /// Bytes this weight holds in host memory (the adapter of a `WithLoRA` included). The
8745    /// instrument for "did this tensor stay quantized": a Q4_K weight is `n*k/256*144` bytes,
8746    /// the same tensor dequantized to `F32` is `n*k*4`.
8747    pub fn resident_bytes(&self) -> usize {
8748        match self {
8749            Self::F32(a) => a.len() * std::mem::size_of::<f32>(),
8750            Self::BF16(a) => a.len() * std::mem::size_of::<half::bf16>(),
8751            Self::Q4_0 { bytes_len, .. } | Self::Ggml { bytes_len, .. } => *bytes_len,
8752            Self::Awq(w) => {
8753                w.weight.len() * std::mem::size_of::<u32>()
8754                    + w.zeros.len() * std::mem::size_of::<u32>()
8755                    + w.scales.len() * std::mem::size_of::<half::f16>()
8756            }
8757            Self::WithLoRA {
8758                base,
8759                lora_a,
8760                lora_b,
8761                ..
8762            } => base.resident_bytes() + (lora_a.len() + lora_b.len()) * std::mem::size_of::<f32>(),
8763        }
8764    }
8765
8766    pub fn elem_count(&self) -> usize {
8767        match self {
8768            Self::F32(a) => a.len(),
8769            Self::BF16(a) => a.len(),
8770            // Logical element count for a Q4_0 weight matrix is n*k.
8771            Self::Q4_0 {
8772                in_features,
8773                out_features,
8774                ..
8775            }
8776            | Self::Ggml {
8777                in_features,
8778                out_features,
8779                ..
8780            } => *in_features * *out_features,
8781            Self::Awq(w) => w.ic * w.oc,
8782            Self::WithLoRA {
8783                in_features,
8784                out_features,
8785                ..
8786            } => *in_features * *out_features,
8787        }
8788    }
8789
8790    pub fn dtype(&self) -> fuel_ir::DType {
8791        match self {
8792            Self::F32(_) => fuel_ir::DType::F32,
8793            Self::BF16(_) => fuel_ir::DType::BF16,
8794            // Q4_0 surfaces as U32 at the graph level (raw bytes
8795            // reinterpreted). Callers that care about the "actual"
8796            // quantization type should match on the variant directly.
8797            Self::Q4_0 { .. } | Self::Ggml { .. } => fuel_ir::DType::U32,
8798            // AWQ surfaces as U32 for the same reason (packed nibbles).
8799            Self::Awq(_) => fuel_ir::DType::U32,
8800            // WithLoRA exposes the base's dtype (the LoRA adapter is
8801            // always F32 but activations are typed by the base weight).
8802            Self::WithLoRA { base, .. } => base.dtype(),
8803        }
8804    }
8805
8806    /// Emit a `Const` node on `anchor`'s graph matching this
8807    /// storage's dtype. Used everywhere the forward pass wraps a
8808    /// weight into a `Tensor`.
8809    ///
8810    /// For `Q4_0`, the emitted tensor is a 1-D `U32` const of length
8811    /// `bytes.len() / 4` holding the raw block byte stream. Callers
8812    /// must pair this with `Tensor::qmatmul` rather than `matmul`.
8813    ///
8814    /// Returns Err for `WithLoRA` — the base + LoRA update can only be
8815    /// applied via `apply_linear` so the right graph structure is built.
8816    pub fn const_like(
8817        &self,
8818        anchor: &Tensor,
8819        shape: Shape,
8820    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8821        match self {
8822            Self::F32(a) => anchor.const_f32_like(a.clone(), shape),
8823            Self::BF16(a) => anchor.const_bf16_like(a.clone(), shape),
8824            Self::Q4_0 { words, .. } | Self::Ggml { words, .. } => {
8825                let _ = shape; // shape arg unused — Q4_0 const is 1-D U32
8826                // Arc-clone the precomputed u32 view; no byte copy.
8827                anchor.const_u32_like(Arc::clone(words), Shape::from_dims(&[words.len()]))
8828            }
8829            Self::Awq(_) => Err(fuel_ir::Error::Msg(
8830                "WeightStorage::Awq::const_like is not supported — an AWQ weight is three operands \
8831                 (weight, zeros, scales), applied via apply_linear."
8832                    .into(),
8833            )
8834            .bt()),
8835            Self::WithLoRA { .. } => Err(fuel_ir::Error::Msg(
8836                "WeightStorage::WithLoRA::const_like is not supported \
8837                 — the base + LoRA update must be applied via \
8838                 apply_linear to produce the right graph structure."
8839                    .into(),
8840            )
8841            .bt()),
8842        }
8843    }
8844
8845    /// Produce `X @ W + bias` for this weight storage. Bias is a
8846    /// length-`out_features` Arc<[f32]> materialized fresh on the
8847    /// receiver's graph and broadcast across the leading dims of
8848    /// the output.
8849    ///
8850    /// Equivalent to the per-port `apply_linear_with_bias` helpers
8851    /// that several ports inlined — promoted here so call sites
8852    /// stop drifting.
8853    pub fn apply_linear_with_bias(
8854        &self,
8855        x: &Tensor,
8856        in_features: usize,
8857        out_features: usize,
8858        bias: std::sync::Arc<[f32]>,
8859    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8860        if bias.len() != out_features {
8861            // Was a `debug_assert_eq!` — i.e. compiled OUT of release builds,
8862            // so a release binary silently built a broadcast against a
8863            // wrong-length bias. A length mismatch is a checkpoint condition;
8864            // it errors in every profile now.
8865            return Err(fuel_ir::Error::Msg(format!(
8866                "apply_linear_with_bias: bias len ({}) != out_features ({out_features})",
8867                bias.len(),
8868            ))
8869            .bt());
8870        }
8871        let projected = self.apply_linear(x, in_features, out_features)?;
8872        let bias_t = projected.const_f32_like(bias, Shape::from_dims(&[out_features]))?;
8873        projected.broadcast_add(&bias_t)
8874    }
8875
8876    /// Produce `X @ W` (with optional bias) for this weight storage.
8877    /// Dispatches to `matmul` for F32/BF16 weights and to `qmatmul`
8878    /// for Q4_0. `x`'s dtype must be compatible with this weight's
8879    /// dtype per `matmul`'s gate: same-dtype homogeneous (e.g. BF16
8880    /// activations × BF16 weights — LlamaModel's BF16-throughout
8881    /// decode path, Phase D increment A) or `(x=F32, weight=BF16)`
8882    /// (f32-activation quantized-weight serving). `(x=BF16,
8883    /// weight=F32)` is NOT supported — cast the weight or the
8884    /// activation to match before calling.
8885    /// # Errors
8886    ///
8887    /// Returns a typed error rather than panicking on a dimension or dtype
8888    /// mismatch. This used to `.unwrap()` the inner `matmul`/`qmatmul` and
8889    /// `assert_eq!` the stored-vs-requested dimensions, which made a
8890    /// **production** path panic — a mismatched checkpoint (a GGUF whose
8891    /// stored shape disagrees with the model config) is a data condition, not
8892    /// a programming invariant, so it must surface as `Err`.
8893    pub fn apply_linear(
8894        &self,
8895        x: &Tensor,
8896        in_features: usize,
8897        out_features: usize,
8898    ) -> std::result::Result<Tensor, fuel_ir::Error> {
8899        // Build-time contract check, shared by every arm: a "linear with
8900        // `in_features`" requires x's trailing dim to BE `in_features`.
8901        // Checked here rather than at the ~620 call sites, and phrased so the
8902        // message names the projection instead of surfacing a bare matmul
8903        // shape error two layers down.
8904        let x_dims = x.shape().dims().to_vec();
8905        match x_dims.last() {
8906            Some(&k) if k == in_features => {}
8907            _ => {
8908                return Err(fuel_ir::Error::Msg(format!(
8909                    "apply_linear({in_features} -> {out_features}): input shape {x_dims:?} \
8910                     must have trailing dim {in_features}",
8911                ))
8912                .bt());
8913            }
8914        }
8915        match self {
8916            Self::F32(_) | Self::BF16(_) => {
8917                let w = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8918                x.matmul(&w)
8919            }
8920            Self::Q4_0 {
8921                in_features: expected_in,
8922                out_features: expected_out,
8923                ..
8924            } => {
8925                if *expected_in != in_features || *expected_out != out_features {
8926                    return Err(fuel_ir::Error::Msg(format!(
8927                        "WeightStorage::Q4_0 shape mismatch: stored \
8928                         [{expected_in}, {expected_out}], requested \
8929                         [{in_features}, {out_features}]",
8930                    ))
8931                    .bt());
8932                }
8933                let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8934                x.qmatmul(
8935                    &w_bytes,
8936                    fuel_graph::QuantType::Q4_0,
8937                    in_features,
8938                    out_features,
8939                )
8940            }
8941            Self::Ggml {
8942                qtype,
8943                in_features: expected_in,
8944                out_features: expected_out,
8945                ..
8946            } => {
8947                if *expected_in != in_features || *expected_out != out_features {
8948                    return Err(fuel_ir::Error::Msg(format!(
8949                        "WeightStorage::Ggml({qtype:?}) shape mismatch: stored                          [{expected_in}, {expected_out}], requested                          [{in_features}, {out_features}]",
8950                    ))
8951                    .bt());
8952                }
8953                let w_bytes = self.const_like(x, Shape::from_dims(&[in_features, out_features]))?;
8954                x.qmatmul(&w_bytes, *qtype, in_features, out_features)
8955            }
8956            Self::Awq(w) => {
8957                if w.ic != in_features || w.oc != out_features {
8958                    return Err(fuel_ir::Error::Msg(format!(
8959                        "WeightStorage::Awq shape mismatch: stored [{}, {}], requested [{in_features}, {out_features}]",
8960                        w.ic, w.oc,
8961                    ))
8962                    .bt());
8963                }
8964                // 8 is AutoAWQ's default launch tuning; the decompose path
8965                // ignores it.
8966                w.matmul(x, 8)
8967            }
8968            Self::WithLoRA {
8969                base,
8970                lora_a,
8971                lora_b,
8972                rank,
8973                alpha,
8974                in_features: expected_in,
8975                out_features: expected_out,
8976            } => {
8977                if *expected_in != in_features || *expected_out != out_features {
8978                    return Err(fuel_ir::Error::Msg(format!(
8979                        "WeightStorage::WithLoRA shape mismatch: stored \
8980                         [{expected_in}, {expected_out}], requested \
8981                         [{in_features}, {out_features}]",
8982                    ))
8983                    .bt());
8984                }
8985                // Base forward (F32, BF16, or Q4_0).
8986                let base_out = base.apply_linear(x, in_features, out_features)?;
8987                // Low-rank update: y += (alpha/rank) · x @ A @ B.
8988                let a_t =
8989                    x.const_f32_like(Arc::clone(lora_a), Shape::from_dims(&[in_features, *rank]))?;
8990                let b_t =
8991                    x.const_f32_like(Arc::clone(lora_b), Shape::from_dims(&[*rank, out_features]))?;
8992                let scale = *alpha as f64 / *rank as f64;
8993                // x: [*, in] → @A [*, rank] → @B [*, out] → scale → add base.
8994                let lora_path = Tensor {
8995                    inner: x.matmul(&a_t)?.matmul(&b_t)?.inner.mul_scalar(scale),
8996                };
8997                base_out.add(&lora_path)
8998            }
8999        }
9000    }
9001
9002    /// Data-determined-M variant of [`Self::apply_linear`]: computes only
9003    /// `row_count` rows of the capacity-buffer projection `x @ W`, the rest
9004    /// left zeroed — the per-expert sparse-MoE FFN path. `x` is a
9005    /// `[capacity, in_features]` buffer whose first `row_count` rows are the
9006    /// routed tokens; the returned `[capacity, out_features]` buffer's tail
9007    /// (rows `row_count..capacity`) stays exactly zero (see
9008    /// [`Tensor::matmul_dyn_m`]).
9009    ///
9010    /// F32-only (mirrors `matmul_dyn_m`); other weight encodings surface a
9011    /// typed build-time error. No bias is applied — a bias would fill the
9012    /// un-computed tail, which the sparse-MoE caller relies on being zero
9013    /// for a correct `index_add` scatter-back.
9014    pub fn apply_linear_dyn_m(
9015        &self,
9016        x: &Tensor,
9017        in_features: usize,
9018        out_features: usize,
9019        row_count: fuel_ir::DynScalar,
9020    ) -> std::result::Result<Tensor, fuel_ir::Error> {
9021        match self {
9022            Self::F32(_) => {
9023                // const_like only errors on WithLoRA; the F32 arm is infallible.
9024                let w = self
9025                    .const_like(x, Shape::from_dims(&[in_features, out_features]))
9026                    .expect("apply_linear_dyn_m F32 arm: const_like cannot fail for F32");
9027                x.matmul_dyn_m(&w, row_count)
9028            }
9029            other => Err(fuel_ir::Error::Msg(format!(
9030                "apply_linear_dyn_m: sparse-MoE dispatch is F32-only today, got {:?} \
9031                 weight (cast the expert weights to F32)",
9032                other.dtype(),
9033            ))
9034            .bt()),
9035        }
9036    }
9037
9038    /// Wrap this weight storage with a LoRA adapter. Asserts that the
9039    /// adapter shapes match `in_features`/`out_features`. Panics if the
9040    /// base is already a `WithLoRA` (nested adapters aren't supported;
9041    /// merge them explicitly if needed).
9042    pub fn with_lora(
9043        self,
9044        lora_a: Arc<[f32]>,
9045        lora_b: Arc<[f32]>,
9046        rank: usize,
9047        alpha: f32,
9048        in_features: usize,
9049        out_features: usize,
9050    ) -> Self {
9051        assert_eq!(
9052            lora_a.len(),
9053            in_features * rank,
9054            "lora_a length {} does not match in_features ({in_features}) × rank ({rank}) = {}",
9055            lora_a.len(),
9056            in_features * rank,
9057        );
9058        assert_eq!(
9059            lora_b.len(),
9060            rank * out_features,
9061            "lora_b length {} does not match rank ({rank}) × out_features ({out_features}) = {}",
9062            lora_b.len(),
9063            rank * out_features,
9064        );
9065        assert!(
9066            !matches!(self, Self::WithLoRA { .. }),
9067            "with_lora: base is already WithLoRA (nested adapters unsupported)",
9068        );
9069        Self::WithLoRA {
9070            base: Box::new(self),
9071            lora_a,
9072            lora_b,
9073            rank,
9074            alpha,
9075            in_features,
9076            out_features,
9077        }
9078    }
9079}
9080
9081// Auto-conversions so code that was storing `Arc<[f32]>` keeps
9082// compiling through the refactor — the LayerWeights field type
9083// widened to WeightStorage but ergonomics don't regress.
9084impl From<Arc<[f32]>> for WeightStorage {
9085    fn from(a: Arc<[f32]>) -> Self {
9086        Self::F32(a)
9087    }
9088}
9089impl From<Vec<f32>> for WeightStorage {
9090    fn from(v: Vec<f32>) -> Self {
9091        Self::F32(Arc::from(v))
9092    }
9093}
9094impl From<Arc<[half::bf16]>> for WeightStorage {
9095    fn from(a: Arc<[half::bf16]>) -> Self {
9096        Self::BF16(a)
9097    }
9098}
9099impl From<Vec<half::bf16>> for WeightStorage {
9100    fn from(v: Vec<half::bf16>) -> Self {
9101        Self::BF16(Arc::from(v))
9102    }
9103}
9104
9105/// Per-layer weights of a LLaMA transformer block. All tensors are
9106/// stored as `Arc<[f32]>` so they can be loaded once and shared across
9107/// every forward pass with zero copy — each call to
9108/// `LlamaModel::forward` clones the `Arc` (a refcount bump) when it
9109/// builds fresh const nodes for this layer.
9110///
9111/// LLaMA proper has no biases anywhere in the attention block, so the
9112/// `*_bias` fields are `None` for LLaMA family models. Qwen2 and a few
9113/// related architectures do add biases on Q/K/V (but not on the output
9114/// projection), so the loader stores them here when the safetensors
9115/// file contains them.
9116#[derive(Debug, Clone)]
9117pub struct LayerWeights {
9118    /// `[dim, dim]` query projection. Supports bf16 or f32.
9119    pub attn_q: WeightStorage,
9120    /// `[dim]` query projection bias (Qwen2-style; LLaMA has none).
9121    pub attn_q_bias: Option<Arc<[f32]>>,
9122    /// `[dim, dim]` key projection.
9123    pub attn_k: WeightStorage,
9124    /// `[kv_dim]` key projection bias.
9125    pub attn_k_bias: Option<Arc<[f32]>>,
9126    /// `[dim, dim]` value projection.
9127    pub attn_v: WeightStorage,
9128    /// `[kv_dim]` value projection bias.
9129    pub attn_v_bias: Option<Arc<[f32]>>,
9130    /// `[dim, dim]` output projection.
9131    pub attn_o: WeightStorage,
9132    /// `[dim, ffn_dim]` gate projection for SwiGLU.
9133    pub ffn_gate: WeightStorage,
9134    /// `[dim, ffn_dim]` up projection for SwiGLU.
9135    pub ffn_up: WeightStorage,
9136    /// `[ffn_dim, dim]` down projection for SwiGLU.
9137    pub ffn_down: WeightStorage,
9138    /// `[dim]` RmsNorm gain for the pre-attention norm. Stays f32
9139    /// — norm gains are small and precision-sensitive.
9140    pub attn_norm_gain: Arc<[f32]>,
9141    /// `[dim]` RmsNorm gain for the pre-FFN norm.
9142    pub ffn_norm_gain: Arc<[f32]>,
9143}
9144
9145pub fn invalidate_decode_pair_if_stale<C>(
9146    session: &mut Option<crate::inference_context::DecodeSession>,
9147    captured: &mut Option<C>,
9148    ctx: &mut InferenceContext,
9149    seq: usize,
9150    max_seq_len: Option<usize>,
9151    cache_dtype: DType,
9152    n_layers: usize,
9153    shape_key: u64,
9154    kv: &dyn crate::inference_context::KvRebindSource,
9155    drop_session: impl FnOnce(
9156        &mut Option<crate::inference_context::DecodeSession>,
9157        &mut InferenceContext,
9158    ),
9159) -> SessionDisposition {
9160    refresh_decode_session(
9161        session,
9162        ctx,
9163        seq,
9164        max_seq_len,
9165        cache_dtype,
9166        n_layers,
9167        shape_key,
9168        kv,
9169        // Reader before owner — see the doc comment above. This fires for a
9170        // re-bind as well as a drop: a capture records FIXED device addresses
9171        // drawn from `base_cache`, and `rebind_kv` replaces some of them.
9172        || *captured = None,
9173        drop_session,
9174    )
9175}
9176
9177/// What [`refresh_decode_session`] did to the held plan.
9178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9179pub enum SessionDisposition {
9180    /// There was no held plan; nothing to do.
9181    Absent,
9182    /// The plan is valid for this step and was left alone.
9183    Kept,
9184    /// The KV allocation changed and the plan was re-bound onto it (GAP-028).
9185    /// Any reader of the plan's device addresses has been retired.
9186    Rebound,
9187    /// The plan was retired. `Some(refusal)` means a re-bind was attempted and
9188    /// declined — carried so a caller (or a test) can distinguish "refused for
9189    /// the right reason" from "refused because nothing was tried".
9190    Dropped(Option<crate::inference_context::RebindRefusal>),
9191}
9192
9193/// **The single decision point for what happens to a held decode plan at the
9194/// top of a decode step.** Every model routes through here, so they cannot
9195/// drift on what "stale" means — the reason this was a shared free function
9196/// before GAP-028, and more so now that the answer has three outcomes.
9197///
9198/// Order of business, and why it is this order:
9199///
9200/// 1. Ask [`crate::inference_context::DecodeSession::validity_for`] — ONE comparison list, so "is it
9201///    valid" and "is only the allocation different" cannot disagree.
9202/// 2. On anything but `Valid`, retire readers FIRST via `on_invalidate`. A
9203///    `CapturedDecodeSession` replays a recorded CUDA graph over FIXED device
9204///    addresses drawn from the session's `base_cache`; both a drop and a
9205///    re-bind make some of those addresses stale, and a replay against stale
9206///    addresses is silently wrong logits at full speed. Retiring before
9207///    touching the owner means no replay can observe a half-updated plan.
9208///    Note this fires *before* the re-bind is attempted, not after it
9209///    succeeds: a capture is worthless either way, and clearing it early keeps
9210///    the ordering true without depending on the outcome.
9211/// 3. Try the guarded re-bind. It may refuse; a refusal is not an error.
9212/// 4. Otherwise drop, so the caller's first-decode-token arm rebuilds.
9213///
9214/// Generic in nothing — the capture rides in the `on_invalidate` closure,
9215/// which is what lets this compile (and therefore be CPU-tested) without the
9216/// `cuda` feature.
9217pub fn refresh_decode_session(
9218    session: &mut Option<crate::inference_context::DecodeSession>,
9219    ctx: &mut InferenceContext,
9220    seq: usize,
9221    max_seq_len: Option<usize>,
9222    cache_dtype: DType,
9223    n_layers: usize,
9224    shape_key: u64,
9225    kv: &dyn crate::inference_context::KvRebindSource,
9226    on_invalidate: impl FnOnce(),
9227    drop_session: impl FnOnce(
9228        &mut Option<crate::inference_context::DecodeSession>,
9229        &mut InferenceContext,
9230    ),
9231) -> SessionDisposition {
9232    use crate::inference_context::PlanValidity;
9233
9234    let verdict = match (session.as_ref(), max_seq_len) {
9235        (None, _) => return SessionDisposition::Absent,
9236        (Some(s), Some(msl)) => {
9237            s.validity_for(seq, msl, n_layers, cache_dtype, shape_key, kv.alloc_id())
9238        }
9239        // A cache with no pre-allocated capacity cannot back a held plan at
9240        // all (the graph bakes `max_seq_len` into its KV Const shapes).
9241        (Some(_), None) => PlanValidity::Stale,
9242    };
9243    if verdict == PlanValidity::Valid {
9244        return SessionDisposition::Kept;
9245    }
9246
9247    on_invalidate();
9248
9249    let refusal = if verdict == PlanValidity::AllocationChanged {
9250        match session.as_mut().map(|s| s.rebind_kv(kv)) {
9251            Some(Ok(())) => return SessionDisposition::Rebound,
9252            Some(Err(r)) => Some(r),
9253            // Unreachable: `verdict` was computed from a `Some` session and
9254            // nothing above takes it. Handled rather than `expect`ed because
9255            // this is a production path.
9256            None => None,
9257        }
9258    } else {
9259        None
9260    };
9261
9262    drop_session(session, ctx);
9263    SessionDisposition::Dropped(refusal)
9264}
9265
9266pub fn build_decode_causal_mask(cached_len: usize, seq: usize, max_seq_len: usize) -> Vec<f32> {
9267    let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9268    for q_idx in 0..seq {
9269        let abs_q = cached_len + q_idx;
9270        for k_idx in (abs_q + 1)..max_seq_len {
9271            mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9272        }
9273    }
9274    mask_data
9275}
9276
9277/// Sliding-window sibling of [`build_decode_causal_mask`] — the decode-time
9278/// mask for a layer that attends only to the most recent `window` positions.
9279///
9280/// # Why this exists (GAP-029 increment 3)
9281///
9282/// The decode path has always built **one** mask per model, because `LlamaModel`
9283/// and `PhiModel` — the only two carriers — have no per-layer mask variation
9284/// (measured: **zero** `sliding_window` hits in this file, against a positive
9285/// control of hits in five sibling model files). **Four of the six families
9286/// GAP-029 increment 3 ports do vary per layer**, three of them via a sliding
9287/// window: `Qwen2` (`lazy_qwen2.rs:249-251`), `Qwen3` (`lazy_qwen3.rs:172`) and
9288/// `Qwen3Moe` (`lazy_qwen3_moe.rs:192`) all select per layer on
9289/// `use_sliding_window && layer_idx < max_window_layers`.
9290///
9291/// # The predicate, and why it is stated against the prefill path
9292///
9293/// The shipped **prefill** mask for these families is `j > i || j + window <= i`
9294/// over absolute positions (`lazy_qwen2.rs:271`). Decode must agree with it
9295/// position-for-position, or a model silently changes behaviour at the
9296/// prefill→decode boundary. Here the query's absolute position is
9297/// `cached_len + q_idx` and the key's is `k_idx`, giving the same two clauses:
9298/// causal (`k_idx > abs_q`) and window (`k_idx + window <= abs_q`).
9299///
9300/// `window >= max_seq_len` makes the window clause unsatisfiable, so the result
9301/// is exactly [`build_decode_causal_mask`] — the property that lets a family
9302/// with the window disabled share the dense path rather than a near-copy of it.
9303///
9304/// # Status: LIVE. `#[allow(dead_code)]` removed 2026-08-13 — this has a caller.
9305///
9306/// It landed ahead of its consumer with its correctness established
9307/// independently (see the born-red record in `decode_mask_tests`), under an
9308/// architect-owned checkpoint: *land family 1 or the function is deleted*.
9309/// GAP-029 increment 3 landed `Qwen2Model`'s decode path, and
9310/// [`crate::persistent_decode::build_decode_mask_variants`] calls this for every
9311/// windowed mask variant — so the attribute is gone rather than renewed.
9312///
9313/// It is now on the live decode path of the three windowed families as they
9314/// arrive (`Qwen2Model` today; `Qwen3Model`, `Qwen3MoeModel` next), reached
9315/// through `MaskPlan::split_window`.
9316pub fn build_decode_causal_mask_windowed(
9317    cached_len: usize,
9318    seq: usize,
9319    max_seq_len: usize,
9320    window: usize,
9321) -> Vec<f32> {
9322    let mut mask_data = vec![0.0_f32; seq * max_seq_len];
9323    for q_idx in 0..seq {
9324        let abs_q = cached_len + q_idx;
9325        for k_idx in 0..max_seq_len {
9326            // Causal: no future keys. Window: nothing older than `window` back.
9327            if k_idx > abs_q || k_idx + window <= abs_q {
9328                mask_data[q_idx * max_seq_len + k_idx] = f32::NEG_INFINITY;
9329            }
9330        }
9331    }
9332    mask_data
9333}
9334
9335#[cfg(test)]
9336mod decode_mask_tests {
9337    use super::{build_decode_causal_mask, build_decode_causal_mask_windowed};
9338
9339    /// Render a mask row as `1` for attend / `0` for masked, so a failure
9340    /// prints the shape of the disagreement rather than a wall of `-inf`.
9341    fn attendable(row: &[f32]) -> Vec<u8> {
9342        row.iter().map(|&v| u8::from(v == 0.0)).collect()
9343    }
9344
9345    /// **The discriminating test.** Hand-computed ground truth, NOT a
9346    /// re-derivation of the implementation's own formula: at `cached_len = 3`,
9347    /// `seq = 1`, `max_seq_len = 6`, `window = 2` the single query sits at
9348    /// absolute position 3 and may attend to positions `{2, 3}` — 3 itself
9349    /// (causal boundary) and 2 (one step back, inside a window of 2). Positions
9350    /// 0 and 1 fall out of the window; 4 and 5 are the unwritten future tail.
9351    #[test]
9352    fn windowed_mask_excludes_positions_older_than_the_window() {
9353        let m = build_decode_causal_mask_windowed(3, 1, 6, 2);
9354        assert_eq!(
9355            attendable(&m),
9356            vec![0, 0, 1, 1, 0, 0],
9357            "window=2 at absolute position 3 must attend to exactly {{2, 3}}",
9358        );
9359    }
9360
9361    /// Multi-row (prefill-shaped) ground truth, also by hand: `cached_len = 1`,
9362    /// `seq = 2`, `window = 2` puts the queries at absolute positions 1 and 2,
9363    /// attending to `{0, 1}` and `{1, 2}` respectively. Guards the `q_idx`
9364    /// → `abs_q` offset, which a `seq == 1` test cannot see at all.
9365    #[test]
9366    fn windowed_mask_offsets_each_row_by_cached_len() {
9367        let m = build_decode_causal_mask_windowed(1, 2, 5, 2);
9368        assert_eq!(
9369            attendable(&m[0..5]),
9370            vec![1, 1, 0, 0, 0],
9371            "row 0 = abs pos 1"
9372        );
9373        assert_eq!(
9374            attendable(&m[5..10]),
9375            vec![0, 1, 1, 0, 0],
9376            "row 1 = abs pos 2"
9377        );
9378    }
9379
9380    /// **Non-discrimination control, and it is what keeps the two tests above
9381    /// meaningful.** A window at least as wide as the capacity cannot mask
9382    /// anything the causal clause does not already mask, so the windowed builder
9383    /// must reproduce the dense one byte-for-byte. This passes under BOTH a
9384    /// correct implementation and one that ignores `window` entirely — so it
9385    /// certifies that the suite is not simply broken, and it must NOT be read as
9386    /// evidence that the window works. (Same role as the positive control that
9387    /// stayed `ok` in increment 2a's sabotage record.)
9388    #[test]
9389    fn window_wider_than_capacity_is_byte_identical_to_the_dense_mask() {
9390        for (cached_len, seq, max_seq_len) in [(0, 1, 8), (3, 1, 8), (0, 4, 8), (2, 3, 8)] {
9391            let dense = build_decode_causal_mask(cached_len, seq, max_seq_len);
9392            let windowed =
9393                build_decode_causal_mask_windowed(cached_len, seq, max_seq_len, max_seq_len);
9394            assert_eq!(
9395                dense, windowed,
9396                "window == max_seq_len must equal dense at \
9397                 (cached_len={cached_len}, seq={seq}, max_seq_len={max_seq_len})",
9398            );
9399        }
9400    }
9401
9402    /// Decode must agree with the **shipped prefill** mask position-for-position,
9403    /// or a windowed model changes behaviour at the prefill→decode boundary.
9404    /// This replays `lazy_qwen2.rs:265-277`'s predicate over a full prefill of
9405    /// length `n`, then asserts that decoding position `p` with `cached_len = p`
9406    /// reproduces prefill row `p`. The prefill mask is `[seq, seq]` and the
9407    /// decode mask `[1, max_seq_len]`, so only the first `n` keys are comparable
9408    /// — the tail beyond `n` is the unwritten capacity the prefill mask has no
9409    /// opinion about.
9410    #[test]
9411    fn decode_row_matches_the_prefill_mask_row_at_the_same_position() {
9412        let (n, window, max_seq_len) = (6_usize, 3_usize, 10_usize);
9413
9414        // Qwen2's prefill predicate, transcribed from `build_layer_mask`.
9415        let mut prefill = vec![0.0_f32; n * n];
9416        for i in 0..n {
9417            for j in 0..n {
9418                if j > i || j + window <= i {
9419                    prefill[i * n + j] = f32::NEG_INFINITY;
9420                }
9421            }
9422        }
9423
9424        for p in 0..n {
9425            let decode = build_decode_causal_mask_windowed(p, 1, max_seq_len, window);
9426            assert_eq!(
9427                attendable(&decode[0..n]),
9428                attendable(&prefill[p * n..(p + 1) * n]),
9429                "decode at cached_len={p} must match prefill row {p}",
9430            );
9431            assert!(
9432                decode[n..].iter().all(|&v| v == f32::NEG_INFINITY),
9433                "the unwritten tail beyond position {n} must stay masked",
9434            );
9435        }
9436    }
9437
9438    // =======================================================================
9439    // BORN-RED RECORD (2026-08-13, GAP-029 increment 3)
9440    //
9441    // These tests were run FIRST against a deliberately wrong body — the
9442    // "old fabrication in the new shape": `build_decode_causal_mask_windowed`
9443    // returning `build_decode_causal_mask(..)` and ignoring `window`, which is
9444    // precisely what a single-mask decode port computes today. That makes the
9445    // red state prove *windowing vs dense* rather than merely proving the tests
9446    // execute.
9447    //
9448    //   windowed_mask_excludes_positions_older_than_the_window   FAILED
9449    //       left [1, 1, 1, 1, 0, 0]  right [0, 0, 1, 1, 0, 0]
9450    //   windowed_mask_offsets_each_row_by_cached_len             FAILED
9451    //       left [1, 1, 1, 0, 0]     right [0, 1, 1, 0, 0]
9452    //   decode_row_matches_the_prefill_mask_row_at_the_same_position FAILED
9453    //       left [1, 1, 1, 1, 0, 0]  right [0, 1, 1, 1, 0, 0]
9454    //   window_wider_than_capacity_is_byte_identical_to_the_dense_mask  ok
9455    //   test result: FAILED. 1 passed; 3 failed
9456    //
9457    // The `ok` line is load-bearing in BOTH directions and is the reason the
9458    // control exists: it holds under the correct body AND under the dense
9459    // fabrication, so (a) the suite is demonstrably not simply broken, and
9460    // (b) it must never be cited as evidence that windowing works. Only the
9461    // three that moved carry that claim.
9462    //
9463    // After the flip: `4 passed; 0 failed`, on a run reporting a 53.44s
9464    // compile — i.e. a rebuilt binary, not a cached one. A passing run without
9465    // confirmed recompilation would have certified nothing.
9466    //
9467    // WHAT THIS DOES **NOT** ESTABLISH, stated because the next reader will be
9468    // wiring this into a decode path: these are tests of the MASK BYTES ONLY.
9469    // No decode has yet been run with a windowed mask, so "a single-mask decode
9470    // port is silently wrong for Qwen2/Qwen3/Qwen3Moe" remains an INFERENCE
9471    // from the mask's meaning — argued from the fact that one
9472    // `[1, 1, seq, max_seq_len]` Const cannot express two layer groups. The
9473    // logits-level born-red against Qwen2's live mixed config
9474    // (`use_sliding_window: true, max_window_layers: 1` over 2 layers,
9475    // `lazy_qwen2.rs:441-443`) is the measurement that would settle it, and it
9476    // is NOT in this change.
9477    // =======================================================================
9478}
9479
9480/// Build a [`fuel_dispatch::decode_flash::DecodeFlashSpec`] from a decode
9481/// attention region's tensor handles and offer the optimizer-owned CUDA
9482/// flash-decode arm on the shared graph.
9483///
9484/// This is the model-layer WIRING for [`fuel_dispatch::decode_flash::offer_decode_flash_arm`]: it supplies
9485/// the region's tensor handles + the live attended-prefix `k_len` (as
9486/// `Sym(attended_len_sym)`, resolved per-token via the `SymEnv`) — data the
9487/// model alone knows — while every strategic decision (the shape/dtype/config
9488/// gate, the capability gate, the CUDA pin, the `Op::Branch` construction)
9489/// stays in the dispatch layer. The region is always **causal** with no
9490/// window / softcap / ALiBi (the LlamaModel decode shape).
9491///
9492/// - `q` — the RoPE'd query (`[B, Hq, 1, D]` in decode), also the branch
9493///   diverge point;
9494/// - `k` / `v` — the post-`WriteSlice` capacity KV buffers (`[B, Hkv,
9495///   capacity, D]`);
9496/// - `decomposed_out` — the region's attention output (arm 0 / the oracle);
9497/// - `reconverge` — the sole consumer of `decomposed_out` (the merge).
9498///
9499/// Returns `Ok(None)` (graph untouched, byte-identical to today) whenever the
9500/// emitter's gate declines — f32/f64 dtype, `seq_q != 1` (prefill),
9501/// `head_dim > 128`, or a non-CUDA / kernel-absent topology. Never panics.
9502/// Translate a Fuel sliding-window width into the FA-v2 `window_size_*`
9503/// convention the CUDA flash path speaks.
9504///
9505/// Fuel's mask predicate is `j > i || j + window <= i`, i.e. query `i` attends
9506/// keys `j ∈ [i - window + 1, i]` — **`window - 1` positions LEFT and `0`
9507/// RIGHT**. FA-v2 reads `is_causal` as `window_size_right == 0 &&
9508/// window_size_left < 0`, and treats *both* bounds `>= 0` as opting into local
9509/// attention (`fuel-cuda-backend/src/flash_attn.rs::translate_window`).
9510///
9511/// `None` (a dense layer) stays `(None, None)` — plain causal, which is what
9512/// every non-windowed family wants and what the decode kernel implements.
9513///
9514/// The `w - 1` is saturating: a nonsensical `window == 0` yields `Some(0)`,
9515/// which the admissibility gate rejects along with every other window. It never
9516/// silently becomes "no window".
9517pub fn flash_window_bounds(window: Option<usize>) -> (Option<usize>, Option<usize>) {
9518    match window {
9519        None => (None, None),
9520        Some(w) => (Some(w.saturating_sub(1)), Some(0)),
9521    }
9522}
9523
9524// 11 independent graph handles (q/k/v/decomposed/reconverge node ids) plus the
9525// scalar rewrite parameters (scale, attended-len sym, window, softcap, backend
9526// capability) for one flash-decode-arm offer. Each is a distinct graph node or
9527// scalar, not a bundle-able struct. Exceeds even the raised (10) threshold.
9528pub fn offer_flash_decode_arm_for_region(
9529    graph: &fuel_graph::SharedGraph,
9530    q: fuel_graph::NodeId,
9531    k: fuel_graph::NodeId,
9532    v: fuel_graph::NodeId,
9533    decomposed_out: fuel_graph::NodeId,
9534    reconverge: fuel_graph::NodeId,
9535    softmax_scale: f32,
9536    attended_len_sym: fuel_ir::SymId,
9537    attn_window: Option<usize>,
9538    softcap: Option<f32>,
9539    cap: fuel_dispatch::decode_flash::FlashArmCapability,
9540) -> crate::Result<Option<fuel_graph::NodeId>> {
9541    use fuel_dispatch::decode_flash::{DecodeFlashSpec, offer_decode_flash_arm};
9542    let (window_size_left, window_size_right) = flash_window_bounds(attn_window);
9543    let spec = DecodeFlashSpec {
9544        q,
9545        k,
9546        v,
9547        alibi: None,
9548        softmax_scale,
9549        causal: true,
9550        // ⚠️ GAP-194: these three were hardcoded `None`. That is TRUE for
9551        // `LlamaModel` — no window, no softcap — and would be a LIE for a
9552        // windowed or softcapped family, whose arm would then attend the whole
9553        // prefix and skip the cap, silently. A guard must not encode a claim
9554        // that is false: the caller states them, and the admissibility gate
9555        // declines what `flash_decoding` cannot implement.
9556        window_size_left,
9557        window_size_right,
9558        softcap,
9559        k_len: fuel_ir::DynScalar::Sym(attended_len_sym),
9560        decomposed_out,
9561        reconverge,
9562    };
9563    let mut g = graph.write().map_err(|_| {
9564        fuel_ir::Error::Msg("graph lock poisoned during flash-arm offer".into()).bt()
9565    })?;
9566    offer_decode_flash_arm(&mut g, &spec, cap)
9567}
9568
9569pub fn apply_affine_rms_norm(x: &Tensor, gain: &Arc<[f32]>, dim: usize, eps: f64) -> Tensor {
9570    assert_eq!(
9571        gain.len(),
9572        dim,
9573        "apply_affine_rms_norm: gain length must equal dim"
9574    );
9575    let normalized = x.rms_norm_last_dim(eps).unwrap();
9576    // The gain is always stored f32 (norm gains are precision-sensitive —
9577    // see `LayerWeights::attn_norm_gain`'s doc) but must be materialized
9578    // in `x`'s dtype: under BF16-throughout decode (Phase D increment A)
9579    // `x` is BF16 and `broadcast_mul` asserts dtype equality, so an f32
9580    // gain would panic. No-op conversion for f32 activations.
9581    let gain_t = x
9582        .const_like_dtype(gain, Shape::from_dims(&[dim]), x.dtype())
9583        .expect("apply_affine_rms_norm: activation dtype must be F32 or BF16");
9584    normalized.broadcast_mul(&gain_t).unwrap()
9585}
9586
9587// ---- HuggingFace Hub and safetensors weight loading ----------------------
9588
9589/// Load a tensor by name from a `MmapedSafetensors` as a flat
9590/// `Vec<f32>`, converting from whatever dtype the file stores it in.
9591/// Handles `F32`, `F64`, `BF16`, and `F16` — the dtypes real LLaMA
9592/// weights use on disk. Returns an error for unsupported dtypes.
9593pub fn load_tensor_as_f32(
9594    st: &fuel_formats::safetensors::MmapedSafetensors,
9595    name: &str,
9596) -> crate::Result<Vec<f32>> {
9597    use safetensors::Dtype;
9598    let view = st.get(name)?;
9599    let bytes = view.data();
9600    match view.dtype() {
9601        Dtype::F32 => {
9602            let mut out = Vec::with_capacity(bytes.len() / 4);
9603            for chunk in bytes.as_chunks::<4>().0.iter() {
9604                out.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
9605            }
9606            Ok(out)
9607        }
9608        Dtype::F64 => {
9609            let mut out = Vec::with_capacity(bytes.len() / 8);
9610            for chunk in bytes.as_chunks::<8>().0.iter() {
9611                let arr: [u8; 8] = *chunk;
9612                out.push(f64::from_le_bytes(arr) as f32);
9613            }
9614            Ok(out)
9615        }
9616        Dtype::BF16 => {
9617            let mut out = Vec::with_capacity(bytes.len() / 2);
9618            for chunk in bytes.as_chunks::<2>().0.iter() {
9619                let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9620                out.push(half::bf16::from_bits(raw).to_f32());
9621            }
9622            Ok(out)
9623        }
9624        Dtype::F16 => {
9625            let mut out = Vec::with_capacity(bytes.len() / 2);
9626            for chunk in bytes.as_chunks::<2>().0.iter() {
9627                let raw = u16::from_le_bytes([chunk[0], chunk[1]]);
9628                out.push(half::f16::from_bits(raw).to_f32());
9629            }
9630            Ok(out)
9631        }
9632        other => {
9633            crate::bail!("load_tensor_as_f32: unsupported dtype {other:?} for tensor {name:?}",)
9634        }
9635    }
9636}
9637
9638/// Load a tensor by name and physically transpose it from `[out, in]`
9639/// (HuggingFace layout) to `[in, out]` (fuel-graph's layout for
9640/// `x @ W` where `W` is `[in, out]`). Linear-layer weights in HF
9641/// transformers are stored as `[out_features, in_features]`, so every
9642/// call to this function is effectively "give me that matrix as I'd
9643/// use it in `matmul`."
9644pub fn load_transposed_matrix(
9645    st: &fuel_formats::safetensors::MmapedSafetensors,
9646    name: &str,
9647    out_features: usize,
9648    in_features: usize,
9649) -> crate::Result<Vec<f32>> {
9650    let flat = load_tensor_as_f32(st, name)?;
9651    if flat.len() != out_features * in_features {
9652        crate::bail!(
9653            "load_transposed_matrix: tensor {name:?} has {} elements, expected {} ({out_features} × {in_features})",
9654            flat.len(),
9655            out_features * in_features,
9656        );
9657    }
9658    // HF layout: flat[i * in_features + j] is W[i, j] for (out i, in j).
9659    // Target layout: out[j * out_features + i] so that indexing `[j, i]`
9660    // in row-major gives the same W[i, j] — i.e. out has shape [in, out].
9661    let mut out = vec![0.0_f32; out_features * in_features];
9662    for i in 0..out_features {
9663        for j in 0..in_features {
9664            out[j * out_features + i] = flat[i * in_features + j];
9665        }
9666    }
9667    Ok(out)
9668}
9669
9670/// Transposed-matrix loader that preserves source dtype. For
9671/// safetensors files saved with bf16 weights, returns
9672/// `WeightStorage::BF16` and never materializes an f32 copy — the
9673/// 2× memory saving vs `load_transposed_matrix` comes from here.
9674/// f32 and other source dtypes still go through the f32 upcast path
9675/// for safety; extending this to preserve f16 is a one-line change
9676/// when a consumer wants it.
9677///
9678/// The transpose itself is done in whatever dtype we're keeping:
9679/// read bf16 elements from the file, place them in the transposed
9680/// target buffer, no conversion.
9681pub fn load_transposed_matrix_preserve_dtype(
9682    st: &fuel_formats::safetensors::MmapedSafetensors,
9683    name: &str,
9684    out_features: usize,
9685    in_features: usize,
9686) -> crate::Result<WeightStorage> {
9687    use safetensors::Dtype;
9688    let view = st.get(name)?;
9689    let bytes = view.data();
9690    let expected = out_features * in_features;
9691    match view.dtype() {
9692        Dtype::BF16 => {
9693            if bytes.len() != expected * 2 {
9694                crate::bail!(
9695                    "load_transposed_matrix_preserve_dtype: bf16 tensor {name:?} has {} bytes, expected {}",
9696                    bytes.len(),
9697                    expected * 2,
9698                );
9699            }
9700            // Reinterpret input as [out_features, in_features] of
9701            // bf16; write transposed layout.
9702            let mut out = vec![half::bf16::ZERO; expected];
9703            for i in 0..out_features {
9704                for j in 0..in_features {
9705                    let src_off = (i * in_features + j) * 2;
9706                    let bits = u16::from_le_bytes([bytes[src_off], bytes[src_off + 1]]);
9707                    out[j * out_features + i] = half::bf16::from_bits(bits);
9708                }
9709            }
9710            Ok(WeightStorage::BF16(Arc::from(out)))
9711        }
9712        _ => {
9713            // F32, F64, F16 all fall through to the f32 upcast path.
9714            // Non-f32 source types still benefit from being readable;
9715            // they just lose the "weights stay compact" win.
9716            let flat = load_transposed_matrix(st, name, out_features, in_features)?;
9717            Ok(WeightStorage::F32(Arc::from(flat)))
9718        }
9719    }
9720}
9721
9722/// Sampling strategy for decode loops.
9723#[derive(Debug, Clone, Copy, Default)]
9724pub enum SamplingStrategy {
9725    /// Greedy: always pick the highest-probability token.
9726    #[default]
9727    Greedy,
9728    /// Temperature-scaled sampling with a deterministic seed. `temp`
9729    /// is the softmax temperature (`1.0` is unscaled, `temp <= 0.0` or NaN is
9730    /// greedy, higher values spread probability mass).
9731    /// The seed makes sampling reproducible.
9732    Temperature { temp: f32, seed: u64 },
9733}
9734
9735fn argmax_logits(logits: &[f32]) -> u32 {
9736    let (i, _) = logits
9737        .iter()
9738        .enumerate()
9739        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
9740        .expect("sample_logits: empty logits");
9741    i as u32
9742}
9743
9744/// Pick the next token from a logits vector using the configured
9745/// sampling strategy. Pulled out of `generate` so both the cached and
9746/// future non-cached callers can share it.
9747pub fn sample_logits(logits: &[f32], strategy: SamplingStrategy, rng_state: &mut u64) -> u32 {
9748    match strategy {
9749        SamplingStrategy::Greedy => argmax_logits(logits),
9750        // `temp <= 0.0` (and NaN) is the greedy limit: documented as "effectively greedy". It
9751        // used to scale by 1.0 and sample from the unscaled softmax.
9752        SamplingStrategy::Temperature { temp, .. } if temp.is_nan() || temp <= 0.0 => {
9753            argmax_logits(logits)
9754        }
9755        SamplingStrategy::Temperature { temp, .. } => {
9756            // Stable softmax over temperature-scaled logits,
9757            // then a deterministic multinomial draw.
9758            let inv_temp = 1.0 / temp;
9759            let scaled: Vec<f32> = logits.iter().map(|&x| x * inv_temp).collect();
9760            let max = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9761            let exp: Vec<f32> = scaled.iter().map(|&x| (x - max).exp()).collect();
9762            let sum: f32 = exp.iter().sum();
9763            let probs: Vec<f32> = exp.iter().map(|&x| x / sum).collect();
9764            sample_multinomial(&probs, rng_state)
9765        }
9766    }
9767}
9768
9769// ---- Speculative-decoding helpers ---------------------------------------
9770//
9771// Shared by `generate_streaming_spec_with_kv_context`'s draft / accept
9772// phases. All host-side: spec decode's accept rule operates on logits
9773// vectors already downloaded from the device.
9774
9775/// Greedy argmax over a logits row.
9776pub fn spec_argmax(logits: &[f32]) -> u32 {
9777    let mut best = 0;
9778    let mut best_v = logits[0];
9779    for (i, &v) in logits.iter().enumerate().skip(1) {
9780        if v > best_v {
9781            best_v = v;
9782            best = i;
9783        }
9784    }
9785    best as u32
9786}
9787
9788/// Temperature-scaled softmax. Returns normalized probabilities.
9789pub fn spec_softmax_temp(logits: &[f32], temp: f32) -> Vec<f32> {
9790    let inv_t = if temp == 0.0 { 1.0 } else { 1.0 / temp };
9791    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9792    let exp: Vec<f32> = logits.iter().map(|&x| ((x - max) * inv_t).exp()).collect();
9793    let sum: f32 = exp.iter().sum();
9794    exp.iter().map(|&x| x / sum).collect()
9795}
9796
9797/// Advance a deterministic LCG and return a u01 uniform.
9798pub fn spec_next_u01(state: &mut u64) -> f32 {
9799    *state = state
9800        .wrapping_mul(6364136223846793005)
9801        .wrapping_add(1442695040888963407);
9802    (*state >> 32) as f32 / u32::MAX as f32
9803}
9804
9805/// Sample a category from a distribution summing to ~1.
9806pub fn spec_sample_cat(probs: &[f32], state: &mut u64) -> u32 {
9807    let u = spec_next_u01(state);
9808    let mut cum = 0.0_f32;
9809    for (i, &p) in probs.iter().enumerate() {
9810        cum += p;
9811        if u <= cum {
9812            return i as u32;
9813        }
9814    }
9815    (probs.len() - 1) as u32
9816}
9817
9818/// Sample a categorical distribution using a small deterministic LCG.
9819/// Takes `probs` (assumed to sum to ~1) and a mutable RNG state,
9820/// returns a sampled index.
9821pub fn sample_multinomial(probs: &[f32], rng_state: &mut u64) -> u32 {
9822    // Advance the LCG and turn it into a u01 uniform.
9823    *rng_state = rng_state
9824        .wrapping_mul(6364136223846793005)
9825        .wrapping_add(1442695040888963407);
9826    let u = (*rng_state >> 32) as f32 / u32::MAX as f32;
9827    let mut cumulative = 0.0_f32;
9828    for (i, &p) in probs.iter().enumerate() {
9829        cumulative += p;
9830        if u <= cumulative {
9831            return i as u32;
9832        }
9833    }
9834    // Floating-point slop: fall through to the last index.
9835    (probs.len() - 1) as u32
9836}
9837
9838#[cfg(test)]
9839mod lora_tests {
9840    use super::*;
9841    use crate::Shape;
9842
9843    #[test]
9844    fn with_lora_matches_manual_base_plus_lora() {
9845        // Anchor graph.
9846        let in_f = 4;
9847        let out_f = 3;
9848        let rank = 2;
9849        let alpha = 8.0_f32;
9850
9851        let anchor =
9852            Tensor::from_f32(vec![0.0_f32; 1], Shape::from_dims(&[1]), &Device::cpu()).unwrap();
9853        // Base weight [in, out].
9854        let base_vec: Vec<f32> = (0..in_f * out_f).map(|i| (i as f32) * 0.1).collect();
9855        let lora_a_vec: Vec<f32> = (0..in_f * rank).map(|i| (i as f32) * 0.05).collect();
9856        let lora_b_vec: Vec<f32> = (0..rank * out_f).map(|i| (i as f32) * 0.02).collect();
9857
9858        let ws = WeightStorage::F32(Arc::from(base_vec.clone())).with_lora(
9859            Arc::from(lora_a_vec.clone()),
9860            Arc::from(lora_b_vec.clone()),
9861            rank,
9862            alpha,
9863            in_f,
9864            out_f,
9865        );
9866
9867        // Activations x [2, in_f].
9868        let batch = 2;
9869        let x_data: Vec<f32> = (0..batch * in_f).map(|i| (i as f32) * 0.1 + 0.5).collect();
9870        let x = anchor
9871            .const_f32_like(x_data.clone(), Shape::from_dims(&[batch, in_f]))
9872            .unwrap();
9873        let y = ws.apply_linear(&x, in_f, out_f).unwrap();
9874        let got = y.realize_f32().to_vec();
9875
9876        // Reference: base + (alpha/rank) * x @ A @ B, all f32, on CPU.
9877        let mut expected = vec![0.0_f32; batch * out_f];
9878        for b in 0..batch {
9879            for j in 0..out_f {
9880                let mut acc = 0.0_f32;
9881                // Base path: sum_k x[b,k] * W[k,j].
9882                for k in 0..in_f {
9883                    acc += x_data[b * in_f + k] * base_vec[k * out_f + j];
9884                }
9885                // LoRA path: sum_r (sum_k x[b,k] * A[k,r]) * B[r,j] * (alpha/rank).
9886                let scale = alpha as f64 / rank as f64;
9887                for r in 0..rank {
9888                    let mut xar = 0.0_f32;
9889                    for k in 0..in_f {
9890                        xar += x_data[b * in_f + k] * lora_a_vec[k * rank + r];
9891                    }
9892                    acc += (xar * lora_b_vec[r * out_f + j]) * scale as f32;
9893                }
9894                expected[b * out_f + j] = acc;
9895            }
9896        }
9897
9898        for (i, (&e, &g)) in expected.iter().zip(got.iter()).enumerate() {
9899            let diff = (e - g).abs();
9900            assert!(
9901                diff <= 1e-4,
9902                "LoRA mismatch at {i}: expected {e}, got {g} (diff {diff})",
9903            );
9904        }
9905    }
9906
9907    #[test]
9908    #[should_panic(expected = "lora_a length")]
9909    fn with_lora_rejects_mismatched_a_shape() {
9910        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
9911        let bad_a = Arc::from(vec![0.0_f32; 3]); // wrong
9912        let b = Arc::from(vec![0.0_f32; 6]); // 2 x 3
9913        let _ = ws.with_lora(bad_a, b, 2, 8.0, 4, 3);
9914    }
9915
9916    // ---- never-panic conversion (`apply_linear` -> `Result`) ----
9917    //
9918    // These three inputs each used to abort the process on a PRODUCTION path:
9919    // a wrong trailing dim reached `x.matmul(&w).unwrap()`, a stored/requested
9920    // shape disagreement hit `assert_eq!`, and a wrong-length bias hit a
9921    // `debug_assert_eq!` that is compiled OUT of release builds — so release
9922    // binaries broadcast a mis-sized bias with no complaint at all. All three
9923    // are checkpoint/data conditions rather than programming invariants (a
9924    // GGUF whose stored shape disagrees with the model config produces exactly
9925    // this), so all three must be `Err`.
9926
9927    #[test]
9928    fn apply_linear_errors_on_trailing_dim_mismatch() {
9929        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
9930        let x = Tensor::from_f32(
9931            vec![0.0_f32; 10],
9932            Shape::from_dims(&[2, 5]), // trailing dim 5 != in_features 4
9933            &Device::cpu(),
9934        )
9935        .unwrap();
9936        let err = ws
9937            .apply_linear(&x, 4, 3)
9938            .expect_err("must not panic, must Err");
9939        let msg = err.to_string();
9940        assert!(
9941            msg.contains("trailing dim 4"),
9942            "error should name the expected trailing dim, got: {msg}",
9943        );
9944    }
9945
9946    #[test]
9947    fn apply_linear_errors_on_q4_0_stored_shape_mismatch() {
9948        // 4 x 4 of Q4_0: one 32-element block needs 18 bytes; keep the word
9949        // count self-consistent since only the shape check is under test.
9950        let ws = WeightStorage::Q4_0 {
9951            words: Arc::from(vec![0_u32; 8]),
9952            bytes_len: 18, // one Q4_0 block: 2-byte scale + 16 packed nibble bytes
9953            in_features: 4,
9954            out_features: 4,
9955        };
9956        let x =
9957            Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
9958        // Trailing dim matches in_features, so this reaches the stored-shape
9959        // check rather than the contract check above.
9960        let err = ws
9961            .apply_linear(&x, 4, 7)
9962            .expect_err("must not panic, must Err");
9963        let msg = err.to_string();
9964        assert!(
9965            msg.contains("Q4_0 shape mismatch"),
9966            "error should name the stored/requested disagreement, got: {msg}",
9967        );
9968    }
9969
9970    #[test]
9971    fn apply_linear_with_bias_errors_on_wrong_bias_length() {
9972        let ws = WeightStorage::F32(Arc::from(vec![0.0_f32; 12])); // 4 x 3
9973        let x =
9974            Tensor::from_f32(vec![0.0_f32; 8], Shape::from_dims(&[2, 4]), &Device::cpu()).unwrap();
9975        let bias: Arc<[f32]> = Arc::from(vec![0.0_f32; 2]); // wrong: out_features is 3
9976        let err = ws
9977            .apply_linear_with_bias(&x, 4, 3, bias)
9978            .expect_err("wrong-length bias must Err in EVERY profile, not just debug");
9979        assert!(
9980            err.to_string().contains("bias len"),
9981            "error should name the bias length, got: {err}",
9982        );
9983    }
9984}
9985
9986#[cfg(test)]
9987mod safetensors_bridge_tests {
9988    use super::*;
9989
9990    #[test]
9991    fn from_safetensors_bytes_round_trip_f32() {
9992        // Build a tensor, serialize it as little-endian f32 bytes,
9993        // then deserialize via the bridge. Should get back the same
9994        // values.
9995        let original: Vec<f32> = vec![1.0, -2.5, 3.25, 0.0];
9996        let mut bytes = Vec::with_capacity(original.len() * 4);
9997        for &v in &original {
9998            bytes.extend_from_slice(&v.to_le_bytes());
9999        }
10000        let t =
10001            Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::F32, &[4], &Device::cpu())
10002                .unwrap();
10003        assert_eq!(t.shape().dims(), &[4]);
10004        assert_eq!(t.dtype(), DType::F32);
10005        assert_eq!(t.realize_f32(), original);
10006    }
10007
10008    #[test]
10009    fn from_safetensors_bytes_round_trip_bf16() {
10010        let original_f32: Vec<f32> = vec![0.5, -1.0, 2.0, 4.0];
10011        let bf16_vec: Vec<half::bf16> = original_f32
10012            .iter()
10013            .map(|&v| half::bf16::from_f32(v))
10014            .collect();
10015        let mut bytes = Vec::with_capacity(bf16_vec.len() * 2);
10016        for b in &bf16_vec {
10017            bytes.extend_from_slice(&b.to_bits().to_le_bytes());
10018        }
10019        let t =
10020            Tensor::from_safetensors_bytes(&bytes, safetensors::Dtype::BF16, &[4], &Device::cpu())
10021                .unwrap();
10022        assert_eq!(t.dtype(), DType::BF16);
10023        // Values that round-trip exactly through bf16 should come back
10024        // unchanged.
10025        let realized = t.realize_bf16();
10026        assert_eq!(realized, bf16_vec);
10027    }
10028
10029    #[test]
10030    fn from_safetensors_bytes_rejects_wrong_byte_count() {
10031        // Shape says 3 elements, but we pass 4 bytes (1 f32 = 4 bytes
10032        // so 3 elements would need 12 bytes).
10033        let bad_bytes = vec![0_u8; 4];
10034        let result = Tensor::from_safetensors_bytes(
10035            &bad_bytes,
10036            safetensors::Dtype::F32,
10037            &[3],
10038            &Device::cpu(),
10039        );
10040        assert!(result.is_err());
10041    }
10042}
10043
10044// ============================================================================
10045// Phase A.1 wrapper smoke tests.
10046//
10047// Pure pass-through tests: realize and assert the returned tensor has the
10048// expected shape / dtype / values. The graph-level ops are tested in
10049// `fuel-graph`; here we only verify that the Tensor wrappers don't
10050// drop information or mis-thread arguments.
10051// ============================================================================
10052#[cfg(test)]
10053mod phase_a1_wrapper_tests {
10054    use super::*;
10055
10056    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10057        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10058    }
10059
10060    #[test]
10061    fn unsqueeze_adds_size_one_dim() {
10062        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10063        let out = t.unsqueeze(0_usize).unwrap();
10064        assert_eq!(out.shape().dims(), &[1, 2, 2]);
10065        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10066    }
10067
10068    #[test]
10069    fn unsqueeze_errors_out_of_bounds() {
10070        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10071        // rank=1, so dim<=1 is valid; dim=2 must error.
10072        assert!(t.unsqueeze(0_usize).is_ok());
10073        assert!(t.unsqueeze(1_usize).is_ok());
10074        assert!(t.unsqueeze(2_usize).is_err());
10075    }
10076
10077    #[test]
10078    fn try_reshape_errors_on_size_mismatch() {
10079        let t = cpu_f32(vec![1.0; 6], &[2, 3]);
10080        assert!(t.reshape(vec![3, 2]).is_ok());
10081        assert!(t.reshape(vec![2, 2]).is_err());
10082    }
10083
10084    #[test]
10085    fn try_permute_validates_axes() {
10086        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10087        // The Dims trait accepts tuples, owned arrays, and slices.
10088        assert!(t.permute((2_usize, 0_usize, 1_usize)).is_ok());
10089        assert!(t.permute([2_usize, 0, 1]).is_ok());
10090        assert!(t.permute([0_usize, 1]).is_err()); // wrong rank
10091        assert!(t.permute([0_usize, 0, 1]).is_err()); // dup axis
10092    }
10093
10094    #[test]
10095    fn try_transpose_requires_rank_two_plus() {
10096        let scalar = cpu_f32(vec![1.0], &[1]);
10097        // rank-1: transpose surfaces a typed error at build time.
10098        let _ = scalar.transpose();
10099    }
10100
10101    #[test]
10102    fn triu_tril_shape_preserved() {
10103        let t = cpu_f32(vec![1.0; 9], &[3, 3]);
10104        let upper = t.triu(0).unwrap();
10105        let lower = t.tril(0).unwrap();
10106        assert_eq!(upper.shape().dims(), &[3, 3]);
10107        assert_eq!(lower.shape().dims(), &[3, 3]);
10108        // tril(0) of all-ones: 1s on/below diagonal, 0s above
10109        assert_eq!(
10110            lower.realize_f32(),
10111            vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]
10112        );
10113    }
10114
10115    #[test]
10116    fn triu_rejects_rank_one() {
10117        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10118        assert!(t.triu(0).is_err());
10119    }
10120
10121    #[test]
10122    fn log_softmax_last_dim_shape_preserved() {
10123        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10124        let out = t.log_softmax_last_dim().unwrap();
10125        assert_eq!(out.shape().dims(), &[2, 2]);
10126        // log_softmax values must be <= 0.
10127        for v in out.realize_f32() {
10128            assert!(v <= 0.0 + 1e-6, "log_softmax produced positive value: {v}");
10129        }
10130    }
10131
10132    #[test]
10133    fn softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10134        // shape [2, 3, 2] — softmax along axis=1 (the size-3 axis).
10135        // Layout (row-major): element (b, r, c) lives at b*6 + r*2 + c.
10136        // We hand-pick values so each (b, c) lane's max is exactly 0 to
10137        // make the reference closed-form: probs = exp(x) / sum_r exp(x).
10138        // Lane (b=0, c=0): values [-1, 0, -2]  → exp = [e^-1, 1, e^-2]
10139        // Lane (b=0, c=1): values [ 0,-3, -1]  → exp = [1, e^-3, e^-1]
10140        // Lane (b=1, c=0): values [-2,-1,  0]  → exp = [e^-2, e^-1, 1]
10141        // Lane (b=1, c=1): values [-1,-1,  0]  → exp = [e^-1, e^-1, 1]
10142        let data: Vec<f32> = vec![
10143            // b=0
10144            -1.0, 0.0, // r=0, c=0..1
10145            0.0, -3.0, // r=1
10146            -2.0, -1.0, // r=2
10147            // b=1
10148            -2.0, -1.0, // r=0
10149            -1.0, -1.0, // r=1
10150            0.0, 0.0, // r=2
10151        ];
10152        let t = cpu_f32(data, &[2, 3, 2]);
10153        let out = t.softmax(1_usize).unwrap();
10154        assert_eq!(out.shape().dims(), &[2, 3, 2]);
10155        let v = out.realize_f32();
10156
10157        // Reference: closed-form softmax per (b, c) lane.
10158        let lane_softmax = |xs: [f32; 3]| -> [f32; 3] {
10159            let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10160            let exps = [(xs[0] - m).exp(), (xs[1] - m).exp(), (xs[2] - m).exp()];
10161            let s = exps[0] + exps[1] + exps[2];
10162            [exps[0] / s, exps[1] / s, exps[2] / s]
10163        };
10164        // Re-extract source lanes
10165        let lanes: [[f32; 3]; 4] = [
10166            [-1.0, 0.0, -2.0], // (b=0, c=0)
10167            [0.0, -3.0, -1.0], // (b=0, c=1)
10168            [-2.0, -1.0, 0.0], // (b=1, c=0)
10169            [-1.0, -1.0, 0.0], // (b=1, c=1)
10170        ];
10171        let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_softmax(*l)).collect();
10172
10173        // out[b, r, c] at index b*6 + r*2 + c — verify each (b, c) lane.
10174        for b in 0..2 {
10175            for c in 0..2 {
10176                let lane_ix = b * 2 + c;
10177                for r in 0..3 {
10178                    let got = v[b * 6 + r * 2 + c];
10179                    let want = refs[lane_ix][r];
10180                    assert!(
10181                        (got - want).abs() < 1e-6,
10182                        "softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10183                    );
10184                }
10185                // sanity: lane sums to 1
10186                let sum: f32 = (0..3).map(|r| v[b * 6 + r * 2 + c]).sum();
10187                assert!((sum - 1.0).abs() < 1e-6, "lane (b={b},c={c}) sums to {sum}");
10188            }
10189        }
10190    }
10191
10192    #[test]
10193    fn softmax_last_axis_matches_softmax_last_dim() {
10194        let data: Vec<f32> = vec![
10195            1.0, 2.0, -1.0, 0.5, 0.0, -2.0, 3.0, 1.5, // batch dim 2
10196            4.0, -1.0, 2.0, 0.0, -3.0, 0.25, 0.75, 1.0,
10197        ];
10198        let t = cpu_f32(data, &[2, 2, 4]);
10199        let via_general = t.softmax(2_usize).unwrap();
10200        let via_fused = t.softmax_last_dim().unwrap();
10201        assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10202        let g = via_general.realize_f32();
10203        let f = via_fused.realize_f32();
10204        assert_eq!(g.len(), f.len());
10205        for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10206            assert!(
10207                (a - b).abs() < 1e-6,
10208                "softmax (general axis=2) vs softmax_last_dim diverge at {i}: {a} vs {b}",
10209            );
10210        }
10211    }
10212
10213    #[test]
10214    fn log_softmax_general_axis_matches_hand_computed_rank3_middle_axis() {
10215        // Same construction as the softmax test, but compare against
10216        // closed-form log_softmax per (b, c) lane.
10217        let data: Vec<f32> = vec![
10218            -1.0, 0.0, 0.0, -3.0, -2.0, -1.0, -2.0, -1.0, -1.0, -1.0, 0.0, 0.0,
10219        ];
10220        let t = cpu_f32(data, &[2, 3, 2]);
10221        let out = t.log_softmax(1_usize).unwrap();
10222        assert_eq!(out.shape().dims(), &[2, 3, 2]);
10223        let v = out.realize_f32();
10224
10225        let lane_log_softmax = |xs: [f32; 3]| -> [f32; 3] {
10226            let m = xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
10227            let shifted = [xs[0] - m, xs[1] - m, xs[2] - m];
10228            let lse = (shifted[0].exp() + shifted[1].exp() + shifted[2].exp()).ln();
10229            [shifted[0] - lse, shifted[1] - lse, shifted[2] - lse]
10230        };
10231        let lanes: [[f32; 3]; 4] = [
10232            [-1.0, 0.0, -2.0],
10233            [0.0, -3.0, -1.0],
10234            [-2.0, -1.0, 0.0],
10235            [-1.0, -1.0, 0.0],
10236        ];
10237        let refs: Vec<[f32; 3]> = lanes.iter().map(|l| lane_log_softmax(*l)).collect();
10238
10239        for b in 0..2 {
10240            for c in 0..2 {
10241                let lane_ix = b * 2 + c;
10242                for r in 0..3 {
10243                    let got = v[b * 6 + r * 2 + c];
10244                    let want = refs[lane_ix][r];
10245                    assert!(
10246                        (got - want).abs() < 1e-6,
10247                        "log_softmax mismatch at (b={b}, r={r}, c={c}): got {got}, want {want}",
10248                    );
10249                    // log_softmax values must be <= 0
10250                    assert!(got <= 1e-6, "log_softmax produced positive value: {got}");
10251                }
10252            }
10253        }
10254    }
10255
10256    #[test]
10257    fn log_softmax_last_axis_matches_log_softmax_last_dim() {
10258        let data: Vec<f32> = vec![
10259            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,
10260        ];
10261        let t = cpu_f32(data, &[2, 2, 4]);
10262        let via_general = t.log_softmax(2_usize).unwrap();
10263        let via_fused = t.log_softmax_last_dim().unwrap();
10264        assert_eq!(via_general.shape().dims(), via_fused.shape().dims());
10265        let g = via_general.realize_f32();
10266        let f = via_fused.realize_f32();
10267        assert_eq!(g.len(), f.len());
10268        for (i, (a, b)) in g.iter().zip(f.iter()).enumerate() {
10269            assert!(
10270                (a - b).abs() < 1e-6,
10271                "log_softmax (general axis=2) vs log_softmax_last_dim diverge at {i}: {a} vs {b}",
10272            );
10273        }
10274    }
10275
10276    #[test]
10277    fn argmin_dim_drops_reduced_axis() {
10278        let t = cpu_f32(vec![3.0, 1.0, 2.0, 0.5, 5.0, 4.0], &[2, 3]);
10279        let out = t.argmin_dim(1_usize).unwrap();
10280        assert_eq!(out.shape().dims(), &[2]);
10281        assert_eq!(out.dtype(), DType::U32);
10282        assert_eq!(out.realize_u32(), vec![1, 0]);
10283    }
10284
10285    #[test]
10286    fn masked_fill_smoke() {
10287        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10288        // Comparison ops produce Bool masks directly (GAP-168(c)) — masked_fill
10289        // now accepts Bool, no F32→mask cast needed.
10290        let probe = t
10291            .const_f32_like(vec![0.0, 1.0, 1.0, 0.0], vec![2, 2])
10292            .unwrap();
10293        let threshold = t.const_f32_like(vec![0.5; 4], vec![2, 2]).unwrap();
10294        let mask = probe.gt(&threshold).unwrap(); // [0, 1, 1, 0] as Bool
10295        let out = t.masked_fill(&mask, fuel_ir::Scalar::F32(-9.0)).unwrap();
10296        assert_eq!(out.realize_f32(), vec![1.0, -9.0, -9.0, 4.0]);
10297    }
10298
10299    /// GAP-168(c) DISCRIMINATION: `Bool` and `U8` are byte-identical in storage,
10300    /// which is exactly the condition under which a wrong wiring is *silently
10301    /// correct*. This test proves they are NOT interchangeable end-to-end on CPU:
10302    /// a comparison yields a `Bool` (not `U8`) tensor, and `to_dtype(Bool)` on a
10303    /// `U8` tensor is a real `!= 0` CONVERSION — never a byte reinterpret.
10304    #[test]
10305    fn bool_is_distinguishable_from_u8_end_to_end() {
10306        // A comparison realizes end-to-end as a Bool tensor (NOT U8) whose bytes
10307        // are 0/1 — the byte-identity hazard's most likely hiding spot, closed:
10308        // dtype tag is Bool, the CPU kernel dispatches on [F32,F32,Bool] (its FKC
10309        // contract declares fixed(BOOL)), and Copy[Bool] materializes it to host.
10310        let t = cpu_f32(vec![0.0, 5.0, 3.0, 0.0], &[4]);
10311        let thr = t.const_f32_like(vec![0.5; 4], vec![4]).unwrap();
10312        let mask = t.gt(&thr).unwrap();
10313        assert_eq!(mask.dtype(), DType::Bool, "gt yields Bool, not U8");
10314        assert_eq!(mask.realize_u8(), vec![0, 1, 1, 0], "mask bytes are 0/1");
10315
10316        // ---- The cast discrimination, now that the 22 Bool pairs are wired ----
10317        //
10318        // NEGATIVE CONTROL FIRST, or the assertion below is vacuous: build a U8
10319        // tensor that genuinely holds 5. If this line ever came back as 0/1, the
10320        // real test would pass for the wrong reason — it would be comparing 0/1
10321        // against 0/1 and could not tell a conversion from a reinterpret.
10322        let u8_vals = t
10323            .const_f32_like(vec![0.0, 5.0, 3.0, 0.0], vec![4])
10324            .unwrap()
10325            .to_dtype(DType::U8)
10326            .unwrap();
10327        assert_eq!(u8_vals.dtype(), DType::U8);
10328        assert_eq!(
10329            u8_vals.realize_u8(),
10330            vec![0, 5, 3, 0],
10331            "negative control: the U8 source must really hold 5 and 3, else the \
10332             conversion assertion below cannot discriminate"
10333        );
10334
10335        // THE DISCRIMINATION: U8 -> Bool is a real `!= 0` conversion. A byte
10336        // reinterpret would yield [0, 5, 3, 0] — byte-identical storage makes
10337        // that the silently-correct-looking failure. A conversion yields 0/1.
10338        let as_bool = u8_vals.to_dtype(DType::Bool).unwrap();
10339        assert_eq!(as_bool.dtype(), DType::Bool);
10340        assert_eq!(
10341            as_bool.realize_u8(),
10342            vec![0, 1, 1, 0],
10343            "U8->Bool must CONVERT (5 -> 1), not reinterpret (5 -> 5)"
10344        );
10345
10346        // And back out: Bool -> F32 is exactly 0.0/1.0.
10347        assert_eq!(
10348            as_bool.to_dtype(DType::F32).unwrap().realize_f32(),
10349            vec![0.0, 1.0, 1.0, 0.0],
10350            "Bool->F32 yields 0.0/1.0"
10351        );
10352        // Bool -> U8 keeps the canonical 0/1 (this direction IS byte-preserving,
10353        // which is fine — it is the OTHER direction that must not be).
10354        assert_eq!(
10355            mask.to_dtype(DType::U8).unwrap().realize_u8(),
10356            vec![0, 1, 1, 0]
10357        );
10358
10359        // FINALLY, the two are not INTERCHANGEABLE at the API, which is what
10360        // stops a numeric mask being coerced silently: `masked_fill` requires a
10361        // Bool mask and rejects U8 at GRAPH-BUILD time, so the cast is explicit
10362        // at the call site rather than implied.
10363        let err = t.masked_fill(&u8_vals, fuel_ir::Scalar::F32(-9.0));
10364        assert!(
10365            err.is_err(),
10366            "a U8 mask must be REJECTED by masked_fill — Bool and U8 are \
10367             byte-identical, so accepting it would 'work' and erase the distinction"
10368        );
10369    }
10370
10371    /// GAP-183: `float -> Bool` is lowered in the optimizer to `Ne(x, x*0)` so it
10372    /// reaches CUDA's shipped `ne_{f32,f64,f16,bf16}` kernels, which a
10373    /// storage-level cast cannot compose. This pins the VALUES end-to-end, and
10374    /// the three interesting inputs are the whole point of the test — a lowering
10375    /// that got only the ordinary cases right would still be wrong:
10376    ///
10377    ///   -0.0  -> FALSE   (IEEE `-0.0 == 0.0`)
10378    ///   NaN   -> TRUE    (matches PyTorch `.bool()`)
10379    ///   ±inf  -> TRUE
10380    ///
10381    /// The zeros operand is itself NaN for non-finite x; that is harmless because
10382    /// `x != NaN` and `x != 0` agree for every non-finite x. This test is what
10383    /// would catch it if that ever stopped being true.
10384    #[test]
10385    fn float_to_bool_lowering_preserves_ieee_semantics() {
10386        let t = cpu_f32(
10387            vec![
10388                0.0,
10389                -0.0,
10390                5.0,
10391                -3.0,
10392                f32::NAN,
10393                f32::INFINITY,
10394                f32::NEG_INFINITY,
10395            ],
10396            &[7],
10397        );
10398        let b = t.to_dtype(DType::Bool).unwrap();
10399        assert_eq!(b.dtype(), DType::Bool, "to_dtype(Bool) still yields Bool");
10400        assert_eq!(
10401            b.realize_u8(),
10402            vec![0, 0, 1, 1, 1, 1, 1],
10403            "0 and -0.0 are false; every other value including NaN and both \
10404             infinities is true",
10405        );
10406    }
10407
10408    #[test]
10409    fn index_add_smoke() {
10410        let base = cpu_f32(vec![1.0, 1.0, 1.0, 1.0], &[2, 2]);
10411        let src = base
10412            .const_f32_like(vec![10.0, 20.0, 30.0, 40.0], vec![2, 2])
10413            .unwrap();
10414        let indices = base.const_u32_like(vec![0_u32, 0_u32], vec![2]).unwrap();
10415        let out = base.index_add(0, &indices, &src).unwrap();
10416        assert_eq!(out.shape().dims(), &[2, 2]);
10417        // both src rows added to row 0; row 1 unchanged
10418        let v = out.realize_f32();
10419        assert_eq!(v[0], 41.0); // 1 + 10 + 30
10420        assert_eq!(v[1], 61.0); // 1 + 20 + 40
10421        assert_eq!(v[2], 1.0);
10422        assert_eq!(v[3], 1.0);
10423    }
10424
10425    #[test]
10426    fn scatter_add_smoke() {
10427        let base = cpu_f32(vec![0.0, 0.0, 0.0, 0.0], &[2, 2]);
10428        let src = base
10429            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
10430            .unwrap();
10431        let indices = base
10432            .const_u32_like(vec![0_u32, 1_u32, 1_u32, 0_u32], vec![2, 2])
10433            .unwrap();
10434        let out = base.scatter_add(0, &indices, &src).unwrap();
10435        assert_eq!(out.shape().dims(), &[2, 2]);
10436    }
10437
10438    #[test]
10439    fn inplace_activations_compile_and_run() {
10440        let t = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]);
10441        // Each in-place op is destructive, so chain through fresh tensors.
10442        let r = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).relu_inplace();
10443        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).silu_inplace();
10444        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).gelu_tanh_inplace();
10445        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).tanh_inplace();
10446        let _ = cpu_f32(vec![-1.0, 0.5, -3.0, 2.0], &[4]).sigmoid_inplace();
10447        let _ = t.affine_inplace(2.0, 1.0);
10448        // Spot-check the relu output.
10449        let v = r.realize_f32();
10450        assert_eq!(v, vec![0.0, 0.5, 0.0, 2.0]);
10451    }
10452
10453    #[test]
10454    fn const_f64_like_round_trips() {
10455        let anchor = cpu_f32(vec![0.0], &[1]);
10456        let t = anchor.const_f64_like(vec![1.5, 2.5, 3.5], vec![3]).unwrap();
10457        assert_eq!(t.shape().dims(), &[3]);
10458        assert_eq!(t.dtype(), DType::F64);
10459        assert_eq!(t.realize_f64(), vec![1.5, 2.5, 3.5]);
10460    }
10461
10462    #[test]
10463    fn const_i64_like_round_trips() {
10464        let anchor = cpu_f32(vec![0.0], &[1]);
10465        let t = anchor.const_i64_like(vec![-1_i64, 2, -3], vec![3]).unwrap();
10466        assert_eq!(t.shape().dims(), &[3]);
10467        assert_eq!(t.dtype(), DType::I64);
10468    }
10469
10470    #[test]
10471    fn on_device_smoke_cpu() {
10472        let t = cpu_f32(vec![1.0, 2.0], &[2]);
10473        let pinned = t.on_device(&Device::cpu());
10474        assert_eq!(pinned.realize_f32(), vec![1.0, 2.0]);
10475    }
10476
10477    #[test]
10478    fn copy_to_device_same_device_round_trips() {
10479        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
10480        let copied = t.copy_to_device(&Device::cpu());
10481        assert_eq!(copied.realize_f32(), vec![1.0, 2.0, 3.0]);
10482    }
10483}
10484
10485// ============================================================================
10486// Phase A.2 composite primitives tests.
10487// ============================================================================
10488#[cfg(test)]
10489mod phase_a2_composite_tests {
10490    use super::*;
10491
10492    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
10493        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
10494    }
10495
10496    #[test]
10497    fn transpose_last_two_swaps_last_two_dims() {
10498        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10499        let out = t.transpose_last_two().unwrap();
10500        assert_eq!(out.shape().dims(), &[3, 2]);
10501        assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
10502    }
10503
10504    #[test]
10505    fn t_is_alias_of_transpose_last_two() {
10506        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10507        assert_eq!(
10508            t.t().unwrap().realize_f32(),
10509            t.transpose_last_two().unwrap().realize_f32()
10510        );
10511    }
10512
10513    #[test]
10514    fn transpose_dims_swaps_arbitrary_axes() {
10515        let t = cpu_f32((0..24).map(|i| i as f32).collect(), &[2, 3, 4]);
10516        let out = t.transpose_dims(0, 2).unwrap();
10517        assert_eq!(out.shape().dims(), &[4, 3, 2]);
10518    }
10519
10520    #[test]
10521    fn transpose_dims_identity_when_same_axis() {
10522        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
10523        let out = t.transpose_dims(0, 0).unwrap();
10524        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
10525    }
10526
10527    #[test]
10528    fn transpose_dims_errors_out_of_bounds() {
10529        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10530        assert!(t.transpose_dims(0, 2).is_err());
10531        assert!(t.transpose_dims(5, 0).is_err());
10532    }
10533
10534    #[test]
10535    fn flatten_merges_middle_dims() {
10536        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10537        let out = t.flatten(0, 1).unwrap();
10538        assert_eq!(out.shape().dims(), &[6, 4]);
10539    }
10540
10541    #[test]
10542    fn flatten_to_merges_leading_dims() {
10543        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10544        let out = t.flatten_to(1).unwrap();
10545        assert_eq!(out.shape().dims(), &[6, 4]);
10546    }
10547
10548    #[test]
10549    fn flatten_from_merges_trailing_dims() {
10550        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
10551        let out = t.flatten_from(1).unwrap();
10552        assert_eq!(out.shape().dims(), &[2, 12]);
10553    }
10554
10555    #[test]
10556    fn flatten_all_produces_rank_one() {
10557        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10558        let out = t.flatten_all().unwrap();
10559        assert_eq!(out.shape().dims(), &[6]);
10560        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
10561    }
10562
10563    /// `rope_batched` at `B == 1` must be **bit-identical** to
10564    /// `rope_with_tables_decomposed`, and each row at `B == 3` must equal the
10565    /// single-position result at that row's own position — the exactness proof
10566    /// for the per-row RoPE that unblocks ragged (non-uniform-position) batched
10567    /// decode. A subtly wrong rotate-half (wrong half split, wrong sign, wrong
10568    /// concat order) still produces plausible tokens, so this asserts
10569    /// bit-equality; the CONTROL proves the per-row table is load-bearing.
10570    /// (Adopted from the Lightbulb consumer's verified `rope_batched` oracle;
10571    /// the mechanism belongs in Fuel.)
10572    #[test]
10573    fn rope_batched_matches_single_position_rope_row_by_row() {
10574        let lcg = |n: usize, seed: u32| -> Vec<f32> {
10575            let mut s = seed;
10576            (0..n)
10577                .map(|_| {
10578                    s = s.wrapping_mul(1103515245).wrapping_add(12345);
10579                    ((s >> 16) as u16 as f32 / 65535.0 - 0.5) * 0.5
10580                })
10581                .collect()
10582        };
10583        let (b, heads, hd) = (3usize, 4usize, 8usize);
10584        let base = 10000.0f64;
10585        let positions = [0usize, 7, 3];
10586
10587        let x_data = lcg(b * heads * hd, 11);
10588        let x = cpu_f32(x_data.clone(), &[b, heads, 1, hd]);
10589        let (cos, sin) = x.rope_tables_const_batched(base, &positions, hd);
10590        let got = x.rope_batched(&cos, &sin).unwrap().realize_f32();
10591
10592        let per_row = heads * hd;
10593        for (row, &pos) in positions.iter().enumerate() {
10594            let row_data = x_data[row * per_row..(row + 1) * per_row].to_vec();
10595            let xr = cpu_f32(row_data, &[1, heads, 1, hd]);
10596            let (c, s) = xr.rope_tables_const(base, pos, 1, hd);
10597            let want = xr
10598                .rope_with_tables_decomposed(&c, &s)
10599                .unwrap()
10600                .realize_f32();
10601            assert_eq!(
10602                &got[row * per_row..(row + 1) * per_row],
10603                &want[..],
10604                "row {row} (position {pos}) != decomposed RoPE at that position",
10605            );
10606        }
10607
10608        // CONTROL: prove the per-row table is load-bearing. Give EVERY row
10609        // position 0 (row 0's position); rows at other positions must now
10610        // DISAGREE with their own-position result — else the comparison above is
10611        // blind to the whole per-row-position mechanism.
10612        let shared = [positions[0]; 3];
10613        let (c0, s0) = x.rope_tables_const_batched(base, &shared, hd);
10614        let wrong = x.rope_batched(&c0, &s0).unwrap().realize_f32();
10615        for (row, &pos) in positions.iter().enumerate().skip(1) {
10616            assert_ne!(
10617                &wrong[row * per_row..(row + 1) * per_row],
10618                &got[row * per_row..(row + 1) * per_row],
10619                "CONTROL: row {row} at shared position 0 matched its own position \
10620                 {pos} — per-row RoPE not applied, or comparison blind to it",
10621            );
10622        }
10623    }
10624
10625    #[test]
10626    fn flatten_errors_on_bad_range() {
10627        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
10628        assert!(t.flatten(0, 5).is_err());
10629        assert!(t.flatten(2, 1).is_err()); // start > end
10630    }
10631
10632    #[test]
10633    fn split_heads_then_merge_heads_round_trip() {
10634        // (B=1, N=2, embed=6) — split into 2 heads of head_dim=3.
10635        let x = cpu_f32((0..12).map(|i| i as f32).collect(), &[1, 2, 6]);
10636        let split = x.split_heads(2, 3).unwrap();
10637        assert_eq!(split.shape().dims(), &[1, 2, 2, 3]);
10638        let merged = split.merge_heads().unwrap();
10639        assert_eq!(merged.shape().dims(), &[1, 2, 6]);
10640        let m = merged.realize_f32();
10641        let original = x.realize_f32();
10642        for (a, b) in m.iter().zip(original.iter()) {
10643            assert!((a - b).abs() < 1e-7, "{a} vs {b}");
10644        }
10645    }
10646
10647    #[test]
10648    fn rope_tables_const_shapes_and_anchoring() {
10649        let anchor = cpu_f32(vec![0.0_f32; 8], &[1, 4, 2]);
10650        let (cos, sin) = anchor.rope_tables_const(10_000.0, 0, 4, 8);
10651        assert_eq!(cos.shape().dims(), &[4, 8]);
10652        assert_eq!(sin.shape().dims(), &[4, 8]);
10653        // First row at position 0: cos = 1.0, sin = 0.0 for every pair.
10654        let cv = cos.realize_f32();
10655        let sv = sin.realize_f32();
10656        // cos[0,...] should all be 1.0 (RoPE at position 0).
10657        for i in 0..8 {
10658            assert!((cv[i] - 1.0).abs() < 1e-5, "cos[0,{i}] = {}", cv[i]);
10659            assert!(sv[i].abs() < 1e-5, "sin[0,{i}] = {}", sv[i]);
10660        }
10661    }
10662
10663    #[test]
10664    fn embed_tokens_shape_and_lookup() {
10665        // 5-token vocab, 3-dim hidden. Vocab embedding table contains
10666        // row i = (i, i+0.5, i+1) so the lookup result is verifiable.
10667        let vocab_size = 5;
10668        let hidden = 3;
10669        let table: Vec<f32> = (0..vocab_size)
10670            .flat_map(|i| vec![i as f32, i as f32 + 0.5, i as f32 + 1.0])
10671            .collect();
10672        let tokens = vec![1_u32, 3, 0];
10673        let out = Tensor::embed_tokens(
10674            std::sync::Arc::from(table),
10675            vocab_size,
10676            hidden,
10677            &tokens,
10678            &crate::Device::cpu(),
10679        )
10680        .unwrap();
10681        assert_eq!(out.shape().dims(), &[1, 3, hidden]);
10682        let v = out.realize_f32();
10683        let want = [
10684            1.0_f32, 1.5, 2.0, // token 1
10685            3.0, 3.5, 4.0, // token 3
10686            0.0, 0.5, 1.0, // token 0
10687        ];
10688        for (i, (&got, &exp)) in v.iter().zip(want.iter()).enumerate() {
10689            assert!((got - exp).abs() < 1e-5, "row {i}: got={got} want={exp}");
10690        }
10691    }
10692
10693    #[test]
10694    fn embed_tokens_anchored_lives_on_receiver_graph() {
10695        // Two paths: one bootstrapped via embed_tokens, one anchored
10696        // on a pre-existing tensor. Both produce identical values,
10697        // but only the anchored one can compose with the anchor.
10698        let vocab_size = 4;
10699        let hidden = 2;
10700        let table: Vec<f32> = (0..vocab_size)
10701            .flat_map(|i| vec![i as f32, i as f32 * 2.0])
10702            .collect();
10703        let table_arc: std::sync::Arc<[f32]> = std::sync::Arc::from(table);
10704        let tokens = vec![2_u32, 1];
10705
10706        let anchor = cpu_f32(vec![0.0_f32], &[1]);
10707        let embedded = anchor
10708            .embed_tokens_anchored(
10709                std::sync::Arc::clone(&table_arc),
10710                vocab_size,
10711                hidden,
10712                &tokens,
10713            )
10714            .unwrap();
10715        assert_eq!(embedded.shape().dims(), &[1, 2, hidden]);
10716
10717        // Anchored: composes with the anchor.
10718        let one_scaled = anchor
10719            .const_f32_like(std::sync::Arc::from(vec![1.0_f32]), Shape::from_dims(&[1]))
10720            .unwrap();
10721        let _ = embedded
10722            .add(
10723                &one_scaled
10724                    .reshape(Shape::from_dims(&[1, 1, 1]))
10725                    .unwrap()
10726                    .broadcast_to(Shape::from_dims(&[1, 2, hidden]))
10727                    .unwrap(),
10728            )
10729            .unwrap();
10730        let v = embedded.realize_f32();
10731        let want = [
10732            2.0_f32, 4.0, // token 2
10733            1.0, 2.0, // token 1
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_empty_returns_error() {
10742        let r = Tensor::embed_tokens(
10743            std::sync::Arc::from(vec![0.0_f32]),
10744            1,
10745            1,
10746            &[],
10747            &crate::Device::cpu(),
10748        );
10749        assert!(r.is_err());
10750    }
10751
10752    #[test]
10753    fn softcap_matches_tanh_form() {
10754        // Tiny input; verify cap·tanh(x/cap) at known points.
10755        let x = cpu_f32(vec![0.0_f32, 5.0, -5.0, 30.0], &[1, 4]);
10756        let capped = x.softcap(10.0).realize_f32();
10757        // tanh(0)=0; tanh(0.5)≈0.4621; tanh(-0.5)≈-0.4621; tanh(3)≈0.9951.
10758        let expect = [0.0_f32, 4.6212, -4.6212, 9.9505];
10759        for (i, (&got, &want)) in capped.iter().zip(expect.iter()).enumerate() {
10760            assert!(
10761                (got - want).abs() < 1e-3,
10762                "softcap[{i}] got={got} want={want}"
10763            );
10764        }
10765    }
10766
10767    #[test]
10768    fn softcap_optional_none_returns_input_unchanged() {
10769        let x = cpu_f32(vec![1.0_f32, -2.0, 30.0], &[1, 3]);
10770        let out = x.softcap_optional(None).realize_f32();
10771        let expect = [1.0_f32, -2.0, 30.0];
10772        for (g, w) in out.iter().zip(expect.iter()) {
10773            assert!((g - w).abs() < 1e-6);
10774        }
10775        // Some(0.0) or negative cap also returns unchanged (guard).
10776        let out = x.softcap_optional(Some(0.0)).realize_f32();
10777        for (g, w) in out.iter().zip(expect.iter()) {
10778            assert!((g - w).abs() < 1e-6);
10779        }
10780    }
10781
10782    #[test]
10783    fn rope_partial_full_dim_matches_rope_with_tables() {
10784        // head_dim == rope_dim ⇒ should degenerate to full rope.
10785        let qk = cpu_f32(vec![1.0_f32; 1 * 1 * 2 * 4], &[1, 1, 2, 4]);
10786        let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 2, 4);
10787        let via_partial = qk.rope_partial(&cos, &sin, 4).unwrap();
10788        let via_full = qk.rope_with_tables(&cos, &sin).unwrap();
10789        let a = via_partial.realize_f32();
10790        let b = via_full.realize_f32();
10791        for (i, (av, bv)) in a.iter().zip(b.iter()).enumerate() {
10792            assert!((av - bv).abs() < 1e-6, "{i}: {av} vs {bv}");
10793        }
10794    }
10795
10796    #[test]
10797    fn rope_partial_pass_through_suffix_unchanged() {
10798        // rope_dim=2, head_dim=4 ⇒ first 2 features rotated, last 2
10799        // unchanged. At position 0 the rotation is identity, so all 4
10800        // features should equal the input.
10801        let qk = cpu_f32(
10802            vec![
10803                // shape [1, 1, 1, 4] — one position, one head
10804                1.0_f32, 2.0, 3.0, 4.0,
10805            ],
10806            &[1, 1, 1, 4],
10807        );
10808        let (cos, sin) = qk.rope_tables_const(10_000.0, 0, 1, 2);
10809        let out = qk.rope_partial(&cos, &sin, 2).unwrap().realize_f32();
10810        for (i, &v) in out.iter().enumerate() {
10811            let expect = [1.0_f32, 2.0, 3.0, 4.0][i];
10812            assert!((v - expect).abs() < 1e-6, "{i}: {v} != {expect}");
10813        }
10814    }
10815
10816    #[test]
10817    fn add_optional_trailing_bias_none_returns_input_unchanged() {
10818        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10819        let original = a.realize_f32();
10820        let out = a.add_optional_trailing_bias(None).unwrap();
10821        assert_eq!(out.realize_f32(), original);
10822    }
10823
10824    #[test]
10825    fn add_optional_trailing_bias_some_applies_add() {
10826        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10827        let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, 20.0, 30.0]);
10828        let out = a.add_optional_trailing_bias(Some(&bias)).unwrap();
10829        assert_eq!(out.realize_f32(), vec![11.0, 22.0, 33.0]);
10830    }
10831
10832    #[test]
10833    fn add_trailing_bias_broadcasts_across_leading_dims() {
10834        // (2, 3) input + length-3 bias should add per-column.
10835        let x = cpu_f32(vec![1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0], &[2, 3]);
10836        let bias = std::sync::Arc::<[f32]>::from(vec![100.0_f32, 200.0, 300.0]);
10837        let out = x.add_trailing_bias(bias).unwrap();
10838        assert_eq!(out.shape().dims(), &[2, 3]);
10839        let v = out.realize_f32();
10840        assert_eq!(v, vec![101.0, 202.0, 303.0, 110.0, 220.0, 330.0]);
10841    }
10842
10843    #[test]
10844    fn rms_norm_affine_with_offset_adds_offset_to_each_gain() {
10845        let x = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10846        let gain_raw: [f32; 3] = [-0.5, 0.0, 0.5];
10847        let via_offset = x.rms_norm_affine_with_offset(&gain_raw, 1.0, 1e-6).unwrap();
10848        let gain_shifted = std::sync::Arc::<[f32]>::from(vec![0.5_f32, 1.0, 1.5]);
10849        let via_plain = x.rms_norm_affine(gain_shifted, 1e-6).unwrap();
10850        let a = via_offset.realize_f32();
10851        let b = via_plain.realize_f32();
10852        for (x, y) in a.iter().zip(b.iter()) {
10853            assert!((x - y).abs() < 1e-6, "{x} vs {y}");
10854        }
10855    }
10856
10857    #[test]
10858    fn global_avg_pool_2d_averages_spatial_dims() {
10859        // (1, 2, 2, 3) — two channels, 2×3 spatial.
10860        // Channel 0: 1..=6, mean = 3.5.
10861        // Channel 1: 10, 20, 30, 40, 50, 60, mean = 35.
10862        let x = cpu_f32(
10863            vec![
10864                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,
10865            ],
10866            &[1, 2, 2, 3],
10867        );
10868        let out = x.global_avg_pool_2d().unwrap();
10869        assert_eq!(out.shape().dims(), &[1, 2]);
10870        let v = out.realize_f32();
10871        assert!((v[0] - 3.5).abs() < 1e-5);
10872        assert!((v[1] - 35.0).abs() < 1e-4);
10873    }
10874
10875    #[test]
10876    fn channel_affine_4d_applies_per_channel_gain_and_bias() {
10877        // (1, 2, 2, 2) — two channels, each a 2×2 spatial map.
10878        let x = cpu_f32(
10879            vec![
10880                1.0_f32, 2.0, 3.0, 4.0, // channel 0
10881                10.0, 20.0, 30.0, 40.0, // channel 1
10882            ],
10883            &[1, 2, 2, 2],
10884        );
10885        let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5]);
10886        let bias = std::sync::Arc::<[f32]>::from(vec![1.0_f32, -10.0]);
10887        let out = x.channel_affine_4d(gain, bias).unwrap();
10888        let v = out.realize_f32();
10889        // Channel 0: gain=2, bias=1 → 2x+1
10890        assert_eq!(&v[0..4], &[3.0, 5.0, 7.0, 9.0]);
10891        // Channel 1: gain=0.5, bias=-10 → 0.5x-10
10892        assert_eq!(&v[4..8], &[-5.0, 0.0, 5.0, 10.0]);
10893    }
10894
10895    #[test]
10896    fn additive_causal_mask_has_strict_lower_triangle() {
10897        let anchor = cpu_f32(vec![0.0_f32], &[1]);
10898        let mask = Tensor::additive_causal_mask_like(&anchor, 4);
10899        assert_eq!(mask.shape().dims(), &[4, 4]);
10900        let v = mask.realize_f32();
10901        // Expected (-inf shown as 'x'):
10902        //   0 x x x
10903        //   0 0 x x
10904        //   0 0 0 x
10905        //   0 0 0 0
10906        for i in 0..4 {
10907            for j in 0..4 {
10908                let got = v[i * 4 + j];
10909                if j > i {
10910                    assert!(
10911                        got.is_infinite() && got.is_sign_negative(),
10912                        "above-diag (i={i}, j={j}) should be -inf, got {got}"
10913                    );
10914                } else {
10915                    assert_eq!(
10916                        got, 0.0,
10917                        "on/below-diag (i={i}, j={j}) should be 0, got {got}"
10918                    );
10919                }
10920            }
10921        }
10922    }
10923
10924    #[test]
10925    fn layer_norm_affine_unit_gain_zero_bias_matches_layer_norm_last_dim() {
10926        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10927        let gain = std::sync::Arc::<[f32]>::from(vec![1.0_f32; 3]);
10928        let bias = std::sync::Arc::<[f32]>::from(vec![0.0_f32; 3]);
10929        let out_affine = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10930        let out_plain = a.layer_norm_last_dim(1e-5).unwrap();
10931        let va = out_affine.realize_f32();
10932        let vp = out_plain.realize_f32();
10933        for (a, b) in va.iter().zip(vp.iter()) {
10934            assert!((a - b).abs() < 1e-5, "{a} vs {b}");
10935        }
10936    }
10937
10938    #[test]
10939    fn layer_norm_affine_applies_gain_and_bias() {
10940        let a = cpu_f32(vec![1.0_f32, 2.0, 3.0], &[1, 3]);
10941        let gain = std::sync::Arc::<[f32]>::from(vec![2.0_f32, 0.5, 1.5]);
10942        let bias = std::sync::Arc::<[f32]>::from(vec![10.0_f32, -5.0, 0.0]);
10943        let out = a.layer_norm_affine(gain, bias, 1e-5).unwrap();
10944        let v = out.realize_f32();
10945        // Manual: mean=2, var=2/3; normed = (x-2)/sqrt(2/3+1e-5).
10946        let mean = 2.0_f32;
10947        let var = ((1.0 - mean).powi(2) + (2.0 - mean).powi(2) + (3.0 - mean).powi(2)) / 3.0;
10948        let den = (var + 1e-5_f32).sqrt();
10949        let expected = [
10950            ((1.0 - mean) / den) * 2.0 + 10.0,
10951            ((2.0 - mean) / den) * 0.5 + (-5.0),
10952            ((3.0 - mean) / den) * 1.5 + 0.0,
10953        ];
10954        for (got, want) in v.iter().zip(expected.iter()) {
10955            assert!((got - want).abs() < 1e-4, "{got} vs {want}");
10956        }
10957    }
10958
10959    #[test]
10960    fn l2_normalize_last_dim_unit_norm_per_row() {
10961        // (2, 3): rows [3,4,0] (norm 5) and [1,2,2] (norm 3).
10962        let a = cpu_f32(vec![3.0, 4.0, 0.0, 1.0, 2.0, 2.0], &[2, 3]);
10963        let out = a.l2_normalize(1_usize, 1e-12).unwrap();
10964        assert_eq!(out.shape().dims(), &[2, 3]);
10965        let v = out.realize_f32();
10966        let row0_norm = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
10967        let row1_norm = (v[3] * v[3] + v[4] * v[4] + v[5] * v[5]).sqrt();
10968        assert!((row0_norm - 1.0).abs() < 1e-5, "row 0 norm = {row0_norm}");
10969        assert!((row1_norm - 1.0).abs() < 1e-5, "row 1 norm = {row1_norm}");
10970        // Row 0: [3,4,0]/5 → [0.6, 0.8, 0.0].
10971        assert!((v[0] - 0.6).abs() < 1e-5);
10972        assert!((v[1] - 0.8).abs() < 1e-5);
10973        assert!(v[2].abs() < 1e-5);
10974    }
10975
10976    #[test]
10977    fn l2_normalize_eps_zero_works_when_nonzero() {
10978        let a = cpu_f32(vec![1.0_f32, 0.0], &[2]);
10979        let out = a.l2_normalize(0_usize, 0.0).unwrap();
10980        let v = out.realize_f32();
10981        assert!((v[0] - 1.0).abs() < 1e-6);
10982        assert!(v[1].abs() < 1e-6);
10983    }
10984
10985    #[test]
10986    fn repeat_interleave_last_dim_matches_torch_semantics() {
10987        // (2, 3) input: rows [1,2,3] and [4,5,6]. dim=1, repeats=2
10988        // → each element becomes two consecutive copies:
10989        // (2, 6): [1,1,2,2,3,3] and [4,4,5,5,6,6].
10990        let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
10991        let out = a.repeat_interleave(1_usize, 2).unwrap();
10992        assert_eq!(out.shape().dims(), &[2, 6]);
10993        assert_eq!(
10994            out.realize_f32(),
10995            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]
10996        );
10997    }
10998
10999    #[test]
11000    fn repeat_interleave_middle_dim() {
11001        // (2, 2, 2) input. dim=1, repeats=3 → (2, 6, 2).
11002        let a = cpu_f32((0..8).map(|i| i as f32).collect(), &[2, 2, 2]);
11003        let out = a.repeat_interleave(1_usize, 3).unwrap();
11004        assert_eq!(out.shape().dims(), &[2, 6, 2]);
11005        // First sample's elements: (0,1) repeated 3× then (2,3) repeated 3×.
11006        let v = out.realize_f32();
11007        assert_eq!(&v[0..6], &[0.0, 1.0, 0.0, 1.0, 0.0, 1.0]);
11008        assert_eq!(&v[6..12], &[2.0, 3.0, 2.0, 3.0, 2.0, 3.0]);
11009    }
11010
11011    #[test]
11012    fn repeat_interleave_repeats_one_is_noop() {
11013        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11014        let out = a.repeat_interleave(0_usize, 1).unwrap();
11015        assert_eq!(out.shape().dims(), &[3]);
11016        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11017    }
11018
11019    #[test]
11020    fn repeat_interleave_repeats_zero_errors() {
11021        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11022        assert!(a.repeat_interleave(0_usize, 0).is_err());
11023    }
11024
11025    #[test]
11026    fn stack_adds_leading_dim() {
11027        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11028        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11029        let out = Tensor::stack(&[&a, &b], 0).unwrap();
11030        assert_eq!(out.shape().dims(), &[2, 3]);
11031        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
11032    }
11033
11034    #[test]
11035    fn stack_adds_trailing_dim() {
11036        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11037        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11038        let out = Tensor::stack(&[&a, &b], 1).unwrap();
11039        assert_eq!(out.shape().dims(), &[3, 2]);
11040        assert_eq!(out.realize_f32(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
11041    }
11042
11043    #[test]
11044    fn stack_rejects_mismatched_shapes() {
11045        let a = cpu_f32(vec![1.0, 2.0], &[2]);
11046        let b = a.const_f32_like(vec![3.0, 4.0, 5.0], vec![3]).unwrap();
11047        assert!(Tensor::stack(&[&a, &b], 0).is_err());
11048    }
11049
11050    #[test]
11051    fn stack_rejects_empty_input() {
11052        let result = Tensor::stack(&[], 0);
11053        assert!(result.is_err());
11054    }
11055
11056    #[test]
11057    fn repeat_tiles_along_each_dim() {
11058        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11059        let out = t.repeat(vec![3]).unwrap();
11060        assert_eq!(out.shape().dims(), &[6]);
11061        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 1.0, 2.0, 1.0, 2.0]);
11062    }
11063
11064    #[test]
11065    fn repeat_extends_rank_when_needed() {
11066        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11067        // repeat with shape [3, 2] left-pads tensor to [1, 2] then tiles to [3, 4]
11068        let out = t.repeat(vec![3, 2]).unwrap();
11069        assert_eq!(out.shape().dims(), &[3, 4]);
11070    }
11071
11072    #[test]
11073    fn repeat_identity_with_all_ones() {
11074        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11075        let out = t.repeat(vec![1]).unwrap();
11076        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0]);
11077    }
11078}
11079
11080// ============================================================================
11081// Phase A.3 keepdim reduction tests.
11082// ============================================================================
11083#[cfg(test)]
11084mod phase_a3_keepdim_tests {
11085    use super::*;
11086
11087    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11088        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11089    }
11090
11091    #[test]
11092    fn sum_keepdim_preserves_dim_as_one() {
11093        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11094        let out = t.sum_keepdim(1_usize).unwrap();
11095        assert_eq!(out.shape().dims(), &[2, 1]);
11096        assert_eq!(out.realize_f32(), vec![3.0, 7.0]);
11097    }
11098
11099    #[test]
11100    fn mean_keepdim_preserves_dim_as_one() {
11101        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11102        let out = t.mean_keepdim(0_usize).unwrap();
11103        assert_eq!(out.shape().dims(), &[1, 2]);
11104        assert_eq!(out.realize_f32(), vec![2.0, 3.0]);
11105    }
11106
11107    #[test]
11108    fn max_keepdim_preserves_dim_as_one() {
11109        let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11110        let out = t.max_keepdim(1_usize).unwrap();
11111        assert_eq!(out.shape().dims(), &[2, 1]);
11112        assert_eq!(out.realize_f32(), vec![3.0, 4.0]);
11113    }
11114
11115    #[test]
11116    fn min_keepdim_preserves_dim_as_one() {
11117        let t = cpu_f32(vec![1.0, 3.0, 2.0, 4.0], &[2, 2]);
11118        let out = t.min_keepdim(1_usize).unwrap();
11119        assert_eq!(out.shape().dims(), &[2, 1]);
11120        assert_eq!(out.realize_f32(), vec![1.0, 2.0]);
11121    }
11122
11123    // ---- the divisor clamps at zero: var = sum((x-mean)^2) / max(0, n - correction) ----
11124    // (ruling 2026-11-25, torch): extent == correction -> 0/0 = NaN; extent < correction -> x/0 =
11125    // inf (NaN if the sum is 0); NEVER negative. Before, `correction > n` gave a finite, possibly
11126    // NEGATIVE variance ([1,3] with correction 3 was -2.0).
11127
11128    /// `var(dim, correction)` of `data` (given as f64) in the named dtype, realized as f64.
11129    fn var_in(dtype: &str, data: &[f64], shape: &[usize], dim: usize, correction: f64) -> Vec<f64> {
11130        let dev = Device::cpu();
11131        let s = Shape::from_dims(shape);
11132        match dtype {
11133            "f32" => Tensor::from_f32(data.iter().map(|&x| x as f32).collect::<Vec<_>>(), s, &dev)
11134                .unwrap()
11135                .var(dim, correction)
11136                .unwrap()
11137                .realize_f32()
11138                .iter()
11139                .map(|&x| x as f64)
11140                .collect(),
11141            "f64" => Tensor::from_f64(data.to_vec(), s, &dev)
11142                .unwrap()
11143                .var(dim, correction)
11144                .unwrap()
11145                .realize_f64(),
11146            "f16" => Tensor::from_f16(
11147                data.iter()
11148                    .map(|&x| half::f16::from_f64(x))
11149                    .collect::<Vec<_>>(),
11150                s,
11151                &dev,
11152            )
11153            .unwrap()
11154            .var(dim, correction)
11155            .unwrap()
11156            .realize_f16()
11157            .iter()
11158            .map(|x| x.to_f64())
11159            .collect(),
11160            "bf16" => Tensor::from_bf16(
11161                data.iter()
11162                    .map(|&x| half::bf16::from_f64(x))
11163                    .collect::<Vec<_>>(),
11164                s,
11165                &dev,
11166            )
11167            .unwrap()
11168            .var(dim, correction)
11169            .unwrap()
11170            .realize_bf16()
11171            .iter()
11172            .map(|x| x.to_f64())
11173            .collect(),
11174            other => panic!("dtype {other}"),
11175        }
11176    }
11177
11178    /// PIP #715 L2: a NaN correction is a typed error, never a silently clamped zero divisor (`inf`).
11179    #[test]
11180    fn var_rejects_a_nan_correction() {
11181        let dev = Device::cpu();
11182        let x = Tensor::from_f32(vec![1.0, 3.0], Shape::from_dims(&[2]), &dev).unwrap();
11183        assert!(x.var_keepdim(0, f64::NAN).is_err());
11184        // control: the same call with a finite correction succeeds
11185        assert!(x.var_keepdim(0, 1.0).is_ok());
11186    }
11187
11188    #[test]
11189    fn var_divisor_is_clamped_at_zero_in_every_dtype() {
11190        for dt in ["f32", "f64", "f16", "bf16"] {
11191            // extent == correction: 0/0 = NaN
11192            assert!(var_in(dt, &[5.0], &[1], 0, 1.0)[0].is_nan(), "{dt} [5] c=1");
11193            let v = var_in(dt, &[5.0, 7.0], &[2, 1], 1, 1.0);
11194            assert!(v[0].is_nan() && v[1].is_nan(), "{dt} [[5],[7]] c=1: {v:?}");
11195            // extent == correction with a nonzero sum: x/0 = inf
11196            assert_eq!(
11197                var_in(dt, &[1.0, 3.0], &[2], 0, 2.0)[0],
11198                f64::INFINITY,
11199                "{dt} [1,3] c=2"
11200            );
11201            // extent < correction: a zero sum is NaN, a nonzero sum is inf, NEVER negative
11202            assert!(var_in(dt, &[5.0], &[1], 0, 2.0)[0].is_nan(), "{dt} [5] c=2");
11203            assert_eq!(
11204                var_in(dt, &[1.0, 3.0], &[2], 0, 3.0)[0],
11205                f64::INFINITY,
11206                "{dt} [1,3] c=3"
11207            );
11208            // controls: population variance of one element is 0; Bessel on two is 2
11209            assert_eq!(var_in(dt, &[5.0], &[1], 0, 0.0)[0], 0.0, "{dt} [5] c=0");
11210            assert_eq!(
11211                var_in(dt, &[1.0, 3.0], &[2], 0, 1.0)[0],
11212                2.0,
11213                "{dt} [1,3] c=1"
11214            );
11215        }
11216    }
11217
11218    #[test]
11219    fn var_matches_unbiased_formula_with_correction_1() {
11220        // [[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
11221        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11222        let out = t.var(1, 1.0).unwrap();
11223        assert_eq!(out.shape().dims(), &[2]);
11224        let v = out.realize_f32();
11225        assert!((v[0] - 1.0).abs() < 1e-5, "var row 0 = {} != 1.0", v[0]);
11226        assert!((v[1] - 1.0).abs() < 1e-5, "var row 1 = {} != 1.0", v[1]);
11227    }
11228
11229    /// KISS-Ops §6.13 S14: `correction = 0.0` (the spec default, numpy's
11230    /// default) divides by `n` instead of `n - 1` -- same fixture as the
11231    /// Bessel test above, different divisor, so the two tests pin BOTH
11232    /// halves of the explicit-attribute contract against the same data.
11233    #[test]
11234    fn var_population_with_correction_0() {
11235        // Same fixture: dev=[-1,0,1], sq sum=2, /3 = 0.666...
11236        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11237        let out = t.var(1, 0.0).unwrap();
11238        let v = out.realize_f32();
11239        let want = 2.0 / 3.0;
11240        assert!(
11241            (v[0] - want).abs() < 1e-5,
11242            "population var row 0 = {} != {want}",
11243            v[0]
11244        );
11245        assert!(
11246            (v[1] - want).abs() < 1e-5,
11247            "population var row 1 = {} != {want}",
11248            v[1]
11249        );
11250    }
11251
11252    #[test]
11253    fn var_keepdim_preserves_dim() {
11254        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11255        let out = t.var_keepdim(1, 1.0).unwrap();
11256        assert_eq!(out.shape().dims(), &[2, 1]);
11257    }
11258
11259    #[test]
11260    fn var_errors_out_of_bounds() {
11261        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11262        assert!(t.var(3, 1.0).is_err());
11263        assert!(t.var_keepdim(3, 1.0).is_err());
11264    }
11265}
11266
11267// ============================================================================
11268// Phase A.4 scalar/binary composite tests.
11269// ============================================================================
11270#[cfg(test)]
11271mod phase_a4_composite_tests {
11272    use super::*;
11273
11274    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11275        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11276    }
11277
11278    #[test]
11279    fn affine_applies_mul_then_add() {
11280        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11281        let out = t.affine(2.0, 10.0);
11282        assert_eq!(out.realize_f32(), vec![12.0, 14.0, 16.0]);
11283    }
11284
11285    #[test]
11286    fn scale_and_shift_alias_of_affine() {
11287        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11288        assert_eq!(
11289            t.scale_and_shift(2.0, 10.0).realize_f32(),
11290            t.affine(2.0, 10.0).realize_f32(),
11291        );
11292    }
11293
11294    #[test]
11295    fn elu_matches_reference_values() {
11296        let t = cpu_f32(vec![1.0, 0.0, -1.0, -2.0], &[4]);
11297        let out = t.elu(1.0);
11298        let v = out.realize_f32();
11299        // x > 0: identity. x == 0: 0 (boundary; gt returns 0 → neg branch which is alpha*(1-1)=0).
11300        // x < 0: alpha * (exp(x) - 1).
11301        assert!((v[0] - 1.0).abs() < 1e-5);
11302        assert!(v[1].abs() < 1e-5);
11303        assert!((v[2] - ((-1.0_f32).exp() - 1.0)).abs() < 1e-5);
11304        assert!((v[3] - ((-2.0_f32).exp() - 1.0)).abs() < 1e-5);
11305    }
11306
11307    #[test]
11308    fn dot_of_rank_one_vectors() {
11309        let a = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11310        let b = a.const_f32_like(vec![4.0, 5.0, 6.0], vec![3]).unwrap();
11311        let out = a.dot(&b).unwrap();
11312        assert_eq!(out.shape().elem_count(), 1);
11313        let v = out.realize_f32();
11314        assert_eq!(v[0], 32.0); // 1*4 + 2*5 + 3*6
11315    }
11316
11317    #[test]
11318    fn dot_rejects_non_rank_one() {
11319        let a = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11320        let b = a
11321            .const_f32_like(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])
11322            .unwrap();
11323        assert!(a.dot(&b).is_err());
11324    }
11325
11326    #[test]
11327    fn dot_rejects_length_mismatch() {
11328        let a = cpu_f32(vec![1.0, 2.0], &[2]);
11329        let b = a.const_f32_like(vec![1.0, 2.0, 3.0], vec![3]).unwrap();
11330        assert!(a.dot(&b).is_err());
11331    }
11332
11333    #[test]
11334    fn mv_matrix_times_vector() {
11335        let m = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
11336        let v = m.const_f32_like(vec![1.0, 1.0, 1.0], vec![3]).unwrap();
11337        let out = m.mv(&v).unwrap();
11338        assert_eq!(out.shape().dims(), &[2]);
11339        assert_eq!(out.realize_f32(), vec![6.0, 15.0]);
11340    }
11341
11342    #[test]
11343    fn matvec_is_mv_alias() {
11344        let m = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11345        let v = m.const_f32_like(vec![3.0, 4.0], vec![2]).unwrap();
11346        let a = m.mv(&v).unwrap().realize_f32();
11347        let b = m.matvec(&v).unwrap().realize_f32();
11348        assert_eq!(a, b);
11349    }
11350
11351    #[test]
11352    fn mv_rejects_shape_mismatch() {
11353        let m = cpu_f32(vec![1.0; 6], &[2, 3]);
11354        let v = m.const_f32_like(vec![1.0, 1.0], vec![2]).unwrap();
11355        assert!(m.mv(&v).is_err());
11356    }
11357
11358    #[test]
11359    fn broadcast_matmul_passes_through_to_matmul() {
11360        let a = cpu_f32(vec![1.0, 0.0, 0.0, 1.0], &[2, 2]);
11361        let b = a
11362            .const_f32_like(vec![5.0, 6.0, 7.0, 8.0], vec![2, 2])
11363            .unwrap();
11364        let out = a.broadcast_matmul(&b).unwrap();
11365        assert_eq!(out.realize_f32(), vec![5.0, 6.0, 7.0, 8.0]);
11366    }
11367}
11368
11369// ============================================================================
11370// Phase A.5 factory family tests.
11371// ============================================================================
11372#[cfg(test)]
11373mod phase_a5_factory_tests {
11374    use super::*;
11375
11376    fn cpu_f32(data: Vec<f32>, shape: &[usize]) -> Tensor {
11377        Tensor::from_f32(data, shape.to_vec(), &Device::cpu()).unwrap()
11378    }
11379
11380    #[test]
11381    fn ones_like_matches_shape_dtype_graph() {
11382        let t = cpu_f32(vec![5.0, 6.0, 7.0, 8.0], &[2, 2]);
11383        let ones = t.ones_like().unwrap();
11384        assert_eq!(ones.shape().dims(), t.shape().dims());
11385        assert_eq!(ones.dtype(), t.dtype());
11386        assert_eq!(ones.realize_f32(), vec![1.0; 4]);
11387    }
11388
11389    #[test]
11390    fn zeros_like_matches_shape_dtype_graph() {
11391        let t = cpu_f32(vec![5.0, 6.0, 7.0], &[3]);
11392        let zeros = t.zeros_like().unwrap();
11393        assert_eq!(zeros.realize_f32(), vec![0.0; 3]);
11394    }
11395
11396    #[test]
11397    fn static_ones_f32() {
11398        let t = Tensor::ones(vec![2, 3], DType::F32, &Device::cpu()).unwrap();
11399        assert_eq!(t.shape().dims(), &[2, 3]);
11400        assert_eq!(t.realize_f32(), vec![1.0; 6]);
11401    }
11402
11403    #[test]
11404    fn static_zeros_f64() {
11405        let t = Tensor::zeros(vec![4], DType::F64, &Device::cpu()).unwrap();
11406        assert_eq!(t.dtype(), DType::F64);
11407        assert_eq!(t.realize_f64(), vec![0.0; 4]);
11408    }
11409
11410    #[test]
11411    fn full_with_f32_scalar() {
11412        let t = Tensor::full(vec![5], fuel_ir::Scalar::F32(2.5), &Device::cpu()).unwrap();
11413        assert_eq!(t.realize_f32(), vec![2.5; 5]);
11414    }
11415
11416    #[test]
11417    fn eye_identity_matrix() {
11418        let t = Tensor::eye(3, DType::F32, &Device::cpu());
11419        assert_eq!(t.shape().dims(), &[3, 3]);
11420        assert_eq!(
11421            t.realize_f32(),
11422            vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
11423        );
11424    }
11425
11426    #[test]
11427    fn tril2_lower_triangular_ones() {
11428        let t = Tensor::tril2(3, DType::F32, &Device::cpu());
11429        assert_eq!(
11430            t.realize_f32(),
11431            vec![1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0],
11432        );
11433    }
11434
11435    #[test]
11436    fn triu2_upper_triangular_ones() {
11437        let t = Tensor::triu2(3, DType::F32, &Device::cpu());
11438        assert_eq!(
11439            t.realize_f32(),
11440            vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0],
11441        );
11442    }
11443
11444    #[test]
11445    fn meshgrid_ij_indexing_two_inputs() {
11446        let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11447        let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11448        let grids = Tensor::meshgrid(&[&x, &y], false).unwrap();
11449        assert_eq!(grids.len(), 2);
11450        // ij: shapes are [len(x), len(y)] = [3, 2].
11451        assert_eq!(grids[0].shape().dims(), &[3, 2]);
11452        assert_eq!(grids[1].shape().dims(), &[3, 2]);
11453        // X grid: each row repeats x's value, so each row is identical along axis 1.
11454        assert_eq!(grids[0].realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
11455        // Y grid: each column repeats y's value, so each column is identical along axis 0.
11456        assert_eq!(grids[1].realize_f32(), vec![4.0, 5.0, 4.0, 5.0, 4.0, 5.0]);
11457    }
11458
11459    #[test]
11460    fn meshgrid_xy_indexing_swaps_first_two() {
11461        let x = Tensor::from_f32(vec![1.0_f32, 2.0, 3.0], vec![3], &Device::cpu()).unwrap();
11462        let y = x.const_f32_like(vec![4.0_f32, 5.0], vec![2]).unwrap();
11463        let grids = Tensor::meshgrid(&[&x, &y], true).unwrap();
11464        // xy: shapes flip to [len(y), len(x)] = [2, 3].
11465        assert_eq!(grids[0].shape().dims(), &[2, 3]);
11466        assert_eq!(grids[1].shape().dims(), &[2, 3]);
11467        // X grid: same row twice, each row is x.
11468        assert_eq!(grids[0].realize_f32(), vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
11469        // Y grid: each row repeats one y element.
11470        assert_eq!(grids[1].realize_f32(), vec![4.0, 4.0, 4.0, 5.0, 5.0, 5.0]);
11471    }
11472
11473    #[test]
11474    fn meshgrid_rejects_single_input() {
11475        let x = Tensor::from_f32(vec![1.0_f32, 2.0], vec![2], &Device::cpu()).unwrap();
11476        assert!(Tensor::meshgrid(&[&x], false).is_err());
11477    }
11478
11479    #[test]
11480    fn meshgrid_rejects_non_rank_one() {
11481        let x = Tensor::from_f32(vec![1.0; 4], vec![2, 2], &Device::cpu()).unwrap();
11482        let y = x.const_f32_like(vec![1.0, 2.0], vec![2]).unwrap();
11483        assert!(Tensor::meshgrid(&[&x, &y], false).is_err());
11484    }
11485
11486    // ---- additional deferred-Phase-A item tests ----
11487
11488    #[test]
11489    fn narrow_is_slice_alias() {
11490        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5]);
11491        let a = t.narrow(0, 1, 3).unwrap().realize_f32();
11492        let b = t.slice(0, 1, 3).unwrap().realize_f32();
11493        assert_eq!(a, b);
11494        assert_eq!(a, vec![2.0, 3.0, 4.0]);
11495    }
11496
11497    #[test]
11498    fn chunk_splits_evenly() {
11499        let t = cpu_f32((1..=6).map(|i| i as f32).collect(), &[6]);
11500        let parts = t.chunk(3, 0).unwrap();
11501        assert_eq!(parts.len(), 3);
11502        assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0]);
11503        assert_eq!(parts[1].realize_f32(), vec![3.0, 4.0]);
11504        assert_eq!(parts[2].realize_f32(), vec![5.0, 6.0]);
11505    }
11506
11507    #[test]
11508    fn chunk_distributes_remainder_to_leading() {
11509        // size 7, 3 chunks → first 7%3=1 chunk gets the extra: sizes 3, 2, 2
11510        let t = cpu_f32((1..=7).map(|i| i as f32).collect(), &[7]);
11511        let parts = t.chunk(3, 0).unwrap();
11512        assert_eq!(parts.len(), 3);
11513        assert_eq!(parts[0].realize_f32(), vec![1.0, 2.0, 3.0]);
11514        assert_eq!(parts[1].realize_f32(), vec![4.0, 5.0]);
11515        assert_eq!(parts[2].realize_f32(), vec![6.0, 7.0]);
11516    }
11517
11518    #[test]
11519    fn chunk_returns_singletons_when_size_less_than_chunks() {
11520        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11521        let parts = t.chunk(5, 0).unwrap();
11522        assert_eq!(parts.len(), 2);
11523        assert_eq!(parts[0].realize_f32(), vec![1.0]);
11524        assert_eq!(parts[1].realize_f32(), vec![2.0]);
11525    }
11526
11527    #[test]
11528    fn get_at_first_dim() {
11529        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11530        let row1 = t.get(1).unwrap();
11531        assert_eq!(row1.shape().dims(), &[2]);
11532        assert_eq!(row1.realize_f32(), vec![3.0, 4.0]);
11533    }
11534
11535    #[test]
11536    fn get_on_dim_arbitrary_axis() {
11537        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2]);
11538        let col0 = t.get_on_dim(1, 0).unwrap();
11539        assert_eq!(col0.shape().dims(), &[3]);
11540        assert_eq!(col0.realize_f32(), vec![1.0, 3.0, 5.0]);
11541    }
11542
11543    #[test]
11544    fn sum_dims_multi_dim_reduces_to_smaller() {
11545        // [2,3,4] sum over (0, 2) → [3]
11546        let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11547        let s = t.sum_dims([0, 2_usize]).unwrap();
11548        assert_eq!(s.shape().dims(), &[3]);
11549        // each element is 2*4 = 8 (sum across dim 0 = 2 elements, dim 2 = 4 elements)
11550        assert_eq!(s.realize_f32(), vec![8.0; 3]);
11551    }
11552
11553    #[test]
11554    fn mean_dims_multi_dim() {
11555        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11556        let m = t.mean_dims([0, 1_usize]).unwrap();
11557        assert_eq!(m.shape().dims(), &[] as &[usize]);
11558        assert_eq!(m.realize_f32(), vec![2.5]);
11559    }
11560
11561    #[test]
11562    fn sum_dims_keepdim_preserves_rank() {
11563        let t = cpu_f32(vec![1.0; 24], &[2, 3, 4]);
11564        let s = t.sum_dims_keepdim(&[0, 2]).unwrap();
11565        assert_eq!(s.shape().dims(), &[1, 3, 1]);
11566    }
11567
11568    #[test]
11569    fn mean_dims_keepdim_preserves_rank() {
11570        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11571        let m = t.mean_dims_keepdim(&[0, 1]).unwrap();
11572        assert_eq!(m.shape().dims(), &[1, 1]);
11573        assert_eq!(m.realize_f32(), vec![2.5]);
11574    }
11575
11576    #[test]
11577    fn rand_like_matches_shape_dtype() {
11578        let t = cpu_f32(vec![0.0; 6], &[2, 3]);
11579        let r = t.rand_like(-1.0, 1.0).unwrap();
11580        assert_eq!(r.shape().dims(), t.shape().dims());
11581        assert_eq!(r.dtype(), t.dtype());
11582        // Every sample must be in [-1, 1).
11583        for v in r.realize_f32() {
11584            assert!((-1.0..1.0).contains(&v), "sample {v} out of [-1, 1)");
11585        }
11586    }
11587
11588    #[test]
11589    fn randn_like_matches_shape_dtype() {
11590        let t = cpu_f32(vec![0.0; 4], &[4]);
11591        let r = t.randn_like(0.0, 1.0).unwrap();
11592        assert_eq!(r.shape().dims(), &[4]);
11593        assert_eq!(r.dtype(), DType::F32);
11594        // Samples are random — just sanity-check they're finite.
11595        for v in r.realize_f32() {
11596            assert!(v.is_finite());
11597        }
11598    }
11599
11600    #[test]
11601    fn static_rand_f32() {
11602        let t = Tensor::rand(vec![100], 0.0, 1.0, DType::F32, &Device::cpu()).unwrap();
11603        let v = t.realize_f32();
11604        // Mean of uniform [0,1) should be ~0.5; tolerate sample noise.
11605        let mean: f32 = v.iter().sum::<f32>() / v.len() as f32;
11606        assert!((0.3..0.7).contains(&mean), "mean {mean} too far from 0.5");
11607    }
11608
11609    #[test]
11610    fn static_randn_f64() {
11611        let t = Tensor::randn(vec![1000], 0.0, 1.0, DType::F64, &Device::cpu()).unwrap();
11612        let v = t.realize_f64();
11613        let mean: f64 = v.iter().sum::<f64>() / v.len() as f64;
11614        // Normal(0,1) mean should be near 0; n=1000 gives stderr ~0.03.
11615        assert!(mean.abs() < 0.2, "mean {mean} too far from 0");
11616    }
11617
11618    #[test]
11619    fn arange_int_step() {
11620        let t = Tensor::arange(0.0, 5.0, &Device::cpu());
11621        assert_eq!(t.shape().dims(), &[5]);
11622        assert_eq!(t.realize_f32(), vec![0.0, 1.0, 2.0, 3.0, 4.0]);
11623    }
11624
11625    #[test]
11626    fn arange_step_fractional() {
11627        let t = Tensor::arange_step(2.0, 4.0, 0.5, &Device::cpu());
11628        assert_eq!(t.realize_f32(), vec![2.0, 2.5, 3.0, 3.5]);
11629    }
11630
11631    #[test]
11632    fn arange_step_negative_descends() {
11633        let t = Tensor::arange_step(5.0, 0.0, -1.0, &Device::cpu());
11634        assert_eq!(t.realize_f32(), vec![5.0, 4.0, 3.0, 2.0, 1.0]);
11635    }
11636
11637    #[test]
11638    fn linspace_includes_endpoints() {
11639        let t = Tensor::linspace(0.0, 1.0, 5, &Device::cpu());
11640        assert_eq!(t.shape().dims(), &[5]);
11641        let v = t.realize_f32();
11642        assert!((v[0] - 0.0).abs() < 1e-6);
11643        assert!((v[4] - 1.0).abs() < 1e-6);
11644        assert!((v[2] - 0.5).abs() < 1e-6);
11645    }
11646
11647    #[test]
11648    fn linspace_n_one_returns_start() {
11649        let t = Tensor::linspace(7.0, 99.0, 1, &Device::cpu());
11650        assert_eq!(t.realize_f32(), vec![7.0]);
11651    }
11652
11653    #[test]
11654    fn norm_is_sqrt_sum_sq() {
11655        let t = Tensor::from_f32(vec![3.0_f32, 4.0], vec![2], &Device::cpu()).unwrap();
11656        let n = t.norm();
11657        assert!((n.realize_f32()[0] - 5.0).abs() < 1e-6);
11658    }
11659
11660    #[test]
11661    fn pad_with_zeros_left_and_right() {
11662        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11663        let p = t.pad_with_zeros(0, 2, 1).unwrap();
11664        assert_eq!(p.shape().dims(), &[6]);
11665        assert_eq!(p.realize_f32(), vec![0.0, 0.0, 1.0, 2.0, 3.0, 0.0]);
11666    }
11667
11668    #[test]
11669    fn pad_with_zeros_identity_when_both_zero() {
11670        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11671        let p = t.pad_with_zeros(0, 0, 0).unwrap();
11672        assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11673    }
11674
11675    #[test]
11676    fn pad_with_zeros_rejects_bad_dim() {
11677        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11678        assert!(t.pad_with_zeros(3, 1, 1).is_err());
11679    }
11680
11681    #[test]
11682    fn pad_with_value_zero_matches_pad_with_zeros() {
11683        // pad_with_value(_, _, _, 0.0) must be observationally identical
11684        // to pad_with_zeros — the latter is now a wrapper for the former.
11685        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11686        let via_zeros = t.pad_with_zeros(0, 1, 2).unwrap();
11687        let via_value = t.pad_with_value(0, 1, 2, 0.0).unwrap();
11688        assert_eq!(via_zeros.shape().dims(), via_value.shape().dims());
11689        assert_eq!(via_zeros.shape().dims(), &[5, 2]);
11690        assert_eq!(via_zeros.realize_f32(), via_value.realize_f32());
11691        assert_eq!(
11692            via_value.realize_f32(),
11693            vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0],
11694        );
11695    }
11696
11697    #[test]
11698    fn pad_with_value_neg_inf_then_max_reduce_ignores_pad() {
11699        // Negative interior values: -1, -2, -3. Pad with -inf on both
11700        // sides. Max along dim 0 must be the interior max (-1.0), not
11701        // -inf. This is the load-bearing property for max_pool2d.
11702        let t = cpu_f32(vec![-1.0, -2.0, -3.0], &[3]);
11703        let padded = t.pad_with_value(0, 2, 2, f32::NEG_INFINITY).unwrap();
11704        assert_eq!(padded.shape().dims(), &[7]);
11705        let v = padded.realize_f32();
11706        // Layout: [-inf, -inf, -1, -2, -3, -inf, -inf]
11707        assert!(v[0].is_infinite() && v[0].is_sign_negative());
11708        assert!(v[1].is_infinite() && v[1].is_sign_negative());
11709        assert_eq!(v[2], -1.0);
11710        assert_eq!(v[3], -2.0);
11711        assert_eq!(v[4], -3.0);
11712        assert!(v[5].is_infinite() && v[5].is_sign_negative());
11713        assert!(v[6].is_infinite() && v[6].is_sign_negative());
11714        // max along the only dim drops the pad and returns the interior max.
11715        let m = padded.max_all().realize_f32();
11716        assert_eq!(m, vec![-1.0]);
11717    }
11718
11719    #[test]
11720    fn pad_with_value_identity_when_both_zero() {
11721        // The early-out path must fire regardless of value (no spurious
11722        // graph node when there's nothing to pad).
11723        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
11724        let p = t.pad_with_value(0, 0, 0, f32::NEG_INFINITY).unwrap();
11725        assert_eq!(p.realize_f32(), vec![1.0, 2.0, 3.0]);
11726    }
11727
11728    #[test]
11729    fn pad_with_value_rejects_bad_dim() {
11730        let t = cpu_f32(vec![1.0, 2.0], &[2]);
11731        assert!(t.pad_with_value(3, 1, 1, 0.0).is_err());
11732    }
11733
11734    #[test]
11735    fn max_pool2d_with_pad_value_neg_inf_on_negative_interior() {
11736        // Negative-only interior values: a zero-padded max_pool2d would
11737        // incorrectly return 0 in boundary windows. -inf padding gives
11738        // the PyTorch-correct answer (the interior max).
11739        //
11740        // 1x1x3x3 tensor, all values negative:
11741        //   [ -1, -2, -3 ]
11742        //   [ -4, -5, -6 ]
11743        //   [ -7, -8, -9 ]
11744        // With kernel=3, stride=1, padding=1, output is 3x3 where the
11745        // (1,1) center sees the full grid → max = -1.
11746        let x = cpu_f32(
11747            vec![-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0],
11748            &[1, 1, 3, 3],
11749        );
11750        let out = x
11751            .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), f32::NEG_INFINITY)
11752            .unwrap();
11753        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
11754        let v = out.realize_f32();
11755        // Top-left corner (0,0): window sees only [(0,0),(0,1),(1,0),(1,1)]
11756        // = [-1,-2,-4,-5]; padded slots are -inf → max = -1.
11757        assert_eq!(v[0], -1.0);
11758        // Center (1,1): no padded slots in window → max of all 9 = -1.
11759        assert_eq!(v[4], -1.0);
11760        // Bottom-right (2,2): window sees [(1,1),(1,2),(2,1),(2,2)]
11761        // = [-5,-6,-8,-9]; padded slots are -inf → max = -5.
11762        assert_eq!(v[8], -5.0);
11763
11764        // KISS-Ops S14: `max_pool2d`'s own default pad value was 0.0
11765        // ("legacy behavior") -- the exact bug this test file demonstrates
11766        // above -- and is now `f32::NEG_INFINITY`. So `max_pool2d` (no
11767        // explicit pad value) must now agree with the NEG_INFINITY variant
11768        // above, not with a zero-padded one; the OLD zero-padded answer is
11769        // only reachable by asking for it explicitly via
11770        // `max_pool2d_with_pad_value(..., 0.0)`, which this block also
11771        // checks, to keep BOTH halves of the fix (new default AND old
11772        // explicit escape hatch) under one assertion.
11773        let default_pad = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
11774        let vd = default_pad.realize_f32();
11775        assert_eq!(
11776            vd[0], -1.0,
11777            "max_pool2d's default must now match NEG_INFINITY padding, not 0.0"
11778        );
11779        assert_eq!(vd[8], -5.0);
11780
11781        let explicit_zero_pad = x
11782            .max_pool2d_with_pad_value((3, 3), (1, 1), (1, 1), 0.0)
11783            .unwrap();
11784        let vz = explicit_zero_pad.realize_f32();
11785        assert_eq!(
11786            vz[0], 0.0,
11787            "explicit 0.0 padding must still be reachable via max_pool2d_with_pad_value"
11788        );
11789        assert_eq!(vz[8], 0.0);
11790    }
11791
11792    #[test]
11793    fn max_pool2d_with_pad_value_zero_matches_max_pool2d() {
11794        // With pad_value = 0.0, the new variant must agree with the
11795        // legacy max_pool2d byte-for-byte.
11796        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11797        let x = cpu_f32(data, &[1, 1, 4, 4]);
11798        let a = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
11799        let b = x
11800            .max_pool2d_with_pad_value((2, 2), (2, 2), (0, 0), 0.0)
11801            .unwrap();
11802        assert_eq!(a.shape().dims(), b.shape().dims());
11803        assert_eq!(a.realize_f32(), b.realize_f32());
11804    }
11805
11806    // ---- Phase A.6 conv1d composite tests ----
11807
11808    #[test]
11809    fn conv1d_identity_kernel_passes_input_through() {
11810        // Single-batch, single-channel, kernel-1 identity → output equals input.
11811        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[1, 1, 5]);
11812        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11813        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11814        assert_eq!(out.shape().dims(), &[1, 1, 5]);
11815        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
11816    }
11817
11818    #[test]
11819    fn conv1d_sum_kernel_two_wide() {
11820        // Sum kernel of size 2: out[t] = x[t] + x[t+1].
11821        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11822        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11823        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11824        assert_eq!(out.shape().dims(), &[1, 1, 3]);
11825        assert_eq!(out.realize_f32(), vec![3.0, 5.0, 7.0]);
11826    }
11827
11828    #[test]
11829    fn conv1d_with_bias_applies_correctly() {
11830        let x = cpu_f32(vec![1.0, 1.0, 1.0], &[1, 1, 3]);
11831        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11832        let bias = x.const_f32_like(vec![10.0], vec![1]).unwrap();
11833        let out = x.conv1d(&w, Some(&bias), 1, 0, 1).unwrap();
11834        assert_eq!(out.realize_f32(), vec![11.0, 11.0, 11.0]);
11835    }
11836
11837    #[test]
11838    fn conv1d_stride_two_halves_output() {
11839        // Input length 6, kernel 2, stride 2 → output length (6-2)/2+1 = 3.
11840        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[1, 1, 6]);
11841        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11842        let out = x.conv1d(&w, None, 2, 0, 1).unwrap();
11843        assert_eq!(out.shape().dims(), &[1, 1, 3]);
11844        assert_eq!(out.realize_f32(), vec![3.0, 7.0, 11.0]);
11845    }
11846
11847    #[test]
11848    fn conv1d_padding_one_preserves_length() {
11849        // Input length 4, kernel 3, padding 1, stride 1 → output length 4.
11850        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11851        let w = x
11852            .const_f32_like(vec![1.0, 1.0, 1.0], vec![1, 1, 3])
11853            .unwrap();
11854        let out = x.conv1d(&w, None, 1, 1, 1).unwrap();
11855        assert_eq!(out.shape().dims(), &[1, 1, 4]);
11856        // out[0] = 0+x[0]+x[1] = 3; out[1] = x[0]+x[1]+x[2] = 6;
11857        // out[2] = x[1]+x[2]+x[3] = 9; out[3] = x[2]+x[3]+0 = 7
11858        assert_eq!(out.realize_f32(), vec![3.0, 6.0, 9.0, 7.0]);
11859    }
11860
11861    #[test]
11862    fn conv1d_multi_channel_output() {
11863        // 1 batch, 1 in-channel, 3 timesteps; 2 out-channels with kernel 1.
11864        let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
11865        // Weight [Cout=2, Cin=1, K=1]: filter 0 = 2.0, filter 1 = -1.0.
11866        let w = x.const_f32_like(vec![2.0, -1.0], vec![2, 1, 1]).unwrap();
11867        let out = x.conv1d(&w, None, 1, 0, 1).unwrap();
11868        assert_eq!(out.shape().dims(), &[1, 2, 3]);
11869        // Channel 0: 2.0 × input. Channel 1: -1.0 × input.
11870        assert_eq!(out.realize_f32(), vec![2.0, 4.0, 6.0, -1.0, -2.0, -3.0]);
11871    }
11872
11873    #[test]
11874    fn conv1d_rejects_rank_two_input() {
11875        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
11876        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11877        assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11878    }
11879
11880    #[test]
11881    fn conv1d_rejects_rank_two_weight() {
11882        let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11883        let w = x.const_f32_like(vec![1.0], vec![1, 1]).unwrap();
11884        assert!(x.conv1d(&w, None, 1, 0, 1).is_err());
11885    }
11886
11887    #[test]
11888    fn conv1d_rejects_zero_groups_or_stride() {
11889        let x = cpu_f32(vec![1.0; 4], &[1, 1, 4]);
11890        let w = x.const_f32_like(vec![1.0], vec![1, 1, 1]).unwrap();
11891        assert!(x.conv1d(&w, None, 0, 0, 1).is_err());
11892        assert!(x.conv1d(&w, None, 1, 0, 0).is_err());
11893    }
11894
11895    #[test]
11896    fn conv1d_with_algo_ignores_algo_param() {
11897        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 4]);
11898        let w = x.const_f32_like(vec![1.0, 1.0], vec![1, 1, 2]).unwrap();
11899        // Pass a dummy algo (the parameter is ignored on the lazy path).
11900        let a = x.conv1d_with_algo(&w, None, 1, 0, 1, "unused").unwrap();
11901        let b = x.conv1d(&w, None, 1, 0, 1).unwrap();
11902        assert_eq!(a.realize_f32(), b.realize_f32());
11903    }
11904
11905    // ---- Phase A.7 pooling / interpolation composite tests ----
11906
11907    #[test]
11908    fn avg_pool2d_2x2_stride2() {
11909        // 1×1×4×4 input with values 0..15.
11910        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
11911        let x = cpu_f32(data, &[1, 1, 4, 4]);
11912        let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
11913        assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
11914        // Each 2x2 block average: top-left = (0+1+4+5)/4 = 2.5,
11915        // top-right = (2+3+6+7)/4 = 4.5, bottom-left = (8+9+12+13)/4 = 10.5,
11916        // bottom-right = (10+11+14+15)/4 = 12.5.
11917        let v = out.realize_f32();
11918        assert!((v[0] - 2.5).abs() < 1e-5);
11919        assert!((v[1] - 4.5).abs() < 1e-5);
11920        assert!((v[2] - 10.5).abs() < 1e-5);
11921        assert!((v[3] - 12.5).abs() < 1e-5);
11922    }
11923
11924    #[test]
11925    fn avg_pool2d_3x3_stride1_padding1_preserves_size() {
11926        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11927        let out = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11928        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
11929    }
11930
11931    /// KISS-Ops §6.13 S14: `count_include_pad = false` must divide each
11932    /// border window by its TRUE valid-tap count, not the uniform `kh·kw`.
11933    /// Fixture: a 1x1x4x4 all-ones input, 3x3 kernel, padding 1.
11934    ///
11935    /// `excluded` (count_include_pad=false) must be EXACTLY 1.0 at every
11936    /// output position, border included: averaging any positive count of
11937    /// real taps that are all 1.0 is always 1.0, regardless of how many
11938    /// padded slots surround them — this is the invariant the fix exists
11939    /// to restore. `included` (count_include_pad=true, today's old
11940    /// behavior) must NOT share that invariant: it divides by the uniform
11941    /// 9 regardless of how many taps were real, so a corner window (only
11942    /// 4 of 9 taps real) computes `4/9 ≈ 0.444`, well below 1.0 — the two
11943    /// modes genuinely disagree at the border, which is the point of the
11944    /// fix. (On fully-interior positions, where every tap is real either
11945    /// way, both modes necessarily agree — not asserted here since it
11946    /// proves nothing about the fix; see the non-uniform fixture below for
11947    /// a sharper per-position contrast.)
11948    #[test]
11949    fn avg_pool2d_excludes_padding_keeps_uniform_data_exactly_at_its_true_value() {
11950        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
11951        let included = x.avg_pool2d((3, 3), (1, 1), (1, 1), true).unwrap();
11952        let excluded = x.avg_pool2d((3, 3), (1, 1), (1, 1), false).unwrap();
11953        assert_eq!(included.shape().dims(), excluded.shape().dims());
11954
11955        let ve = excluded.realize_f32();
11956        for (i, &v) in ve.iter().enumerate() {
11957            assert!(
11958                (v - 1.0).abs() < 1e-5,
11959                "count_include_pad=false must be exactly 1.0 at every position \
11960                 (all real taps are 1.0) — position {i} got {v}",
11961            );
11962        }
11963
11964        let vi = included.realize_f32();
11965        assert!(
11966            (vi[0] - 1.0).abs() > 0.1,
11967            "count_include_pad=true must NOT match at a corner (4 of 9 taps \
11968             real → 4/9, far from 1.0) — got {}, modes should disagree here",
11969            vi[0]
11970        );
11971    }
11972
11973    /// The actual discriminating case: non-uniform data at a border window.
11974    /// A 1x1x2x2 input `[[10, 10], [10, 10]]`, kernel 2x2, padding 1 (so
11975    /// the TOP-LEFT output position's window is `[[pad,pad],[pad,10]]` --
11976    /// only ONE of four taps is real). count_include_pad=true (today's old
11977    /// behavior) divides by the uniform 4: `10/4 = 2.5`. count_include_pad
11978    /// =false (ONNX/PyTorch default) divides by the TRUE valid count, 1:
11979    /// `10/1 = 10.0` -- the actual average of the real values in the
11980    /// window, which is what "average pooling, excluding padding" means.
11981    #[test]
11982    fn avg_pool2d_excludes_padding_from_divisor_discriminating() {
11983        let x = cpu_f32(vec![10.0, 10.0, 10.0, 10.0], &[1, 1, 2, 2]);
11984        let included = x.avg_pool2d((2, 2), (1, 1), (1, 1), true).unwrap();
11985        let excluded = x.avg_pool2d((2, 2), (1, 1), (1, 1), false).unwrap();
11986        let vi = included.realize_f32();
11987        let ve = excluded.realize_f32();
11988        assert!(
11989            (vi[0] - 2.5).abs() < 1e-5,
11990            "count_include_pad=true: top-left = 10/4 = 2.5, got {}",
11991            vi[0]
11992        );
11993        assert!(
11994            (ve[0] - 10.0).abs() < 1e-5,
11995            "count_include_pad=false: top-left = 10/1 (ONE real tap) = 10.0, got {}",
11996            ve[0]
11997        );
11998    }
11999
12000    /// A 1x1 input with padding >= kernel size: EVERY output window is
12001    /// entirely padding, so the count-include-pad=false divisor would be
12002    /// zero everywhere. Must refuse with a descriptive error rather than
12003    /// let `broadcast_div` emit NaN/inf.
12004    #[test]
12005    fn avg_pool2d_rejects_zero_valid_tap_window() {
12006        let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12007        let err = x
12008            .avg_pool2d((1, 1), (1, 1), (2, 2), false)
12009            .expect_err("a window with zero real taps must be rejected, not silently NaN");
12010        let msg = err.to_string();
12011        assert!(
12012            msg.contains("divide by zero") || msg.contains("no valid"),
12013            "error should explain the zero-valid-tap cause, got: {msg}"
12014        );
12015
12016        // Positive control: count_include_pad=true has no notion of "valid
12017        // taps" (it always divides by kh*kw), so the SAME shape must still
12018        // succeed under that mode -- proving the rejection is specific to
12019        // the zero-valid-tap case, not a blanket refusal of this shape.
12020        let ok = x.avg_pool2d((1, 1), (1, 1), (2, 2), true);
12021        assert!(
12022            ok.is_ok(),
12023            "count_include_pad=true must still accept this shape (uniform divisor, never zero)"
12024        );
12025    }
12026
12027    #[test]
12028    fn avg_pool2d_multi_channel() {
12029        // 1×2×2×2: each channel is filled with its index.
12030        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]);
12031        let out = x.avg_pool2d((2, 2), (2, 2), (0, 0), true).unwrap();
12032        assert_eq!(out.shape().dims(), &[1, 2, 1, 1]);
12033        assert_eq!(out.realize_f32(), vec![0.0, 1.0]);
12034    }
12035
12036    #[test]
12037    fn max_pool2d_2x2_stride2() {
12038        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
12039        let x = cpu_f32(data, &[1, 1, 4, 4]);
12040        let out = x.max_pool2d((2, 2), (2, 2), (0, 0)).unwrap();
12041        assert_eq!(out.shape().dims(), &[1, 1, 2, 2]);
12042        // Each 2x2 block max: 5, 7, 13, 15.
12043        assert_eq!(out.realize_f32(), vec![5.0, 7.0, 13.0, 15.0]);
12044    }
12045
12046    #[test]
12047    fn max_pool2d_3x3_stride1_padding1() {
12048        let x = cpu_f32(
12049            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
12050            &[1, 1, 3, 3],
12051        );
12052        let out = x.max_pool2d((3, 3), (1, 1), (1, 1)).unwrap();
12053        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12054        // Center should be the global max 9; corners should be the max of their 2×2 window.
12055        let v = out.realize_f32();
12056        // (1,1) center: max of all 9 = 9
12057        assert!((v[4] - 9.0).abs() < 1e-5);
12058    }
12059
12060    #[test]
12061    fn upsample_nearest2d_2x() {
12062        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12063        let out = x.upsample_nearest2d(2).unwrap();
12064        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12065        // Each cell replicated 2×2: rows are [1,1,2,2; 1,1,2,2; 3,3,4,4; 3,3,4,4].
12066        assert_eq!(
12067            out.realize_f32(),
12068            vec![
12069                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,
12070            ],
12071        );
12072    }
12073
12074    #[test]
12075    fn upsample_nearest2d_3x() {
12076        let x = cpu_f32(vec![5.0], &[1, 1, 1, 1]);
12077        let out = x.upsample_nearest2d(3).unwrap();
12078        assert_eq!(out.shape().dims(), &[1, 1, 3, 3]);
12079        assert_eq!(out.realize_f32(), vec![5.0; 9]);
12080    }
12081
12082    #[test]
12083    fn upsample_nearest2d_identity_scale_one() {
12084        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12085        let out = x.upsample_nearest2d(1).unwrap();
12086        assert_eq!(out.realize_f32(), vec![1.0, 2.0, 3.0, 4.0]);
12087    }
12088
12089    #[test]
12090    fn upsample_nearest1d_2x() {
12091        let x = cpu_f32(vec![1.0, 2.0, 3.0], &[1, 1, 3]);
12092        let out = x.upsample_nearest1d(2).unwrap();
12093        assert_eq!(out.shape().dims(), &[1, 1, 6]);
12094        assert_eq!(out.realize_f32(), vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
12095    }
12096
12097    #[test]
12098    fn interpolate2d_integer_multiple() {
12099        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2]);
12100        let out = x.interpolate2d(4, 4).unwrap();
12101        assert_eq!(out.shape().dims(), &[1, 1, 4, 4]);
12102    }
12103
12104    #[test]
12105    fn interpolate2d_accepts_non_integer_ratio() {
12106        // Lifted from "rejects non-integer ratio" — arbitrary
12107        // ratios are now supported via the index_select composite
12108        // (matching the eager UpsampleNearest2D convention). See
12109        // tests/lazy_interpolate2d_oracle.rs for parity checks.
12110        let x = cpu_f32(vec![1.0; 4], &[1, 1, 2, 2]);
12111        let out = x.interpolate2d(3, 4).unwrap();
12112        assert_eq!(out.shape().dims(), &[1, 1, 3, 4]);
12113    }
12114
12115    #[test]
12116    fn interpolate1d_integer_multiple() {
12117        let x = cpu_f32(vec![1.0, 2.0], &[1, 1, 2]);
12118        let out = x.interpolate1d(6).unwrap();
12119        assert_eq!(out.shape().dims(), &[1, 1, 6]);
12120        assert_eq!(out.realize_f32(), vec![1.0, 1.0, 1.0, 2.0, 2.0, 2.0]);
12121    }
12122
12123    #[test]
12124    fn pool_rejects_bad_rank() {
12125        let x = cpu_f32(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
12126        assert!(x.avg_pool2d((2, 2), (2, 2), (0, 0), true).is_err());
12127        assert!(x.max_pool2d((2, 2), (2, 2), (0, 0)).is_err());
12128    }
12129
12130    #[test]
12131    fn pool_rejects_zero_kernel() {
12132        let x = cpu_f32(vec![1.0; 16], &[1, 1, 4, 4]);
12133        assert!(x.avg_pool2d((0, 2), (1, 1), (0, 0), true).is_err());
12134        assert!(x.max_pool2d((2, 0), (1, 1), (0, 0)).is_err());
12135    }
12136
12137    // ---- Phase A.8 scope-limited harmonization aliases ----
12138
12139    #[test]
12140    fn numel_matches_elem_count() {
12141        let t = cpu_f32(vec![1.0; 12], &[3, 4]);
12142        assert_eq!(t.numel(), t.elem_count());
12143        assert_eq!(t.numel(), 12);
12144    }
12145
12146    #[test]
12147    fn dim_returns_specific_axis_size() {
12148        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12149        assert_eq!(t.dim(0).unwrap(), 2);
12150        assert_eq!(t.dim(1).unwrap(), 3);
12151        assert_eq!(t.dim(2).unwrap(), 4);
12152        assert!(t.dim(3).is_err());
12153    }
12154
12155    #[test]
12156    fn to_dtype_switches_dtype() {
12157        let t = cpu_f32(vec![1.0, 2.0], &[2]);
12158        let b = t.to_dtype(DType::F64).unwrap();
12159        assert_eq!(b.dtype(), DType::F64);
12160        assert_eq!(b.realize_f64(), vec![1.0, 2.0]);
12161    }
12162
12163    #[test]
12164    fn to_dtype_same_dtype_is_noop() {
12165        let t = cpu_f32(vec![1.0_f32], &[1]);
12166        let b = t.to_dtype(DType::F32).unwrap();
12167        assert_eq!(b.dtype(), DType::F32);
12168    }
12169
12170    #[test]
12171    fn detach_is_identity_on_lazy() {
12172        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12173        let d = t.detach();
12174        assert_eq!(d.realize_f32(), t.realize_f32());
12175    }
12176
12177    #[test]
12178    fn track_op_is_true_on_lazy() {
12179        let t = cpu_f32(vec![0.0], &[1]);
12180        assert!(t.track_op());
12181    }
12182
12183    // ---- Phase A.8a Dim/Dims trait port ergonomics tests ----
12184
12185    #[test]
12186    fn try_permute_accepts_tuple_syntax() {
12187        let t = cpu_f32(vec![0.0; 24], &[2, 3, 4]);
12188        // Eager-style tuple permute now works on lazy.
12189        let out = t.permute((2_usize, 0_usize, 1_usize)).unwrap();
12190        assert_eq!(out.shape().dims(), &[4, 2, 3]);
12191    }
12192
12193    #[test]
12194    fn dim_arg_methods_accept_negative_indexing() {
12195        use fuel_ir::D;
12196        let t = cpu_f32(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
12197        // squeeze, sum_dim, mean_dim, etc. all accept D::Minus1 now.
12198        let sum_last = t.shape().dims().to_vec(); // just demonstrate compile
12199        assert_eq!(sum_last, vec![2, 3]);
12200        // sum_dim is still Self-returning (Phase A.8b will flip), so test
12201        // a method that already returns Result + dim arg.
12202        let cumsum_last = t.cumsum(D::Minus1).unwrap();
12203        assert_eq!(cumsum_last.shape().dims(), &[2, 3]);
12204    }
12205
12206    #[test]
12207    fn unsqueeze_accepts_dim_trait() {
12208        use fuel_ir::D;
12209        let t = cpu_f32(vec![1.0, 2.0, 3.0], &[3]);
12210        // Append a new last dim via D::Minus1 (rank-aware negative indexing).
12211        let out = t.unsqueeze(D::Minus1).unwrap();
12212        // The position D::Minus1 in to_index_plus_one is "the very end"
12213        // → output rank 2 with the new dim trailing.
12214        assert_eq!(out.shape().dims().len(), 2);
12215    }
12216}
12217pub struct TokenDataHost {
12218    pub token_ids: fuel_ir::HostBuffer,
12219    pub rope_cos: fuel_ir::HostBuffer,
12220    pub rope_sin: fuel_ir::HostBuffer,
12221    pub mask: fuel_ir::HostBuffer,
12222    pub offset: Option<fuel_ir::HostBuffer>,
12223}
12224
12225/// Same per-token data as [`crate::inference_context::DecodeTokenData`],
12226/// as raw host bytes instead of freshly-uploaded device Arcs — for
12227/// [`fuel_dispatch::pipelined::CapturedDecodeSession::replay_token`]'s
12228/// in-place H2D overwrite of fixed buffers. `LlamaModel`-private.
12229#[cfg(feature = "cuda")]
12230pub struct TokenDataBytes {
12231    pub token_ids: Vec<u8>,
12232    pub rope_cos: Vec<u8>,
12233    pub rope_sin: Vec<u8>,
12234    pub mask: Vec<u8>,
12235    pub offset: Option<Vec<u8>>,
12236}
12237
12238/// D2H a [`fuel_dispatch::pipelined::CapturedDecodeSession::replay_token`]
12239/// result's device-resident output Arc to a host `Vec<f32>`.
12240///
12241/// The capture mechanism deliberately keeps the output device-resident
12242/// INSIDE the capture (a `Copy`/`Move` node is capture-unsafe — see
12243/// `LlamaModel::forward_with_kv_context_captured`'s design note); this
12244/// reads it back OUTSIDE the capture, dispatching on the same
12245/// `BackendStorage` variants every other pipelined D2H site in this
12246/// codebase does (`CudaStorageBytes::to_cpu_bytes` / `CpuStorageBytes::
12247/// bytes`) rather than hand-rolling a new D2H mechanism. Capture is
12248/// f32-only today (project constraint), so the bytes are reinterpreted
12249/// as f32 directly.
12250#[cfg(feature = "cuda")]
12251pub fn captured_output_to_f32(
12252    output: &Arc<std::sync::RwLock<fuel_memory::Storage>>,
12253) -> fuel_ir::error::Result<Vec<f32>> {
12254    use fuel_memory::BackendStorage;
12255    let guard = output.read().map_err(|_| {
12256        fuel_ir::Error::Msg("captured decode output storage lock poisoned".into()).bt()
12257    })?;
12258    let bytes: Vec<u8> = match &guard.inner {
12259        BackendStorage::Cpu(c) => c.bytes().to_vec(),
12260        BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
12261        #[allow(unreachable_patterns)]
12262        other => {
12263            return Err(fuel_ir::Error::Msg(format!(
12264                "captured decode output is BackendStorage::{:?}, expected Cpu or Cuda",
12265                std::mem::discriminant(other),
12266            ))
12267            .bt());
12268        }
12269    };
12270    Ok(bytemuck::cast_slice::<u8, f32>(&bytes).to_vec())
12271}