Skip to main content

fuel_dispatch/
fused.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! FusedOpRegistry — kernel-side payload. Phase 7.6 step 1 (skeleton).
3//!
4//! Architecture v1.0 splits the fused-op registry across two crates:
5//! - graph-side metadata in `fuel-graph::registry` (id, name, family,
6//!   pattern, decompose, backward, shape/dtype rules);
7//! - kernel-side payload here in `fuel-storage::fused` ([`BackendImpl`],
8//!   [`CostEstimate`], [`PrecisionGuarantee`], [`KernelRevisionHash`]).
9//!
10//! The split exists because [`KernelRef`] lives in fuel-storage and
11//! fuel-graph cannot depend on fuel-storage (the dependency arrow goes
12//! the other way). Joining the two halves is by [`fuel_graph::registry::FusedOpId`]
13//! at runtime: the optimizer reads the metadata-side entry to reason
14//! about decomposition and shape, then asks the kernel-side
15//! [`FusedKernelRegistry`] for the per-backend [`BackendImpl`] when it
16//! needs to pre-resolve a `KernelRef`.
17//!
18//! ## Status (step 1)
19//!
20//! Types only. No callers; no behavior change. Subsequent steps:
21//! - Step 3: register the SoftmaxLastDim CPU `BackendImpl` and dispatch
22//!   `Op::Fused(SOFTMAX_LAST_DIM, _)` through it from the executor.
23//! - Step 6-9: extend per-backend coverage, populate `PrecisionGuarantee`
24//!   and `cost`, and migrate the binding-table lookup off the executor's
25//!   hot path.
26
27use crate::kernel::{KernelCaps, KernelRef};
28use fuel_graph::registry::{FusedOpId, FusedOpParams};
29use fuel_ir::{DType, Shape, backend::BackendCapabilities, probe::BackendId};
30use smallvec::SmallVec;
31use std::collections::HashMap;
32
33/// Per-backend kernel implementation for one fused op. The optimizer
34/// reads this to (1) pre-resolve [`KernelRef`] for nodes it places on
35/// this backend, (2) score routes against [`CostEstimate`], and
36/// (3) admit candidates against the per-route tolerance budget via
37/// [`PrecisionGuarantee`].
38///
39/// Function-pointer composition (no trait-object indirection) — the
40/// registry stores [`BackendImpl`] values inline, the executor calls
41/// the function pointer directly.
42///
43/// A single `(FusedOpId, BackendId)` decision point may have multiple
44/// registered `BackendImpl`s — one per dtype tuple, and potentially
45/// multiple alternatives at the same dtype (e.g. cuBLAS bias-epilogue
46/// vs CUTLASS bias-epilogue for `(FUSED_LINEAR, [BF16,BF16,BF16,BF16],
47/// Cuda)`). The route picker filters by [`Self::dtypes`] and ranks the
48/// remaining alternatives by cost + precision.
49#[derive(Copy, Clone)]
50pub struct BackendImpl {
51    /// Dispatch wrapper for this backend's kernel for this fused op.
52    /// Same `KernelRef` signature as primitive-op kernels.
53    pub kernel: KernelRef,
54    /// Dtype tuple this kernel is registered for. Convention mirrors
55    /// the binding-table key shape: typically `[input1, input2, ...,
56    /// output]` per the existing `register(table, op, &[dtype; N],
57    /// backend, kernel)` call sites. Using `&'static [DType]` keeps
58    /// `BackendImpl` `Copy` and lets registrations declare dtypes
59    /// inline as `&[F32, F32, F32, F32]` literals.
60    pub dtypes: &'static [DType],
61    /// Cost-estimate function. Given the input shapes, the
62    /// per-instance fused-op params, and the backend's capabilities,
63    /// returns a [`CostEstimate`] used for placement and route ranking.
64    pub cost: fn(&[Shape], &FusedOpParams, &BackendCapabilities) -> CostEstimate,
65    /// Numerical precision properties of this kernel.
66    pub precision: PrecisionGuarantee,
67    /// Layout / capability flags (e.g. strided_input).
68    pub caps: KernelCaps,
69    /// Revision hash — opaque identifier for the source-version of this
70    /// kernel. Persisted optimization caches use this to detect kernel
71    /// drift and invalidate stale cache entries (see
72    /// `docs/architecture/11-persistence.md`).
73    pub revision: KernelRevisionHash,
74    /// Declared cost AST compiled from the contract's `cost:` field
75    /// (FKC gap-closure §2.3, Task 2.4). `None` when the contract
76    /// declared no cost expression, or for hand-written (non-FKC)
77    /// registrations. When present, [`crate::fused_cost::fused_layer1_cost`]
78    /// prefers it over the [`is_fused_cost_sentinel`](crate::fused_cost::is_fused_cost_sentinel)
79    /// decompose-derived fallback.
80    pub cost_expr: Option<&'static crate::fkc::CompiledCostExpr>,
81}
82
83/// Coarse cost model for one kernel invocation. Layer-1 of the
84/// architecture's cost-model tower (FLOP counts + bandwidth + launch
85/// overhead). Layer-2 — empirical refinement from per-deployment
86/// telemetry — composes on top of these without changing this shape.
87#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
88pub struct CostEstimate {
89    /// Compute pressure — number of floating-point operations.
90    pub flops: u64,
91    /// Bandwidth pressure — bytes moved through device memory hierarchy
92    /// for this kernel's inputs + outputs (excluding cache hits).
93    pub bytes_moved: u64,
94    /// Fixed launch overhead. CPU kernels measure this in tens of ns;
95    /// GPU launches in low microseconds.
96    pub kernel_overhead_ns: u32,
97}
98
99/// What this kernel guarantees about its numerical behavior.
100///
101/// Replaces the binary-flag OracleGrade concept that pre-architecture
102/// drafts used; per architecture v1.0 every kernel registration carries
103/// a structured precision statement so the optimizer can reason about
104/// tolerance budgets and pick comparators for calibration.
105///
106/// `bit_stable_on_same_hardware` is the strongest property. The
107/// always-built backend (fuel-cpu-backend by convention) commits to
108/// providing at least one `bit_stable_on_same_hardware: true` kernel
109/// per primitive op as the architecture v1.0 coverage commitment;
110/// step 7 enforces this via a CI lint.
111///
112/// The Optional fields encode the bound's flavor (ULP / relative /
113/// absolute). Multiple may be present; the optimizer takes the
114/// intersection (a budget is admissible only if every populated bound
115/// satisfies it). Absent bounds mean "this kernel makes no claim
116/// about that flavor."
117#[derive(Copy, Clone, Debug)]
118pub struct PrecisionGuarantee {
119    /// True iff this kernel produces bit-identical output for
120    /// bit-identical inputs on the same hardware (no nondeterminism
121    /// from kernel scheduling, atomic ordering, etc.).
122    ///
123    /// **This is NOT the KISS-Ops "bit-stable" value (KISS-OPS-6.17-0001 and KISS-OPS-6.17-0002).** KISS bit-stable means every atom rounds
124    /// independently at the storage dtype's full IEEE 754-2019 precision, SUBNORMALS PRESERVED; a kernel that flushes
125    /// subnormals (FTZ/DAZ) is non-conformant under it and must decline `Exact`. A flush is DETERMINISTIC, so a
126    /// flushing kernel can still be `bit_stable_on_same_hardware: true` here (Metal f32/bf16: FTZ measured, hosted
127    /// macOS run 45748920513). This field claims same-hardware repeatability only, never exactness.
128    pub bit_stable_on_same_hardware: bool,
129    /// Maximum unit-in-last-place error vs the IEEE-754 correctly-
130    /// rounded result. Tighter than max_relative for low-magnitude
131    /// values; many vendor math libraries quote ULPs.
132    pub max_ulp: Option<u32>,
133    /// Maximum relative error: `|out - ref| / max(|ref|, eps)`.
134    pub max_relative: Option<f64>,
135    /// Maximum absolute error: `|out - ref|`.
136    pub max_absolute: Option<f64>,
137    /// Free-text qualifier — for audited claims, this carries the
138    /// audit reason (vendor citation, scheduler-dependence note,
139    /// implementation hint). For the [`UNAUDITED`] sentinel, this
140    /// is a fixed placeholder string the coverage lint matches
141    /// against to distinguish unaudited placeholders from audited
142    /// claims that happen to have no static bound. **If you change
143    /// `UNAUDITED.notes`, the lint's detector picks up the new value
144    /// automatically — it reads `PrecisionGuarantee::UNAUDITED.notes`
145    /// at test time, not a hardcoded string.**
146    ///
147    /// [`UNAUDITED`]: PrecisionGuarantee::UNAUDITED
148    pub notes: &'static str,
149}
150
151impl PrecisionGuarantee {
152    /// "Reference" guarantee: bit-stable on same hardware, no error
153    /// claim above that. Used by reference-grade CPU kernels that
154    /// commit to deterministic IEEE-754 evaluation.
155    pub const REFERENCE: PrecisionGuarantee = PrecisionGuarantee {
156        bit_stable_on_same_hardware: true,
157        max_ulp: Some(0),
158        max_relative: Some(0.0),
159        max_absolute: Some(0.0),
160        notes: "Reference IEEE-754 evaluation; bit-identical re-run.",
161    };
162
163    /// Phase 7.6 step 7b: shared precision guarantee for the
164    /// always-built CPU backend's **primitive** kernels — elementwise
165    /// unary/binary, reductions, matmul, casts, comparisons, indexing,
166    /// scalar ops, transcendentals (Exp/Log/Sin/Cos/Tanh/Sigmoid/
167    /// Gelu/Silu), etc. All claim:
168    ///
169    /// - `bit_stable_on_same_hardware: true` (deterministic iteration
170    ///   order; no atomic FP adds; sequential nested loops)
171    /// - F32 accumulator for BF16/F16 inputs, native F32 / F64 / U32
172    ///   for matching dtypes
173    /// - No specific ULP / relative / absolute bound claimed at this
174    ///   layer — the empirical calibration framework in step 8
175    ///   populates per-op-per-shape bounds via reference comparisons
176    ///
177    /// This is the default value bulk-applied by
178    /// [`crate::kernel::KernelBindingTable::fill_unset_cpu_precision`]
179    /// at the end of `register_cpu_kernels`. Sites that need a
180    /// different claim must call
181    /// [`crate::kernel::KernelBindingTable::register_with_precision`]
182    /// explicitly with the weaker guarantee — those don't get
183    /// bulk-overwritten because the fill only touches UNAUDITED
184    /// entries.
185    pub const PRIMITIVE_DETERMINISTIC_CPU: PrecisionGuarantee = PrecisionGuarantee {
186        bit_stable_on_same_hardware: true,
187        max_ulp: None,
188        max_relative: None,
189        max_absolute: None,
190        notes: "fuel-cpu-backend primitive kernel family: deterministic \
191                nested-loop iteration order; F32 accumulator for \
192                half-precision inputs; bit-identical same-hardware \
193                re-run. Per-op-per-shape ULP / relative bounds land \
194                with the step-8 empirical calibration framework.",
195    };
196
197    /// Default placeholder for kernels whose precision hasn't been
198    /// audited yet. Identified by the coverage lint via notes-
199    /// equality against `PrecisionGuarantee::UNAUDITED.notes` —
200    /// the only way a registration ends up with this specific
201    /// notes string is by using the literal `UNAUDITED` const
202    /// (the default in unannotated `register(...)` / `register_with_caps(...)`
203    /// calls).
204    ///
205    /// **For kernels audited and concluded "no static bound
206    /// applies"** (e.g. Vulkan subgroup reductions where FADD
207    /// order is scheduler-determined per dispatch), use
208    /// [`none`] instead. It returns a structurally-similar
209    /// PrecisionGuarantee but with the audit reason in `notes`,
210    /// captured at the registration site. The lint accepts any
211    /// notes value other than UNAUDITED's specific text.
212    ///
213    /// [`none`]: PrecisionGuarantee::none
214    pub const UNAUDITED: PrecisionGuarantee = PrecisionGuarantee {
215        bit_stable_on_same_hardware: false,
216        max_ulp: None,
217        max_relative: None,
218        max_absolute: None,
219        notes: "PrecisionGuarantee::UNAUDITED — default placeholder for \
220                kernels whose precision hasn't been audited yet. Coverage \
221                lints flag these. Sites must either annotate via \
222                `register_with_precision` with a real claim or use \
223                `PrecisionGuarantee::none(reason)` if the audit \
224                concluded no static bound applies.",
225    };
226
227    /// Constructor for the "audited, no static guarantee could be
228    /// established" conclusion. Used by Vulkan subgroup reductions
229    /// (where FADD order is scheduler-determined per dispatch) and
230    /// similar kernels whose numerical character can't be
231    /// summarized by static ULP / relative / absolute bounds.
232    ///
233    /// The `reason` is captured in `notes`, so the audit reasoning
234    /// lives at the registration site — visible in code review,
235    /// not buried in a separate lint allowlist file. Any `reason`
236    /// other than `UNAUDITED.notes` makes the resulting value pass
237    /// the coverage lint.
238    ///
239    /// Distinguished from [`UNAUDITED`] by `notes` content alone
240    /// (the value-field shape is identical). The lint uses
241    /// `precision.notes == PrecisionGuarantee::UNAUDITED.notes` as
242    /// the unaudited detector — robust to UNAUDITED's notes text
243    /// drifting because it reads from the const itself.
244    ///
245    /// [`UNAUDITED`]: PrecisionGuarantee::UNAUDITED
246    pub const fn none(reason: &'static str) -> PrecisionGuarantee {
247        PrecisionGuarantee {
248            bit_stable_on_same_hardware: false,
249            max_ulp: None,
250            max_relative: None,
251            max_absolute: None,
252            notes: reason,
253        }
254    }
255
256    /// Does this guarantee assert nothing machine-checkable — no
257    /// bit-stability, no ULP / relative / absolute bound?
258    ///
259    /// True for BOTH [`UNAUDITED`] and [`none`]: they are field-identical,
260    /// because they make the same (empty) set of claims. What separates them
261    /// is *provenance*, not claim content — see [`Self::is_audited_no_bound`].
262    ///
263    /// [`UNAUDITED`]: PrecisionGuarantee::UNAUDITED
264    /// [`none`]: PrecisionGuarantee::none
265    pub fn makes_no_static_claim(&self) -> bool {
266        !self.bit_stable_on_same_hardware
267            && self.max_ulp.is_none()
268            && self.max_relative.is_none()
269            && self.max_absolute.is_none()
270    }
271
272    /// Is this an **audited conclusion that no static bound applies**
273    /// ([`none(reason)`]) rather than the never-audited placeholder
274    /// ([`UNAUDITED`])?
275    ///
276    /// # Why this is a method and not an open-coded check (GAP-095)
277    ///
278    /// These two states are **field-identical apart from `notes`**, so any
279    /// consumer that must tell them apart is forced to key on a string. Two
280    /// consumers previously invented their own predicate and *disagreed*: the
281    /// bit-stable coverage lint compared `notes` against `UNAUDITED.notes`,
282    /// while [`KernelBindingTable::fill_unset_cpu_precision`] looked only at
283    /// the four value fields — and therefore silently rewrote an audited
284    /// "no static bound applies" conclusion into a
285    /// `bit_stable_on_same_hardware: true` claim the audit had declined to
286    /// make.
287    ///
288    /// One definition, so the next consumer inherits the distinction instead
289    /// of re-deriving it. **This is a seam, not a cure:** a `&'static str`
290    /// remains the load-bearing discriminator, and only making the two states
291    /// structurally distinct would make conflation *unrepresentable*. That
292    /// change is priced at ~64 `PrecisionGuarantee` literals across three
293    /// crates and is tracked separately; when it lands, this method's body
294    /// changes and its callers do not.
295    ///
296    /// [`none(reason)`]: PrecisionGuarantee::none
297    /// [`UNAUDITED`]: PrecisionGuarantee::UNAUDITED
298    /// [`KernelBindingTable::fill_unset_cpu_precision`]: crate::kernel::KernelBindingTable::fill_unset_cpu_precision
299    pub fn is_audited_no_bound(&self) -> bool {
300        self.makes_no_static_claim()
301            && !self.notes.is_empty()
302            && self.notes != Self::UNAUDITED.notes
303    }
304}
305
306/// Opaque revision hash of a registered kernel. Persisted optimization
307/// caches read this to detect kernel drift between cache build and
308/// cache load (see `docs/architecture/11-persistence.md`). Computed
309/// from kernel source + version metadata at registration time; step 9
310/// fills in the actual hashing function alongside the binding-table
311/// planning-time refactor.
312#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
313pub struct KernelRevisionHash(pub u64);
314
315impl KernelRevisionHash {
316    /// Sentinel meaning "no revision tracked yet." Used by step-1-shipped
317    /// `BackendImpl` registrations until step 9 wires real hashing.
318    pub const UNTRACKED: KernelRevisionHash = KernelRevisionHash(0);
319}
320
321/// Inline capacity for per-fused-op backend lists. SmallVec at 4 fits
322/// CPU + CUDA + Vulkan + Metal without spilling to heap; the typical
323/// fused op has 1-3 backends with kernels.
324type BackendImplList = SmallVec<[(BackendId, BackendImpl); 4]>;
325
326/// Kernel-side registry: `FusedOpId` → list of per-backend
327/// [`BackendImpl`]s. Joined to `fuel-graph`'s metadata-side
328/// [`fuel_graph::registry::FusedOpRegistry`] by id at runtime.
329///
330/// Built at process startup, frozen thereafter (architecture v1.0:
331/// no runtime extensibility).
332#[derive(Default)]
333pub struct FusedKernelRegistry {
334    by_id: HashMap<FusedOpId, BackendImplList>,
335    /// Finding 5.4 (FKC side, Task 3.6) side-table: preserves a fused
336    /// contract's `return.bundle` per-slot NAMES, keyed by the same
337    /// `(FusedOpId, BackendId, dtypes)` tuple the kernel itself was
338    /// registered under. Before this table existed the names were parsed
339    /// (`return_check::bundle_slot_names`) then discarded — a later
340    /// consumer (e.g. FDX output-view labeling) had no artifact to read
341    /// them from. `Vec<DType>` (not `&'static [DType]`) because the key is
342    /// built from a caller-owned slice at lookup time.
343    bundle_slot_names: HashMap<(FusedOpId, BackendId, Vec<DType>), Vec<String>>,
344}
345
346impl FusedKernelRegistry {
347    pub fn new() -> Self {
348        Self::default()
349    }
350
351    /// Register a [`BackendImpl`] for this `(id, backend)` pair. Always
352    /// appends — multiple impls per `(id, backend)` are allowed (per-
353    /// dtype registrations, alternative algorithms at the same dtype,
354    /// etc.). The route picker filters by [`BackendImpl::dtypes`] and
355    /// ranks remaining alternatives at lookup time.
356    pub fn register(&mut self, id: FusedOpId, backend: BackendId, impl_: BackendImpl) {
357        self.by_id.entry(id).or_default().push((backend, impl_));
358    }
359
360    /// Look up the first [`BackendImpl`] registered for `(id, backend)`
361    /// regardless of dtypes. Convenience for callers that already know
362    /// a single impl exists for the pair. Prefer
363    /// [`Self::lookup_by_dtypes`] when multiple per-dtype impls may
364    /// share a backend.
365    pub fn lookup(&self, id: FusedOpId, backend: BackendId) -> Option<BackendImpl> {
366        self.by_id
367            .get(&id)
368            .and_then(|impls| impls.iter().find(|(b, _)| *b == backend))
369            .map(|(_, impl_)| *impl_)
370    }
371
372    /// Look up the [`BackendImpl`] registered for `(id, backend,
373    /// dtypes)`. Returns `None` when no kernel matches all three; the
374    /// optimizer's fallback in that case is to lower the fused op via
375    /// the metadata-side `decompose` and run it as primitives on the
376    /// backend.
377    ///
378    /// When multiple impls match (alternatives at the same decision
379    /// point — e.g. cuBLAS vs CUTLASS bf16 matmul), the first
380    /// registration wins. Step 9's route picker replaces this with a
381    /// cost-aware selector.
382    pub fn lookup_by_dtypes(
383        &self,
384        id: FusedOpId,
385        backend: BackendId,
386        dtypes: &[DType],
387    ) -> Option<BackendImpl> {
388        self.by_id
389            .get(&id)
390            .and_then(|impls| {
391                impls
392                    .iter()
393                    .find(|(b, i)| *b == backend && i.dtypes == dtypes)
394            })
395            .map(|(_, impl_)| *impl_)
396    }
397
398    /// All `(BackendId, BackendImpl)` pairs registered for this id.
399    /// The optimizer reads this when deciding placement: a fused op
400    /// with a CUDA-only kernel limits its placement candidates.
401    pub fn impls_for(&self, id: FusedOpId) -> &[(BackendId, BackendImpl)] {
402        self.by_id.get(&id).map(|v| v.as_slice()).unwrap_or(&[])
403    }
404
405    /// Number of distinct `FusedOpId`s with at least one registered
406    /// backend impl.
407    pub fn len(&self) -> usize {
408        self.by_id.len()
409    }
410
411    /// Whether the registry has any registered impls.
412    pub fn is_empty(&self) -> bool {
413        self.by_id.is_empty()
414    }
415
416    /// Finding 5.4 (FKC side, Task 3.6): record a fused contract's
417    /// `return.bundle` per-slot names against the `(id, backend, dtypes)`
418    /// key it was registered under. Overwrites any prior entry at the same
419    /// key (re-import is idempotent, mirroring `register`'s append
420    /// semantics at the registration level — the side-table itself has no
421    /// duplicate-detection gate).
422    pub fn record_bundle_slot_names(
423        &mut self,
424        id: FusedOpId,
425        backend: BackendId,
426        dtypes: &[DType],
427        names: &[String],
428    ) {
429        self.bundle_slot_names
430            .insert((id, backend, dtypes.to_vec()), names.to_vec());
431    }
432
433    /// Look up the per-slot names recorded by [`Self::record_bundle_slot_names`]
434    /// for `(id, backend, dtypes)`. `None` when no bundle names were ever
435    /// recorded for that exact key (including a single-output section,
436    /// which never calls `record_bundle_slot_names` in the first place).
437    pub fn bundle_slot_names(
438        &self,
439        id: FusedOpId,
440        backend: BackendId,
441        dtypes: &[DType],
442    ) -> Option<&[String]> {
443        self.bundle_slot_names
444            .get(&(id, backend, dtypes.to_vec()))
445            .map(|v| v.as_slice())
446    }
447}
448
449/// Register a [`BackendImpl`] into a [`FusedKernelRegistry`] via the
450/// step-6 macro shape. Hides the boilerplate of constructing the
451/// `BackendImpl` struct so registration sites read as a flat list of
452/// `(id, backend, dtypes, kernel, cost, precision)` tuples.
453///
454/// Caps default to [`KernelCaps::empty()`] and revision to
455/// [`KernelRevisionHash::UNTRACKED`]; pass `caps = ...` and
456/// `revision = ...` to override.
457///
458/// # Examples
459///
460/// ```ignore
461/// register_fused!(
462///     registry,
463///     FusedOps::FUSED_LINEAR,
464///     BackendId::Cpu,
465///     &[F32, F32, F32, F32],
466///     fused_linear_f32_cpu_wrapper,
467///     cost = cost_fused_linear_cpu,
468///     precision = PrecisionGuarantee::REFERENCE,
469/// );
470/// ```
471#[macro_export]
472macro_rules! register_fused {
473    (
474        $registry:expr,
475        $id:expr,
476        $backend:expr,
477        $dtypes:expr,
478        $kernel:expr,
479        cost = $cost:expr,
480        precision = $precision:expr
481        $(, caps = $caps:expr)?
482        $(, revision = $revision:expr)?
483        $(,)?
484    ) => {{
485        #[allow(unused_mut, unused_assignments)]
486        let mut caps = $crate::kernel::KernelCaps::empty();
487        $( caps = $caps; )?
488        #[allow(unused_mut, unused_assignments)]
489        let mut revision = $crate::fused::KernelRevisionHash::UNTRACKED;
490        $( revision = $revision; )?
491        $registry.register(
492            $id,
493            $backend,
494            $crate::fused::BackendImpl {
495                kernel: $kernel,
496                dtypes: $dtypes,
497                cost: $cost,
498                precision: $precision,
499                caps,
500                revision,
501                cost_expr: None,
502            },
503        );
504    }};
505}
506
507/// Process-wide default kernel registry: every backend's fused-op
508/// `BackendImpl`s registered at startup. Built once on first access
509/// via [`std::sync::OnceLock`]; immutable thereafter (architecture
510/// v1.0: no runtime extensibility).
511///
512/// Today's coverage:
513/// - `FUSED_LINEAR` × `Cpu` × `{F32, F64, BF16, F16}` — four
514///   bit-stable per-dtype impls registered via [`register_default_kernels`].
515///
516/// Backend-side crates (fuel-cuda-backend, fuel-vulkan-backend) extend
517/// this set by either (a) registering during their own startup, or
518/// (b) the step-9 binding-table refactor where the route picker pulls
519/// from this registry. Today's executors continue to lookup via the
520/// per-dtype [`KernelBindingTable`](crate::kernel::KernelBindingTable); this
521/// registry is
522/// the architecture-target shape for CUTLASS / cuBLAS alternative
523/// registrations and step-9's pre-resolved `KernelRef` pipeline.
524pub fn default_kernel_registry() -> &'static FusedKernelRegistry {
525    use std::sync::OnceLock;
526    static REGISTRY: OnceLock<FusedKernelRegistry> = OnceLock::new();
527    REGISTRY.get_or_init(|| {
528        let mut r = FusedKernelRegistry::new();
529        register_default_kernels(&mut r);
530        r
531    })
532}
533
534/// Populate a [`FusedKernelRegistry`] with the always-built kernels
535/// (today: `fuel-cpu-backend` FusedLinear F32/F64/BF16/F16). Called
536/// from [`default_kernel_registry`]'s OnceLock initializer; exposed as
537/// a free function so backend crates can compose against a custom
538/// registry in tests.
539pub fn register_default_kernels(r: &mut FusedKernelRegistry) {
540    crate::dispatch::register_default_fused_kernels(r);
541}
542
543/// Static cost model for `(FUSED_LINEAR, Cpu)` kernels — the conservative
544/// FLOP + bandwidth model per architecture v1.0 §"Layer-1 cost model."
545/// Identical for F32/F64/BF16/F16 (the kernels accumulate in F32
546/// regardless of input dtype); the empirical Layer-2 refinement
547/// framework will tighten per-dtype later.
548///
549/// Shapes: `[a, b, bias]` where `a = [..., M, K]`, `b = [..., K, N]`,
550/// `bias = [N]`.
551pub fn cost_fused_linear_cpu(
552    shapes: &[Shape],
553    _params: &FusedOpParams,
554    _caps: &BackendCapabilities,
555) -> CostEstimate {
556    debug_assert_eq!(shapes.len(), 3, "FusedLinear cost: expected 3 input shapes");
557    let a_dims = shapes[0].dims();
558    let b_dims = shapes[1].dims();
559    let rank = a_dims.len();
560    if rank < 2 || b_dims.len() < 2 {
561        return CostEstimate::default();
562    }
563    let m = a_dims[rank - 2] as u64;
564    let k = a_dims[rank - 1] as u64;
565    let n = b_dims[b_dims.len() - 1] as u64;
566    let batch: u64 = a_dims[..rank - 2]
567        .iter()
568        .map(|d| *d as u64)
569        .product::<u64>()
570        .max(1);
571    // FMA counts as 2 FLOPs. Matmul: 2·M·N·K per batch. Bias-add: M·N per batch.
572    let mm_flops = 2u64 * m * n * k * batch;
573    let bias_flops = m * n * batch;
574    // Conservative bandwidth: assume 4 B/elem (F32-equivalent). Empirical
575    // refinement adjusts per-dtype; the static layer is intentionally coarse.
576    let elems = batch * (m * k + k * n + m * n) + n;
577    let bytes_moved = elems * 4;
578    CostEstimate {
579        flops: mm_flops + bias_flops,
580        bytes_moved,
581        kernel_overhead_ns: 50, // CPU launch overhead, ballpark
582    }
583}
584
585/// Precision guarantee shared by every `(FUSED_LINEAR, Cpu, *)` impl
586/// in fuel-cpu-backend: deterministic per-element accumulation in F32
587/// (BF16/F16 inputs upcast and narrow at the end), bit-identical on
588/// same hardware. Bounded error claims (max_ulp / max_relative) depend
589/// on the contracting dim K and so stay `None` at this layer — the
590/// empirical calibration framework derives them per-shape.
591pub const FUSED_LINEAR_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
592    bit_stable_on_same_hardware: true,
593    max_ulp: None,
594    max_relative: None,
595    max_absolute: None,
596    notes: "fuel-cpu-backend FusedLinear: deterministic matmul + bias-add; \
597            BF16/F16 accumulate in F32 and narrow at end; same-hardware re-run \
598            bit-identical.",
599};
600
601/// Static cost model for `(FUSED_SOFTMAX_CROSS_ENTROPY, Cpu)` — row-by-row
602/// stable log-softmax + gather. FLOPs scale with `n_rows × vocab`
603/// (two passes per row: one for max+sum_exp, one for the loss
604/// accumulator); memory is `n_rows × vocab` reads plus the targets and
605/// the scalar/vector output.
606///
607/// Shapes: `[logits, targets]` where `logits = [..., V]` (F32) and
608/// `targets = [...]` (I64); the per-row reduction count comes from
609/// the logits shape's leading dims.
610pub fn cost_fused_softmax_cross_entropy_cpu(
611    shapes: &[Shape],
612    _params: &FusedOpParams,
613    _caps: &BackendCapabilities,
614) -> CostEstimate {
615    debug_assert_eq!(
616        shapes.len(),
617        2,
618        "FusedSoftmaxCrossEntropy cost: expected 2 input shapes (logits, targets)",
619    );
620    let logits_dims = shapes[0].dims();
621    if logits_dims.is_empty() {
622        return CostEstimate::default();
623    }
624    let vocab = *logits_dims.last().unwrap() as u64;
625    let n_rows: u64 = logits_dims[..logits_dims.len() - 1]
626        .iter()
627        .map(|d| *d as u64)
628        .product::<u64>()
629        .max(1);
630    // Two passes over vocab per row: pass 1 finds max (V compares),
631    // pass 2 sums exp(x - max) (V FMAs ≈ 2V FLOPs). Plus one log
632    // call. The transcendental `exp` counts as ~10 FLOPs by convention.
633    let per_row_flops = vocab + 2 * vocab + 10 * vocab + 10;
634    let total_flops = n_rows * per_row_flops;
635    // Bandwidth: logits (n_rows × vocab × 4) + targets (n_rows × 8) +
636    // output (4 bytes for Mean/Sum, ~n_rows × 4 for None — average to
637    // the worst case here for the conservative layer-1 estimate).
638    let bytes_moved = n_rows * vocab * 4 + n_rows * 8 + n_rows * 4;
639    CostEstimate {
640        flops: total_flops,
641        bytes_moved,
642        kernel_overhead_ns: 50,
643    }
644}
645
646/// Precision guarantee for `(FUSED_SOFTMAX_CROSS_ENTROPY, Cpu, *)` —
647/// stable log-sum-exp accumulated in F64, gather + NLL in F64,
648/// narrow to F32 at end. Bit-identical re-run on same hardware. The
649/// kernel's iteration order is fixed, so the only sources of
650/// non-determinism (reduction-order changes, denormal flushing) are
651/// excluded by construction.
652pub const FUSED_SOFTMAX_CROSS_ENTROPY_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
653    bit_stable_on_same_hardware: true,
654    max_ulp: None,
655    max_relative: None,
656    max_absolute: None,
657    notes: "fuel-cpu-backend FusedSoftmaxCrossEntropy: stable log-sum-exp \
658            in F64 accumulator; gather + NLL in F64; narrow to F32 at end; \
659            same-hardware re-run bit-identical.",
660};
661
662/// Static cost model for `(CAUSAL_CONV1D, Cpu)` — depthwise 1-D conv.
663/// FLOPs scale with `batch × channels × seq_out × kernel`; bandwidth
664/// is `batch × channels × seq_in` (x reads) + `channels × kernel`
665/// (weight reads) + `channels` (bias) + `batch × channels × seq_out`
666/// (output writes). SiLU adds one transcendental per output element.
667///
668/// Shapes: `[x, weight, bias]` where `x = [batch, channels, seq_in]`,
669/// `weight = [channels, 1, kernel]`, `bias = [channels]`.
670pub fn cost_causal_conv1d_cpu(
671    shapes: &[Shape],
672    params: &FusedOpParams,
673    _caps: &BackendCapabilities,
674) -> CostEstimate {
675    debug_assert_eq!(
676        shapes.len(),
677        3,
678        "CausalConv1d cost: expected 3 input shapes (x, weight, bias)",
679    );
680    let use_silu = match params {
681        FusedOpParams::CausalConv1d { use_silu } => *use_silu,
682        _ => return CostEstimate::default(),
683    };
684    let x_dims = shapes[0].dims();
685    let w_dims = shapes[1].dims();
686    if x_dims.len() != 3 || w_dims.len() != 3 {
687        return CostEstimate::default();
688    }
689    let batch = x_dims[0] as u64;
690    let channels = x_dims[1] as u64;
691    let seq_in = x_dims[2] as u64;
692    let kernel = w_dims[2] as u64;
693    if seq_in < kernel - 1 {
694        return CostEstimate::default();
695    }
696    let seq_out = seq_in - (kernel - 1);
697    // 2·kernel FLOPs per output element (FMA = 2). SiLU adds ~10
698    // FLOPs per element (transcendental convention).
699    let per_out_flops = 2 * kernel + if use_silu { 10 } else { 0 };
700    let flops = batch * channels * seq_out * per_out_flops;
701    let bytes_moved = batch * channels * seq_in * 4
702        + channels * kernel * 4
703        + channels * 4
704        + batch * channels * seq_out * 4;
705    CostEstimate {
706        flops,
707        bytes_moved,
708        kernel_overhead_ns: 50,
709    }
710}
711
712/// Precision guarantee for `(CAUSAL_CONV1D, Cpu, *)` — textbook
713/// nested-loop depthwise conv with F32 accumulator; SiLU computed
714/// element-wise via `x / (1 + exp(-x))`. Iteration order fixed;
715/// bit-identical re-run on same hardware.
716pub const CAUSAL_CONV1D_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
717    bit_stable_on_same_hardware: true,
718    max_ulp: None,
719    max_relative: None,
720    max_absolute: None,
721    notes: "fuel-cpu-backend CausalConv1d: textbook depthwise nested-loop \
722            with F32 accumulator; optional SiLU via x/(1+exp(-x)); \
723            same-hardware re-run bit-identical.",
724};
725
726/// Static cost model for `(SELECTIVE_SCAN, Cpu)` — Mamba's selective
727/// state-space scan. FLOPs scale with `batch · seqlen · dim · dstate`
728/// (the inner triple-nested loop). Bandwidth is dominated by reading
729/// u/delta/b/c per timestep + writing y.
730///
731/// Shapes: `[u, delta, a, b, c]`. Per-step cost: ~4·dstate FMAs (exp +
732/// mul + add for h update; mul + accumulate for y).
733pub fn cost_selective_scan_cpu(
734    shapes: &[Shape],
735    _params: &FusedOpParams,
736    _caps: &BackendCapabilities,
737) -> CostEstimate {
738    debug_assert_eq!(
739        shapes.len(),
740        5,
741        "SelectiveScan cost: expected 5 input shapes (u, delta, a, b, c)",
742    );
743    let u_dims = shapes[0].dims();
744    let a_dims = shapes[2].dims();
745    if u_dims.len() != 3 || a_dims.len() != 2 {
746        return CostEstimate::default();
747    }
748    let batch = u_dims[0] as u64;
749    let seqlen = u_dims[1] as u64;
750    let dim = u_dims[2] as u64;
751    let dstate = a_dims[1] as u64;
752    // ~8 FLOPs per (b, t, i, j) iteration: exp (10), mul (1), mul (1),
753    // add (1), mul (1), add (1). Conservative average ~16/iter once
754    // exp is amortized.
755    let per_iter_flops = 16;
756    let flops = batch * seqlen * dim * dstate * per_iter_flops;
757    // u + delta + b + c (read per step) + a (read once) + out (written once).
758    let bytes_moved = 2 * batch * seqlen * dim * 4
759        + 2 * batch * seqlen * dstate * 4
760        + dim * dstate * 4
761        + batch * seqlen * dim * 4;
762    CostEstimate {
763        flops,
764        bytes_moved,
765        kernel_overhead_ns: 50,
766    }
767}
768
769/// Precision guarantee for `(SELECTIVE_SCAN, Cpu, *)` — recurrence
770/// accumulated in F64 (h is `Vec<f64>` internally), final y narrowed
771/// to F32. Iteration order fixed; bit-identical re-run on same
772/// hardware. The F64 accumulator buys ~7 extra decimal digits of
773/// headroom vs naive F32 over the per-step state update.
774pub const SELECTIVE_SCAN_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
775    bit_stable_on_same_hardware: true,
776    max_ulp: None,
777    max_relative: None,
778    max_absolute: None,
779    notes: "fuel-cpu-backend SelectiveScan: state recurrence in F64 \
780            accumulator; narrow to F32 on y store; deterministic \
781            iteration order; same-hardware re-run bit-identical.",
782};
783
784/// Static cost model for `(SSD_CHUNK_SCAN, Cpu)` — Mamba-2's chunked
785/// SSD scan. FLOPs scale with
786/// `batch · seqlen · heads · head_dim · state_dim` (the inner
787/// quadruple-nested loop). Bandwidth reads x/dt/b/c per timestep +
788/// a once + writes y.
789///
790/// Shapes: `[x, dt, a, b, c]`. v1 single-chunk only.
791pub fn cost_ssd_chunk_scan_cpu(
792    shapes: &[Shape],
793    _params: &FusedOpParams,
794    _caps: &BackendCapabilities,
795) -> CostEstimate {
796    debug_assert_eq!(
797        shapes.len(),
798        5,
799        "SsdChunkScan cost: expected 5 input shapes (x, dt, a, b, c)",
800    );
801    let x_dims = shapes[0].dims();
802    let b_dims = shapes[3].dims();
803    if x_dims.len() != 4 || b_dims.len() != 4 {
804        return CostEstimate::default();
805    }
806    let batch = x_dims[0] as u64;
807    let seqlen = x_dims[1] as u64;
808    let heads = x_dims[2] as u64;
809    let head_dim = x_dims[3] as u64;
810    let state_dim = b_dims[3] as u64;
811    // ~8 FLOPs per (b, t, h, i, j) inner iteration: mul-mul-add for
812    // h-update + mul-add for y-accumulate, plus exp amortized per
813    // outer (b, t, h).
814    let per_iter_flops = 8;
815    let flops = batch * seqlen * heads * head_dim * state_dim * per_iter_flops;
816    let bytes_moved = 2 * batch * seqlen * heads * head_dim * 4
817        + batch * seqlen * heads * 4
818        + 2 * batch * seqlen * heads * state_dim * 4
819        + heads * 4;
820    CostEstimate {
821        flops,
822        bytes_moved,
823        kernel_overhead_ns: 50,
824    }
825}
826
827/// Precision guarantee for `(SSD_CHUNK_SCAN, Cpu, *)` — same shape
828/// as `SELECTIVE_SCAN_CPU_PRECISION`.
829pub const SSD_CHUNK_SCAN_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
830    bit_stable_on_same_hardware: true,
831    max_ulp: None,
832    max_relative: None,
833    max_absolute: None,
834    notes: "fuel-cpu-backend SsdChunkScan: per-head state recurrence \
835            in F64 accumulator; narrow to F32 on y store; \
836            deterministic iteration order; same-hardware re-run \
837            bit-identical. chunk_size is a GPU-parallelism knob; \
838            CPU runs sequential, any positive chunk_size dividing \
839            seqlen produces the same answer.",
840};
841
842/// Static cost model for `(NF4_MATMUL, Cpu)` — bitsandbytes 4-bit
843/// quantized matmul. FLOPs scale with `batch · m · n · k`
844/// (one FMA per k step, after dequant). Bandwidth reads
845/// `batch·m·k` activations + `n·k/2` packed weight bytes + `n·k/block_size`
846/// absmax scales + writes `batch·m·n` outputs.
847pub fn cost_nf4_matmul_cpu(
848    shapes: &[Shape],
849    params: &FusedOpParams,
850    _caps: &BackendCapabilities,
851) -> CostEstimate {
852    debug_assert_eq!(
853        shapes.len(),
854        3,
855        "Nf4Matmul cost: expected 3 input shapes (activations, w_packed, absmax)",
856    );
857    let block_size = match params {
858        FusedOpParams::Nf4Matmul { block_size } => *block_size as u64,
859        _ => return CostEstimate::default(),
860    };
861    let a_dims = shapes[0].dims();
862    let w_dims = shapes[1].dims();
863    if a_dims.len() < 2 || w_dims.len() != 2 {
864        return CostEstimate::default();
865    }
866    let m = a_dims[a_dims.len() - 2] as u64;
867    let k = a_dims[a_dims.len() - 1] as u64;
868    let n = w_dims[0] as u64;
869    let batch: u64 = a_dims[..a_dims.len() - 2]
870        .iter()
871        .map(|d| *d as u64)
872        .product::<u64>()
873        .max(1);
874    if block_size == 0 || !k.is_multiple_of(block_size) {
875        return CostEstimate::default();
876    }
877    // 2 FLOPs per FMA (mul + add). Dequant lookup is one mul per k step.
878    let flops = batch * m * n * k * 3;
879    // Bandwidth: 4 B/elem default (F32-ish), 1 B/elem for w_packed.
880    let elem_bytes = 4;
881    let bytes_moved = batch * m * k * elem_bytes
882        + n * (k / 2)
883        + n * (k / block_size) * 4
884        + batch * m * n * elem_bytes;
885    CostEstimate {
886        flops,
887        bytes_moved,
888        kernel_overhead_ns: 50,
889    }
890}
891
892/// Precision guarantee for `(NF4_MATMUL, Cpu, *)` — inner product
893/// accumulated in F32 regardless of activation/output dtype (F16 +
894/// BF16 variants up-cast on load and narrow on store, matching
895/// bitsandbytes' fp16/bf16 GEMV behavior). Iteration order fixed;
896/// bit-identical re-run on same hardware. The 16-entry NF4 LUT is
897/// baked in as a const so quantization roundtrips are reproducible.
898pub const NF4_MATMUL_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
899    bit_stable_on_same_hardware: true,
900    max_ulp: None,
901    max_relative: None,
902    max_absolute: None,
903    notes: "fuel-cpu-backend Nf4Matmul: dequant via baked NF4_LUT × \
904            per-block absmax; F32 accumulator for the inner product \
905            (F16/BF16 up-cast on load, narrow on store); \
906            deterministic iteration order; same-hardware re-run \
907            bit-identical.",
908};
909
910/// Static cost model for `(CONV2D, Cpu)` kernels — FLOP + bandwidth
911/// per architecture v1.0 §"Layer-1 cost model."
912///
913/// Shapes: `[x, weight, (bias)]` where `x = [N, Cin, H, W]`,
914/// `weight = [Cout, Cin/groups, Kh, Kw]`, optional `bias = [Cout]`.
915/// The per-instance `FusedOpParams::Conv2D { stride, padding, groups }`
916/// supply the rest; output spatial dims are recomputed from input
917/// shape + params via the standard `(H + 2·pad - Kh) / stride + 1`.
918pub fn cost_conv2d_cpu(
919    shapes: &[Shape],
920    params: &FusedOpParams,
921    _caps: &BackendCapabilities,
922) -> CostEstimate {
923    debug_assert!(
924        shapes.len() == 2 || shapes.len() == 3,
925        "Conv2D cost: expected 2 or 3 input shapes",
926    );
927    let (stride, padding, groups) = match params {
928        FusedOpParams::Conv2D {
929            stride,
930            padding,
931            groups,
932        } => (*stride, *padding, *groups),
933        _ => return CostEstimate::default(),
934    };
935    let x_dims = shapes[0].dims();
936    let w_dims = shapes[1].dims();
937    if x_dims.len() != 4 || w_dims.len() != 4 || groups == 0 {
938        return CostEstimate::default();
939    }
940    let (n, cin, h_in, w_in) = (
941        x_dims[0] as u64,
942        x_dims[1] as u64,
943        x_dims[2] as u64,
944        x_dims[3] as u64,
945    );
946    let (cout, cin_per_g, kh, kw) = (
947        w_dims[0] as u64,
948        w_dims[1] as u64,
949        w_dims[2] as u64,
950        w_dims[3] as u64,
951    );
952    let (sh, sw) = (stride.0 as u64, stride.1 as u64);
953    let (ph, pw) = (padding.0 as u64, padding.1 as u64);
954    if sh == 0 || sw == 0 || kh > h_in + 2 * ph || kw > w_in + 2 * pw {
955        return CostEstimate::default();
956    }
957    let h_out = (h_in + 2 * ph - kh) / sh + 1;
958    let w_out = (w_in + 2 * pw - kw) / sw + 1;
959    // FMA counts as 2 FLOPs per (Cin/g · Kh · Kw) inner-product step,
960    // summed across N · Cout · Hout · Wout output positions. Bias-add
961    // contributes one FLOP per output element.
962    let conv_flops = 2u64 * n * cout * h_out * w_out * cin_per_g * kh * kw;
963    let bias_flops = if shapes.len() == 3 {
964        n * cout * h_out * w_out
965    } else {
966        0
967    };
968    let elems_in = n * cin * h_in * w_in;
969    let elems_w = cout * cin_per_g * kh * kw;
970    let elems_out = n * cout * h_out * w_out;
971    let elems_bias = if shapes.len() == 3 { cout } else { 0 };
972    let bytes_moved = (elems_in + elems_w + elems_out + elems_bias) * 4;
973    CostEstimate {
974        flops: conv_flops + bias_flops,
975        bytes_moved,
976        kernel_overhead_ns: 50,
977    }
978}
979
980/// Precision guarantee shared by every `(CONV2D, Cpu, *)` impl in
981/// fuel-cpu-backend: textbook nested-loop accumulation in F32 (F64
982/// kernels accumulate in F64; BF16/F16 upcast each multiply to F32
983/// and narrow at end), bit-identical re-run on same hardware.
984/// Same shape as [`FUSED_LINEAR_CPU_PRECISION`] — the conv kernel's
985/// numerical character is governed by the same "F32 accumulator,
986/// deterministic iteration order" properties.
987pub const CONV2D_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
988    bit_stable_on_same_hardware: true,
989    max_ulp: None,
990    max_relative: None,
991    max_absolute: None,
992    notes: "fuel-cpu-backend Conv2D: textbook nested-loop \
993            cross-correlation; F32 accumulator (F64 for F64 input); \
994            BF16/F16 multiply in F32 and narrow at end; same-hardware \
995            re-run bit-identical.",
996};
997
998// =============================================================================
999// Phase 7.6 step 6 — cost functions + PrecisionGuarantees for the
1000// remaining 8 ops that have CPU byte-level wrappers in
1001// `fuel-storage::dispatch`. The four backward helpers
1002// (SoftmaxLastDimBackward / LayerNormLastDimBackward /
1003// RmsNormLastDimBackward / ReduceMaxToBackward) are not covered
1004// here — their CPU dispatch flows through the `GraphBackend` trait
1005// methods in `fuel-graph-executor`, not the byte-level binding
1006// table. Wrapper conversion + step-6 registration for those is a
1007// follow-up.
1008// =============================================================================
1009
1010/// Shared precision guarantee for the norm/softmax family — softmax,
1011/// rms_norm, layer_norm. All three CPU kernels use deterministic
1012/// elementwise + scalar-reduction patterns with F32 accumulator
1013/// (F64 for F64 input; BF16/F16 multiply in F32 and narrow at end).
1014/// Same shape as [`FUSED_LINEAR_CPU_PRECISION`] — the numerical
1015/// character is governed by the same "F32 accumulator, deterministic
1016/// iteration order" properties.
1017pub const NORM_FAMILY_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1018    bit_stable_on_same_hardware: true,
1019    max_ulp: None,
1020    max_relative: None,
1021    max_absolute: None,
1022    notes: "fuel-cpu-backend Softmax/RmsNorm/LayerNorm: deterministic \
1023            elementwise + per-row reduction; F32 accumulator (F64 for \
1024            F64 input); BF16/F16 multiply in F32 and narrow at end; \
1025            same-hardware re-run bit-identical.",
1026};
1027
1028/// Cost model for `(SoftmaxLastDim | RmsNormLastDim | LayerNormLastDim,
1029/// Cpu)` kernels — outer-product structure: `outer × last_dim`
1030/// elementwise pass + scalar reduction. FLOPs scale linearly with
1031/// element count, bandwidth dominates for typical token-dim sizes.
1032///
1033/// Phase 7.6 step 8 — branches on `FusedOpParams` to use a per-op
1034/// FLOP/element count: softmax ≈ 5, rms_norm ≈ 4, layer_norm ≈ 7
1035/// (plus their backwards, which do comparable per-element work).
1036/// Replaces the step-6 midpoint-of-5 estimate. Both forward and
1037/// backward variants of each norm use the same FLOP/element count
1038/// because they touch the data the same way per row.
1039///
1040/// Shapes: `[x]` (forward, 1 input) or `[x_or_y, g]` (backward,
1041/// 2 inputs). Total element count comes from `input[0]` either way.
1042pub fn cost_norm_family_cpu(
1043    shapes: &[Shape],
1044    params: &FusedOpParams,
1045    _caps: &BackendCapabilities,
1046) -> CostEstimate {
1047    debug_assert!(
1048        !shapes.is_empty(),
1049        "Norm-family cost: expected ≥1 input shape",
1050    );
1051    let dims = shapes[0].dims();
1052    if dims.is_empty() {
1053        return CostEstimate::default();
1054    }
1055    let elems: u64 = dims.iter().map(|&d| d as u64).product();
1056    let flops_per_elem: u64 = match params {
1057        FusedOpParams::SoftmaxLastDim | FusedOpParams::SoftmaxLastDimBackward => 5, // max-sub + exp + sum + divide
1058        FusedOpParams::RmsNormLastDim { .. } | FusedOpParams::RmsNormLastDimBackward { .. } => 4, // sqr + sum + sqrt + divide
1059        FusedOpParams::LayerNormLastDim { .. } | FusedOpParams::LayerNormLastDimBackward { .. } => {
1060            7
1061        } // mean-sub + sqr + sum + sqrt + divide + center
1062        _ => 5, // fallback if a future caller mis-dispatches
1063    };
1064    // Backwards have 2 inputs + 1 output (3 element-count touches);
1065    // forwards have 1 input + 1 output (2 element-count touches).
1066    let bandwidth_factor: u64 = if shapes.len() >= 2 { 3 } else { 2 };
1067    CostEstimate {
1068        flops: flops_per_elem * elems,
1069        bytes_moved: bandwidth_factor * elems * 4,
1070        kernel_overhead_ns: 50,
1071    }
1072}
1073
1074/// Precision guarantee for `(ROPE, Cpu, *)` impls. Rotary position
1075/// embedding is a rotation in 2D subspaces — multiplies + adds with
1076/// the cos/sin tables; F32 accumulator semantics match the norm
1077/// family.
1078pub const ROPE_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1079    bit_stable_on_same_hardware: true,
1080    max_ulp: None,
1081    max_relative: None,
1082    max_absolute: None,
1083    notes: "fuel-cpu-backend Rope: per-head rotation `out = x·cos + \
1084            rotated(x)·sin` with deterministic iteration order. \
1085            BF16/F16 multiply in F32 and narrow at end; same-hardware \
1086            re-run bit-identical.",
1087};
1088
1089/// Cost model for `(ROPE, Cpu)` — per-element rotation costs 4 FMAs
1090/// (2 multiplies + 2 adds in two 2D planes).
1091///
1092/// Shapes: `[x, cos, sin]` where `x = [..., seq, head_dim]`,
1093/// `cos = sin = [seq, head_dim]`.
1094pub fn cost_rope_cpu(
1095    shapes: &[Shape],
1096    _params: &FusedOpParams,
1097    _caps: &BackendCapabilities,
1098) -> CostEstimate {
1099    debug_assert_eq!(
1100        shapes.len(),
1101        3,
1102        "Rope cost: expected 3 input shapes (x, cos, sin)"
1103    );
1104    let dims = shapes[0].dims();
1105    if dims.is_empty() {
1106        return CostEstimate::default();
1107    }
1108    let elems: u64 = dims.iter().map(|&d| d as u64).product();
1109    // 4 FLOPs per element (2 FMA pairs across the two rotation planes).
1110    let flops = 4 * elems;
1111    // Read x + cos/sin tables (small), write x_out.
1112    let cs_elems: u64 = shapes[1].dims().iter().map(|&d| d as u64).product::<u64>() * 2;
1113    let bytes_moved = (2 * elems + cs_elems) * 4;
1114    CostEstimate {
1115        flops,
1116        bytes_moved,
1117        kernel_overhead_ns: 50,
1118    }
1119}
1120
1121/// Precision guarantee for `(CONV_TRANSPOSE2D, Cpu, *)` impls.
1122/// Same structure as Conv2D — textbook nested-loop accumulation in
1123/// F32 (F64 for F64 input).
1124pub const CONV_TRANSPOSE2D_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1125    bit_stable_on_same_hardware: true,
1126    max_ulp: None,
1127    max_relative: None,
1128    max_absolute: None,
1129    notes: "fuel-cpu-backend ConvTranspose2D: textbook scatter-with-stride \
1130            + nested loops; F32 accumulator (F64 for F64); BF16/F16 \
1131            multiply in F32 and narrow at end; same-hardware bit-identical.",
1132};
1133
1134/// Cost model for `(CONV_TRANSPOSE2D, Cpu)` — FLOP count parallels
1135/// Conv2D: `2·N·Cout·Hout·Wout·(Cin/g)·Kh·Kw` (each output position
1136/// accumulates contributions from `Cin/g · Kh · Kw` input positions,
1137/// reading transposed).
1138///
1139/// Shapes: `[x, weight]` where `x = [N, Cin, H, W]`,
1140/// `weight = [Cin, Cout/groups, Kh, Kw]` (note transposed channel
1141/// order vs Conv2D).
1142pub fn cost_conv_transpose2d_cpu(
1143    shapes: &[Shape],
1144    params: &FusedOpParams,
1145    _caps: &BackendCapabilities,
1146) -> CostEstimate {
1147    debug_assert_eq!(
1148        shapes.len(),
1149        2,
1150        "ConvTranspose2D cost: expected 2 input shapes"
1151    );
1152    let (stride, padding, output_padding, dilation, groups) = match params {
1153        FusedOpParams::ConvTranspose2D {
1154            stride,
1155            padding,
1156            output_padding,
1157            dilation,
1158            groups,
1159        } => (*stride, *padding, *output_padding, *dilation, *groups),
1160        _ => return CostEstimate::default(),
1161    };
1162    let x_dims = shapes[0].dims();
1163    let w_dims = shapes[1].dims();
1164    if x_dims.len() != 4 || w_dims.len() != 4 || groups == 0 {
1165        return CostEstimate::default();
1166    }
1167    let (n, cin, h_in, w_in) = (
1168        x_dims[0] as u64,
1169        x_dims[1] as u64,
1170        x_dims[2] as u64,
1171        x_dims[3] as u64,
1172    );
1173    let (_, cout_per_g, kh, kw) = (
1174        w_dims[0] as u64,
1175        w_dims[1] as u64,
1176        w_dims[2] as u64,
1177        w_dims[3] as u64,
1178    );
1179    let cout = cout_per_g * groups as u64;
1180    // Output spatial dims: `(H-1)·stride - 2·pad + dilation·(K-1) + out_pad + 1`.
1181    let h_out = h_in.saturating_sub(1) * stride.0 as u64
1182        + dilation.0 as u64 * kh.saturating_sub(1)
1183        + output_padding.0 as u64
1184        + 1;
1185    let h_out = h_out.saturating_sub(2 * padding.0 as u64);
1186    let w_out = w_in.saturating_sub(1) * stride.1 as u64
1187        + dilation.1 as u64 * kw.saturating_sub(1)
1188        + output_padding.1 as u64
1189        + 1;
1190    let w_out = w_out.saturating_sub(2 * padding.1 as u64);
1191    let cin_per_g = cin / groups as u64;
1192    let flops = 2u64 * n * cout * h_out * w_out * cin_per_g * kh * kw;
1193    let elems_in = n * cin * h_in * w_in;
1194    let elems_w = cin * cout_per_g * kh * kw;
1195    let elems_out = n * cout * h_out * w_out;
1196    let bytes_moved = (elems_in + elems_w + elems_out) * 4;
1197    CostEstimate {
1198        flops,
1199        bytes_moved,
1200        kernel_overhead_ns: 50,
1201    }
1202}
1203
1204/// Precision guarantee for `(FLASH_ATTN | PAGED_ATTN, Cpu, *)` impls.
1205/// The CPU naive-attention reference is bit-stable per-hardware
1206/// because both kernels iterate in fixed order. However the tiled
1207/// flash-attention GPU kernel produces different numerics than the
1208/// naive reference (different reduction tree); that's a GPU-side
1209/// PrecisionGuarantee concern — the CPU side stays bit-stable.
1210pub const ATTN_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1211    bit_stable_on_same_hardware: true,
1212    max_ulp: None,
1213    max_relative: None,
1214    max_absolute: None,
1215    notes: "fuel-cpu-backend FlashAttn/PagedAttn: naive scaled-dot- \
1216            product reference; F32 accumulator; deterministic \
1217            iteration order; bit-identical re-run on same hardware. \
1218            GPU kernels produce different numerics (tiled softmax) — \
1219            their PrecisionGuarantee is declared separately when they \
1220            register.",
1221};
1222
1223/// Cost model for `(FLASH_ATTN, Cpu)` and `(PAGED_ATTN, Cpu)` kernels
1224/// — scaled-dot-product attention is `O(B·Hq·Sq·Sk·D)` multiplies
1225/// for the QK matmul + same for the PV matmul, plus softmax (small).
1226///
1227/// For FlashAttn shapes are `[q, k, v, (alibi)]` with
1228/// `q = [B, Hq, Sq, D]`, `k = v = [B, Hkv, Sk, D]`.
1229/// For PagedAttn the cache shapes complicate the calculation; we
1230/// approximate using q's `Sq` × the maximum context length implied
1231/// by k_cache's `num_blocks · block_size`. Both share this function
1232/// because the dominant FLOP term has the same shape.
1233pub fn cost_attn_cpu(
1234    shapes: &[Shape],
1235    _params: &FusedOpParams,
1236    _caps: &BackendCapabilities,
1237) -> CostEstimate {
1238    if shapes.is_empty() {
1239        return CostEstimate::default();
1240    }
1241    let q_dims = shapes[0].dims();
1242    if q_dims.len() != 4 {
1243        return CostEstimate::default();
1244    }
1245    let (b, hq, sq, d) = (
1246        q_dims[0] as u64,
1247        q_dims[1] as u64,
1248        q_dims[2] as u64,
1249        q_dims[3] as u64,
1250    );
1251    // Approximate K-len from input[1] (k or k_cache). For FlashAttn
1252    // k.shape[-2] is Sk; for PagedAttn k_cache.shape is `[num_blocks,
1253    // block_size, Hkv, D]` so the effective Sk per query is bounded
1254    // by `num_blocks · block_size`.
1255    let sk: u64 = if shapes.len() >= 2 {
1256        let k_dims = shapes[1].dims();
1257        if k_dims.len() == 4 {
1258            // FlashAttn shape: [B, Hkv, Sk, D] → Sk at index 2.
1259            // PagedAttn shape: [num_blocks, block_size, Hkv, D] →
1260            // total slots = dim[0] · dim[1]; conservative upper bound.
1261            (k_dims[2] as u64).max(k_dims[0] as u64 * k_dims[1] as u64)
1262        } else {
1263            sq
1264        }
1265    } else {
1266        sq
1267    };
1268    // QK matmul: 2·B·Hq·Sq·Sk·D FLOPs.
1269    // PV matmul: 2·B·Hq·Sq·Sk·D FLOPs.
1270    // Softmax: ~5·B·Hq·Sq·Sk FLOPs (small relative to the matmuls).
1271    let mm_flops = 4u64 * b * hq * sq * sk * d;
1272    let sm_flops = 5u64 * b * hq * sq * sk;
1273    // Bandwidth: q, k, v reads + output write; approximate.
1274    let elems_qkv = b * hq * sq * d + 2 * b * hq * sk * d;
1275    let elems_out = b * hq * sq * d;
1276    let bytes_moved = (elems_qkv + elems_out) * 4;
1277    CostEstimate {
1278        flops: mm_flops + sm_flops,
1279        bytes_moved,
1280        // Attention has higher launch overhead than elementwise.
1281        kernel_overhead_ns: 200,
1282    }
1283}
1284
1285/// Precision guarantee for `(FLASH_ATTN_BACKWARD_{Q,K,V}, Cpu, *)`
1286/// impls. The CPU backward is the math-definition gradient: it
1287/// recomputes the forward softmax probabilities row-by-row and
1288/// accumulates dQ/dK/dV with sequential nested loops — fixed
1289/// iteration order, no atomics, no parallel reductions. F32/F64 run
1290/// natively; BF16/F16 accumulate in F32 and narrow on store.
1291/// Bit-identical re-run on same hardware.
1292pub const ATTN_BACKWARD_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1293    bit_stable_on_same_hardware: true,
1294    max_ulp: None,
1295    max_relative: None,
1296    max_absolute: None,
1297    notes: "fuel-cpu-backend FlashAttnBackward{Q,K,V}: math-definition \
1298            gradient with recomputed softmax; sequential nested-loop \
1299            accumulation (F32 accumulator for half types); \
1300            deterministic iteration order; bit-identical re-run on \
1301            same hardware. GPU backward kernels (tiled, atomics) \
1302            declare their own PrecisionGuarantee when they register.",
1303};
1304
1305/// Cost model for `(FLASH_ATTN_BACKWARD_{Q,K,V}, Cpu)` kernels. The
1306/// math-definition backward recomputes the attention probabilities
1307/// (one QKᵀ matmul) and then forms dV, dP, dQ and dK — five
1308/// `O(B·Hq·Sq·Sk·D)` matmul-shaped passes vs the forward's two.
1309/// The CPU byte wrapper additionally computes ALL THREE gradients
1310/// per call and persists only the requested one (the Q/K/V OpKind
1311/// split has one output each), so the per-call cost does not shrink
1312/// with the selected gradient.
1313///
1314/// Shapes are `[q, k, v, do, (alibi)]` with `q = do = [B, Hq, Sq, D]`,
1315/// `k = v = [B, Hkv, Sk, D]`.
1316pub fn cost_attn_backward_cpu(
1317    shapes: &[Shape],
1318    _params: &FusedOpParams,
1319    _caps: &BackendCapabilities,
1320) -> CostEstimate {
1321    if shapes.is_empty() {
1322        return CostEstimate::default();
1323    }
1324    let q_dims = shapes[0].dims();
1325    if q_dims.len() != 4 {
1326        return CostEstimate::default();
1327    }
1328    let (b, hq, sq, d) = (
1329        q_dims[0] as u64,
1330        q_dims[1] as u64,
1331        q_dims[2] as u64,
1332        q_dims[3] as u64,
1333    );
1334    let sk: u64 = if shapes.len() >= 2 {
1335        let k_dims = shapes[1].dims();
1336        if k_dims.len() == 4 {
1337            k_dims[2] as u64
1338        } else {
1339            sq
1340        }
1341    } else {
1342        sq
1343    };
1344    // Five matmul-shaped passes (P recompute, dV, dP, dQ, dK):
1345    // 2·B·Hq·Sq·Sk·D FLOPs each.
1346    let mm_flops = 10u64 * b * hq * sq * sk * d;
1347    // Softmax recompute + dS row reductions: ~8·B·Hq·Sq·Sk.
1348    let sm_flops = 8u64 * b * hq * sq * sk;
1349    // Bandwidth: q + do reads, k + v reads (Hkv ≈ Hq approximation,
1350    // mirroring cost_attn_cpu), plus all three gradient buffers
1351    // written (the wrapper materializes dQ, dK and dV internally
1352    // even though only one persists).
1353    let elems_read = 2 * b * hq * sq * d + 2 * b * hq * sk * d;
1354    let elems_written = b * hq * sq * d + 2 * b * hq * sk * d;
1355    let bytes_moved = (elems_read + elems_written) * 4;
1356    CostEstimate {
1357        flops: mm_flops + sm_flops,
1358        bytes_moved,
1359        // Same launch-overhead class as the attention forward.
1360        kernel_overhead_ns: 200,
1361    }
1362}
1363
1364/// Precision guarantee for `(QMATMUL, Cpu, *)` impls. Quantized
1365/// matmul dequantizes inline; the dequant arithmetic is exact for
1366/// the quantization scheme's block format, and the F32 matmul
1367/// accumulator stays deterministic. Bit-identical on same hardware.
1368///
1369/// NOT a statement of closeness to the exact product: the kernel quantizes the activations to
1370/// 8 bits as ggml does and is 3e-3 to 8e-3 off it (ROADMAP row 129, a documented property).
1371pub const QMATMUL_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1372    bit_stable_on_same_hardware: true,
1373    max_ulp: None,
1374    max_relative: None,
1375    max_absolute: None,
1376    notes: "fuel-cpu-backend QMatMul: per-block dequant + F32 matmul \
1377            accumulate; deterministic iteration order; bit-identical \
1378            re-run on same hardware. Inherent precision loss from \
1379            the quantization itself is a property of the QuantType, \
1380            not the kernel — captured separately when the calibration \
1381            framework lands.",
1382};
1383
1384/// Precision guarantee for `(REDUCE_MAX_TO_BACKWARD, Cpu, *)` impls.
1385/// The kernel recomputes the forward max, builds a tie-mask,
1386/// counts ties via reduce_sum, divides upstream by the count, then
1387/// broadcasts back and gates by the mask. All deterministic on
1388/// same hardware (no atomics, no parallel reductions); F32
1389/// accumulator for half-precision dtypes via the shared
1390/// `reduce_max_to_backward_impl` adapter.
1391pub const REDUCE_MAX_TO_BACKWARD_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1392    bit_stable_on_same_hardware: true,
1393    max_ulp: None,
1394    max_relative: None,
1395    max_absolute: None,
1396    notes: "fuel-cpu-backend ReduceMaxTo backward: recomputed-max + \
1397            tie-mask + scale + gate; deterministic iteration order; \
1398            F32 accumulator for half-precision; bit-identical same-\
1399            hardware re-run.",
1400};
1401
1402/// Precision guarantee for `(INPLACE_AFFINE, Cpu)`. Single-pass
1403/// `x = mul · x + add` per element with no parallel accumulation;
1404/// deterministic iteration order; bit-identical same-hardware re-run.
1405/// The half-precision dtypes (bf16/f16) pivot through f32 for the
1406/// arithmetic, identical to the non-inplace Affine family.
1407pub const INPLACE_AFFINE_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1408    bit_stable_on_same_hardware: true,
1409    max_ulp: None,
1410    max_relative: None,
1411    max_absolute: None,
1412    notes: "fuel-cpu-backend in-place affine: single-pass `mul · x + \
1413            add` per element; deterministic iteration order; F32 pivot \
1414            for half-precision dtypes; bit-identical same-hardware re-run.",
1415};
1416
1417/// Cost model for `(INPLACE_AFFINE, Cpu)`. Single pass: 1 FMA per
1418/// element. Bandwidth is one read + one write per element (in place,
1419/// so the buffer is touched once for read + once for write through
1420/// the same cache line).
1421pub fn cost_inplace_affine_cpu(
1422    shapes: &[Shape],
1423    _params: &FusedOpParams,
1424    _caps: &BackendCapabilities,
1425) -> CostEstimate {
1426    debug_assert_eq!(
1427        shapes.len(),
1428        1,
1429        "InplaceAffine cost: expected 1 input shape"
1430    );
1431    let n: u64 = shapes[0].dims().iter().map(|&d| d as u64).product();
1432    // mul + add per element = 1 FMA. Treat as 1 FLOP for simplicity
1433    // (matches Affine's accounting; the fused mul-add is one tier-2
1434    // float op).
1435    let flops = n;
1436    // In-place: the buffer is read once + written once. Use
1437    // dtype-agnostic 4 bytes/elem default — the cost model's caller
1438    // scales by the actual dtype size if it cares.
1439    let bytes_moved = n * 4 * 2;
1440    CostEstimate {
1441        flops,
1442        bytes_moved,
1443        kernel_overhead_ns: 50,
1444    }
1445}
1446
1447/// Precision guarantee for `(POWI_BACKWARD, Cpu)`. Per-element
1448/// `grad_x = exp · x^(exp-1) · upstream` with the same floating-point
1449/// determinism guarantees as the forward PowI primitive: deterministic
1450/// iteration order, no parallel reductions, F32 compute for half-
1451/// precision dtypes via the shared `powi_backward_half_kernel`.
1452pub const POWI_BACKWARD_CPU_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1453    bit_stable_on_same_hardware: true,
1454    max_ulp: None,
1455    max_relative: None,
1456    max_absolute: None,
1457    notes: "fuel-cpu-backend PowI backward: single-pass `exp · \
1458            x.powi(exp-1) · upstream` per element; deterministic \
1459            iteration order; F32 compute for half-precision; bit-\
1460            identical same-hardware re-run.",
1461};
1462
1463/// Cost model for `(POWI_BACKWARD, Cpu)` — single pass over the input:
1464/// per-element `powi(exp-1)` (≈ log2(|exp|) FMAs) + 2 multiplies. Bandwidth
1465/// dominated by reading `x` + `upstream` and writing `grad_x`.
1466pub fn cost_powi_backward_cpu(
1467    shapes: &[Shape],
1468    params: &FusedOpParams,
1469    _caps: &BackendCapabilities,
1470) -> CostEstimate {
1471    debug_assert_eq!(
1472        shapes.len(),
1473        2,
1474        "PowIBackward cost: expected 2 input shapes"
1475    );
1476    let in_count: u64 = shapes[0].dims().iter().map(|&d| d as u64).product();
1477    let exp_abs = match params {
1478        FusedOpParams::PowIBackward { exp } => (*exp).unsigned_abs().max(1) as u64,
1479        _ => 1,
1480    };
1481    // power-by-squaring: ceil(log2(|exp|)) multiplies for the powi,
1482    // +2 multiplies for the coefficient and upstream factors.
1483    let powi_muls = 64 - exp_abs.leading_zeros() as u64;
1484    let flops = in_count * (powi_muls + 2);
1485    let bytes_moved = in_count * 4 /* x */ + in_count * 4 /* upstream */ + in_count * 4 /* grad_x */;
1486    CostEstimate {
1487        flops,
1488        bytes_moved,
1489        kernel_overhead_ns: 60,
1490    }
1491}
1492
1493/// Cost model for `(REDUCE_MAX_TO_BACKWARD, Cpu)` — five passes over
1494/// the input: forward max, mask build, count, scale, broadcast +
1495/// gate. Roughly `5 · in_count` FLOPs, with bandwidth dominated by
1496/// 5× the input element count.
1497pub fn cost_reduce_max_to_backward_cpu(
1498    shapes: &[Shape],
1499    _params: &FusedOpParams,
1500    _caps: &BackendCapabilities,
1501) -> CostEstimate {
1502    debug_assert_eq!(
1503        shapes.len(),
1504        2,
1505        "ReduceMaxToBackward cost: expected 2 input shapes"
1506    );
1507    let in_count: u64 = shapes[0].dims().iter().map(|&d| d as u64).product();
1508    let out_count: u64 = shapes[1].dims().iter().map(|&d| d as u64).product();
1509    let flops = 5 * in_count + 2 * out_count;
1510    let bytes_moved = (5 * in_count + 3 * out_count) * 4;
1511    CostEstimate {
1512        flops,
1513        bytes_moved,
1514        kernel_overhead_ns: 80,
1515    }
1516}
1517
1518/// Cost model for `(QMATMUL, Cpu)` — same FLOP count as a regular
1519/// matmul (the dequant adds a small per-block overhead that's
1520/// dwarfed by the FMA count for any useful K).
1521///
1522/// Shapes: `[a, w_q_bytes]` where `a = [..., M, K]`. `N` comes from
1523/// the FusedOpParams::QMatMul payload.
1524pub fn cost_qmatmul_cpu(
1525    shapes: &[Shape],
1526    params: &FusedOpParams,
1527    _caps: &BackendCapabilities,
1528) -> CostEstimate {
1529    debug_assert_eq!(shapes.len(), 2, "QMatMul cost: expected 2 input shapes");
1530    let (k, n) = match params {
1531        FusedOpParams::QMatMul { k, n, .. } => (*k as u64, *n as u64),
1532        _ => return CostEstimate::default(),
1533    };
1534    let a_dims = shapes[0].dims();
1535    let rank = a_dims.len();
1536    if rank < 2 {
1537        return CostEstimate::default();
1538    }
1539    let m = a_dims[rank - 2] as u64;
1540    let batch: u64 = a_dims[..rank - 2]
1541        .iter()
1542        .map(|&d| d as u64)
1543        .product::<u64>()
1544        .max(1);
1545    // 2·M·N·K FLOPs per batch (FMA).
1546    let flops = 2 * batch * m * n * k;
1547    // Bandwidth: read A + W_Q (counted as bytes via shapes[1]
1548    // elem_count of U32 = 4 bytes), write C.
1549    let a_elems = batch * m * k;
1550    let w_u32_elems: u64 = shapes[1].dims().iter().map(|&d| d as u64).product();
1551    let c_elems = batch * m * n;
1552    let bytes_moved = (a_elems + c_elems) * 4 + w_u32_elems * 4;
1553    CostEstimate {
1554        flops,
1555        bytes_moved,
1556        kernel_overhead_ns: 50,
1557    }
1558}
1559
1560// =============================================================================
1561// Vulkan PrecisionGuarantee constants (Phase 7.6 step 9c follow-up,
1562// 2026-05-23). Per-kernel precision claims so the optimizer's
1563// tolerance-budget pass can admit Vulkan alternatives. The constants
1564// group Vulkan kernels by their numerical character: pointwise IEEE-
1565// 754 ops (bit-stable, ~1 ULP), half-precision pointwise (bit-stable
1566// at lower mantissa), transcendentals (vendor lib ~2-4 ULP),
1567// reductions (NOT bit-stable due to subgroup composition), matmul
1568// (deterministic accumulation), tensor-core matmul (FMA chains),
1569// byte-level (memcpy, bit-identical), cast, and qmatmul.
1570// =============================================================================
1571
1572/// Vulkan f32 / f64 pointwise ops — Add, Sub, Mul, Div, Maximum,
1573/// Minimum, Neg, Sqr, Sqrt, Relu, Step, Affine, Clamp.
1574///
1575/// IEEE-754 conformant per the Vulkan SPIR-V spec: direct hardware
1576/// FADD / FMUL / FMA per thread, no atomic accumulators, no
1577/// cross-thread communication. Bit-stable on same hardware (kernel
1578/// scheduling doesn't affect per-thread outputs). ULP is the
1579/// standard IEEE-754 round-to-nearest tolerance (≤0.5 ULP for FADD/
1580/// FMUL/FDIV, ≤1 ULP for FMA chains).
1581///
1582/// Not REFERENCE-grade because we don't claim ULP=0 across all
1583/// implementations — Vulkan compilers may reorder commutative ops
1584/// or fuse multiply-adds in ways that differ from a strict
1585/// IEEE-754-strict reference. Within those bounds, every conforming
1586/// Vulkan implementation produces results within 1 ULP.
1587pub const VULKAN_FLOAT_POINTWISE_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1588    bit_stable_on_same_hardware: true,
1589    max_ulp: Some(1),
1590    max_relative: None,
1591    max_absolute: None,
1592    notes: "fuel-vulkan-backend f32/f64 pointwise: direct hardware FADD/\
1593            FMUL/FMA per thread; no atomics; bit-stable on same hardware. \
1594            Within 1 ULP of IEEE-754 round-to-nearest; small variation \
1595            across implementations due to commutative-reorder + FMA fusion.",
1596};
1597
1598/// Vulkan f16 / bf16 pointwise ops — same op surface as
1599/// [`VULKAN_FLOAT_POINTWISE_PRECISION`] at half precision. f16 uses
1600/// shaderFloat16 native ops (where available); bf16 packs two values
1601/// per u32 with software upcast/downcast through f32 for the arithmetic.
1602///
1603/// Bit-stable on same hardware (no atomics, deterministic per-thread).
1604/// ULP claim is 1 in the dtype's mantissa space — meaningful for f16
1605/// (10-bit mantissa) and bf16 (7-bit mantissa) precision budgeting.
1606/// Absolute error scales with magnitude × 2^(-mantissa_bits).
1607pub const VULKAN_HALF_POINTWISE_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1608    bit_stable_on_same_hardware: true,
1609    max_ulp: Some(1),
1610    max_relative: None,
1611    max_absolute: None,
1612    notes: "fuel-vulkan-backend f16/bf16 pointwise: shaderFloat16 native or \
1613            u32-packed bf16; bit-stable on same hardware; within 1 ULP in \
1614            the dtype's mantissa space (10-bit f16, 7-bit bf16).",
1615};
1616
1617/// Vulkan transcendentals — Exp, Log, Sin, Cos, Tanh, Sigmoid, Silu,
1618/// Gelu (f32/f16/bf16/f64). f32/f16 go through GLSL.std.450's vendor-
1619/// library implementations (variable ULP per GPU/driver); f64 uses
1620/// the Horner-polynomial approximations in `unary_f64.slang`
1621/// (target ~1e-12 relative error).
1622///
1623/// Bit-stable on same hardware (driver-deterministic; the
1624/// transcendental implementation is fixed per build). ULP bound is
1625/// loose: Vulkan spec allows 3-4 ULP for GLSL.std.450 transcendentals;
1626/// real implementations are typically tighter (~1-2 ULP on NVIDIA's
1627/// libdevice).
1628pub const VULKAN_TRANSCENDENTAL_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1629    bit_stable_on_same_hardware: true,
1630    max_ulp: Some(4),
1631    max_relative: None,
1632    max_absolute: None,
1633    notes: "fuel-vulkan-backend transcendentals: GLSL.std.450 vendor lib \
1634            (f32/f16/bf16) or Horner polynomial (f64); bit-stable on same \
1635            hardware; Vulkan spec allows ≤4 ULP, real GPUs typically tighter.",
1636};
1637
1638// Vulkan reductions — SumReduce, MaxReduce, MinReduce, MeanReduce,
1639// SoftmaxLastDim, RmsNormLastDim, LayerNormLastDim, and any kernel
1640// that uses subgroup tree reductions — use `PrecisionGuarantee::
1641// UNAUDITED` (audited result of "no static bound to claim"). The
1642// reasoning: subgroup composition is scheduler-determined per
1643// dispatch, so reordering FADDs across subgroups produces different
1644// floating-point results; no static ULP / relative / absolute bound
1645// applies. Their (op, dtypes, Vulkan) tuples are listed in the
1646// `vulkan_dispatch_per_kernel_precision_and_cost_coverage` lint's
1647// `KNOWN_GAPS` allowlist so the lint accepts UNAUDITED for these
1648// specific kernels; new Vulkan reduction kernels must be added to
1649// KNOWN_GAPS at registration time. The architectural decision is
1650// thus visible at review time rather than buried in a per-kernel
1651// constant.
1652
1653/// Vulkan matmul (f32 standard, no tensor cores) — tiled / reg-tile /
1654/// matvec kernels. Accumulation order is deterministic per kernel
1655/// dispatch (each output element's reduction runs in a single thread
1656/// with no cross-thread atomic adds); the kernel is bit-stable on
1657/// same hardware.
1658///
1659/// ULP claim left unspecified; the per-element error is bounded by
1660/// `K · ULP(2 · max_abs_product)` from the K-deep FMA chain.
1661pub const VULKAN_MATMUL_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1662    bit_stable_on_same_hardware: true,
1663    max_ulp: None,
1664    max_relative: None,
1665    max_absolute: None,
1666    notes: "fuel-vulkan-backend f32 matmul: tiled / reg-tile / matvec \
1667            kernels with per-thread sequential FMA accumulation; bit-stable \
1668            on same hardware; error bounded by O(K · ULP) from K-deep \
1669            reduction.",
1670};
1671
1672/// Vulkan tensor-core mixed-precision matmul (f32 × bf16 → f32, via
1673/// `matmul_coop` cooperative kernels on Ampere+ tensor cores).
1674///
1675/// Tensor-core FMAs accumulate in extended precision (f32 internal,
1676/// IEEE-754 conformant FMA chain); the cross-tile reduction happens
1677/// with full f32 precision. Bit-stable on same hardware per the
1678/// Ampere/Ada spec (the tensor cores are deterministic given the
1679/// same inputs + scheduling). ULP claim is wider than pure f32
1680/// because the bf16 inputs lose 16 mantissa bits before the FMA.
1681pub const VULKAN_MATMUL_TENSORCORE_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1682    bit_stable_on_same_hardware: true,
1683    max_ulp: None,
1684    max_relative: None,
1685    max_absolute: None,
1686    notes: "fuel-vulkan-backend tensor-core matmul (f32 × bf16 → f32): \
1687            cooperative-matrix FMAs with f32 internal accumulator; bit-stable \
1688            on same hardware; per-tile error bounded by O(K · ULP_bf16 + \
1689            tile_K · ULP_f32).",
1690};
1691
1692/// Vulkan byte-level (memcpy-style) ops — Triu, Tril, Flip, Roll,
1693/// WriteSlice, IndexSelect, Concat, Copy (D2H/H2D). Pure data movement
1694/// with no FP arithmetic; output bytes are bit-identical to input
1695/// bytes selected/permuted according to the op.
1696///
1697/// Bit-stable on same hardware, ULP/relative/absolute = 0 (byte-level
1698/// equivalence). The strongest precision claim, equivalent to
1699/// REFERENCE but earned through "no FP math" rather than "explicit
1700/// IEEE-754 evaluation."
1701pub const VULKAN_BYTE_LEVEL_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1702    bit_stable_on_same_hardware: true,
1703    max_ulp: Some(0),
1704    max_relative: Some(0.0),
1705    max_absolute: Some(0.0),
1706    notes: "fuel-vulkan-backend byte-level ops (Triu/Tril/Flip/Roll/\
1707            WriteSlice/IndexSelect/Concat/Copy): pure data movement, no FP \
1708            math; bit-identical to input bytes.",
1709};
1710
1711/// Vulkan dtype cast — f32↔f16, f32↔bf16, F8E4M3↔{f32,f16,bf16}.
1712/// Pure conversion with no accumulation; output is the IEEE-754
1713/// round-to-nearest representation of the input in the target dtype.
1714///
1715/// Bit-stable on same hardware (no atomics, no cross-thread comm).
1716/// ULP=0 vs the IEEE-754 round-to-nearest reference for the target
1717/// dtype (the cast itself is exact within the target's representable
1718/// range; any precision loss is inherent to the dtype, not the
1719/// implementation).
1720pub const VULKAN_CAST_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1721    bit_stable_on_same_hardware: true,
1722    max_ulp: Some(0),
1723    max_relative: None,
1724    max_absolute: None,
1725    notes: "fuel-vulkan-backend Cast: pure dtype conversion via SPIR-V \
1726            OpFConvert / OpConvertFToS / OpConvertSToF; bit-stable on same \
1727            hardware; ULP=0 vs IEEE-754 round-to-nearest in target dtype \
1728            (loss is inherent to the target dtype, not the implementation).",
1729};
1730
1731/// Vulkan QMatMul (Q4_0 / Q4_K_M / Q8_0 weights × F32 activation).
1732/// Per-block dequant + per-output-element FMA accumulation; same
1733/// deterministic structure as the CPU QMatMul kernel (bit-stable on
1734/// same hardware).
1735///
1736/// The inherent precision loss from quantization is a property of
1737/// the QuantType (captured separately when the calibration framework
1738/// lands); the kernel itself contributes only the matmul accumulation
1739/// error.
1740pub const VULKAN_QMATMUL_PRECISION: PrecisionGuarantee = PrecisionGuarantee {
1741    bit_stable_on_same_hardware: true,
1742    max_ulp: None,
1743    max_relative: None,
1744    max_absolute: None,
1745    notes: "fuel-vulkan-backend QMatMul (Q4_0/Q4_K_M/Q8_0 × F32): per-block \
1746            dequant + per-output-element FMA; bit-stable on same hardware. \
1747            Quantization precision loss is a QuantType property, not the \
1748            kernel's contribution.",
1749};
1750
1751#[cfg(test)]
1752mod tests {
1753    use super::*;
1754    use fuel_ir::{DType, Layout, Result};
1755    use std::sync::Arc;
1756    use std::sync::RwLock;
1757
1758    fn dummy_kernel(
1759        _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
1760        _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
1761        _layouts: &[Layout],
1762        _params: &crate::kernel::OpParams,
1763    ) -> Result<()> {
1764        Ok(())
1765    }
1766
1767    fn dummy_cost(_s: &[Shape], _p: &FusedOpParams, _c: &BackendCapabilities) -> CostEstimate {
1768        CostEstimate::default()
1769    }
1770
1771    const DUMMY_DTYPES: &[DType] = &[DType::F32];
1772
1773    fn make_impl() -> BackendImpl {
1774        BackendImpl {
1775            kernel: dummy_kernel,
1776            dtypes: DUMMY_DTYPES,
1777            cost: dummy_cost,
1778            precision: PrecisionGuarantee::UNAUDITED,
1779            caps: KernelCaps::empty(),
1780            revision: KernelRevisionHash::UNTRACKED,
1781            cost_expr: None,
1782        }
1783    }
1784
1785    /// Smoke: empty registry has no impls.
1786    #[test]
1787    fn fused_kernel_registry_empty() {
1788        let r = FusedKernelRegistry::new();
1789        assert!(r.is_empty());
1790        assert_eq!(r.len(), 0);
1791        assert!(r.lookup(FusedOpId(1), BackendId::Cpu).is_none());
1792        assert!(r.impls_for(FusedOpId(1)).is_empty());
1793        // Suppress unused-warning for DType import on no-feature builds.
1794        let _ = DType::F32;
1795    }
1796
1797    /// Smoke: register and look up a single impl.
1798    #[test]
1799    fn fused_kernel_registry_register_and_lookup() {
1800        let mut r = FusedKernelRegistry::new();
1801        r.register(FusedOpId(1), BackendId::Cpu, make_impl());
1802        assert!(!r.is_empty());
1803        assert_eq!(r.len(), 1);
1804        let got = r.lookup(FusedOpId(1), BackendId::Cpu);
1805        assert!(got.is_some());
1806        let impls = r.impls_for(FusedOpId(1));
1807        assert_eq!(impls.len(), 1);
1808        assert_eq!(impls[0].0, BackendId::Cpu);
1809    }
1810
1811    /// Re-registering at the same `(id, backend)` appends — multiple
1812    /// alternatives at the same decision point are a feature (e.g.
1813    /// cuBLAS vs CUTLASS bf16 matmul at the same dtype). The route
1814    /// picker filters by dtypes via `lookup_by_dtypes` and ranks
1815    /// remaining alternatives.
1816    #[test]
1817    fn fused_kernel_registry_register_appends_alternatives() {
1818        let mut r = FusedKernelRegistry::new();
1819        r.register(FusedOpId(1), BackendId::Cpu, make_impl());
1820        r.register(FusedOpId(1), BackendId::Cpu, make_impl());
1821        assert_eq!(r.len(), 1, "one id");
1822        assert_eq!(
1823            r.impls_for(FusedOpId(1)).len(),
1824            2,
1825            "two alternatives registered",
1826        );
1827    }
1828
1829    /// PrecisionGuarantee::REFERENCE has the strongest properties.
1830    #[test]
1831    fn precision_guarantee_reference_is_strict() {
1832        let p = PrecisionGuarantee::REFERENCE;
1833        assert!(p.bit_stable_on_same_hardware);
1834        assert_eq!(p.max_ulp, Some(0));
1835    }
1836
1837    /// CostEstimate::default is all-zero.
1838    #[test]
1839    fn cost_estimate_default_zero() {
1840        let c = CostEstimate::default();
1841        assert_eq!(c.flops, 0);
1842        assert_eq!(c.bytes_moved, 0);
1843        assert_eq!(c.kernel_overhead_ns, 0);
1844    }
1845
1846    /// Step 6 — `default_kernel_registry` populates the four CPU
1847    /// FusedLinear impls under `FUSED_LINEAR × Cpu × (F32|F64|BF16|F16)`.
1848    #[test]
1849    fn default_kernel_registry_has_fused_linear_cpu_quartet() {
1850        use fuel_graph::registry::FusedOps;
1851
1852        let r = default_kernel_registry();
1853        let impls = r.impls_for(FusedOps::FUSED_LINEAR);
1854        assert_eq!(
1855            impls.len(),
1856            4,
1857            "expected 4 FusedLinear × Cpu × dtype registrations, got {}",
1858            impls.len(),
1859        );
1860        for (backend, _) in impls {
1861            assert_eq!(*backend, BackendId::Cpu);
1862        }
1863        // Per-dtype lookup hits each registration.
1864        for dtype in [DType::F32, DType::F64, DType::BF16, DType::F16] {
1865            let want = [dtype; 4];
1866            let got = r.lookup_by_dtypes(FusedOps::FUSED_LINEAR, BackendId::Cpu, &want);
1867            assert!(
1868                got.is_some(),
1869                "lookup_by_dtypes missed FusedLinear × Cpu × {dtype:?}",
1870            );
1871            let impl_ = got.unwrap();
1872            assert!(
1873                impl_.precision.bit_stable_on_same_hardware,
1874                "CPU FusedLinear should be bit-stable on same hardware",
1875            );
1876        }
1877    }
1878
1879    /// Step 6 (Conv2D extension) — `default_kernel_registry` populates
1880    /// eight CPU Conv2D impls: four dtypes × {no-bias, with-bias}.
1881    /// The route picker filters by the dtype tuple length to dispatch
1882    /// the right variant per call site.
1883    #[test]
1884    fn default_kernel_registry_has_conv2d_cpu_octet() {
1885        use fuel_graph::registry::FusedOps;
1886
1887        let r = default_kernel_registry();
1888        let impls = r.impls_for(FusedOps::CONV2D);
1889        assert_eq!(
1890            impls.len(),
1891            8,
1892            "expected 8 Conv2D × Cpu × dtype × (no-bias|with-bias) \
1893             registrations, got {}",
1894            impls.len(),
1895        );
1896        for (backend, _) in impls {
1897            assert_eq!(*backend, BackendId::Cpu);
1898        }
1899        // No-bias (rank-3) and with-bias (rank-4) lookups both hit per dtype.
1900        for dtype in [DType::F32, DType::F64, DType::BF16, DType::F16] {
1901            let no_bias = [dtype; 3];
1902            let with_bias = [dtype; 4];
1903            assert!(
1904                r.lookup_by_dtypes(FusedOps::CONV2D, BackendId::Cpu, &no_bias)
1905                    .is_some(),
1906                "lookup_by_dtypes missed Conv2D × Cpu × {dtype:?} (no-bias)",
1907            );
1908            let with_bias_impl = r.lookup_by_dtypes(FusedOps::CONV2D, BackendId::Cpu, &with_bias);
1909            assert!(
1910                with_bias_impl.is_some(),
1911                "lookup_by_dtypes missed Conv2D × Cpu × {dtype:?} (with-bias)",
1912            );
1913            let impl_ = with_bias_impl.unwrap();
1914            assert!(
1915                impl_.precision.bit_stable_on_same_hardware,
1916                "CPU Conv2D should be bit-stable on same hardware",
1917            );
1918        }
1919    }
1920
1921    /// Phase 7.6 step 7 — the architecture v1.0 §05 "always-built
1922    /// backend bit-stable coverage commitment" lint.
1923    ///
1924    /// Every fused op registered in
1925    /// `fuel_graph::registry::default_registry()` MUST have at least
1926    /// one CPU `BackendImpl` in
1927    /// `fuel_memory::fused::default_kernel_registry()` with
1928    /// `precision.bit_stable_on_same_hardware == true`. This is the
1929    /// architecture's correctness anchor: the always-built backend
1930    /// gives every downstream consumer a deterministic
1931    /// implementation to fall back on, so cross-backend equivalence
1932    /// tests have a fixed reference.
1933    ///
1934    /// The lint runs as a unit test so violations surface in CI
1935    /// rather than at runtime. Adding a new `FusedOpEntry` without
1936    /// a matching CPU registration fails this test immediately.
1937    ///
1938    /// As of step-6 follow-up (2026-05-11), the previously-empty-
1939    /// covered backward helpers (SoftmaxLastDimBackward,
1940    /// LayerNormLastDimBackward, RmsNormLastDimBackward,
1941    /// ReduceMaxToBackward) gained byte-level CPU wrappers +
1942    /// binding-table registrations + BackendImpls. The `KNOWN_GAPS`
1943    /// allowlist is therefore **empty** — every registered fused
1944    /// op has bit-stable CPU coverage.
1945    ///
1946    /// Note on primitive Ops: this lint covers the **fused-op**
1947    /// registry only. Primitive ops (Op::Add, Op::MatMul, etc.)
1948    /// dispatch through `KernelBindingTable` and don't carry a
1949    /// `PrecisionGuarantee` field today. Extending the architecture
1950    /// commitment to primitives is step 7b — pending a binding-table
1951    /// refactor or a parallel PrecisionGuarantee side-table per
1952    /// OpKind.
1953    #[test]
1954    fn precision_guarantee_lint_bit_stable_cpu_coverage() {
1955        use fuel_graph::registry::{FusedOpId, FusedOps, default_registry};
1956
1957        // If a future commit introduces a new entry without immediate
1958        // CPU coverage, add it here with a documented reason AND file
1959        // a follow-up to remove the line. This check already detects
1960        // its own expiry: if a CPU registration later appears for an
1961        // allowlisted id, the `has_cpu` check below fails loudly
1962        // rather than silently granting double coverage.
1963        //
1964        // AwqMatmul (fuel-graph's AWQ weight-only GEMM op) has no CPU
1965        // binding: its dequant-then-matmul decompose is built from
1966        // primitive ops that carry their own CPU coverage, but REALIZE
1967        // DOES NOT LOWER AN UNBOUND FUSED OP ON ITS OWN (GAP-367), so an
1968        // AWQ graph realizes on CPU only after an explicit lowering
1969        // (`RuleRegistry::lowering_only`). This lint checks for a DIRECT
1970        // binding-table CPU registration of the fused op itself, which
1971        // AwqMatmul does not have. Reaching the CUDA kernel
1972        // (fuel-cuda-backend/src/baracuda/quant_w4a16.rs::awq_gemm_f16)
1973        // is now registered in the binding table under
1974        // (OpKind::AwqMatmul, Cuda) from kernel-contracts/cuda/awq_matmul.fkc.md,
1975        // which this CPU-coverage lint does not look at; a CPU binding-table
1976        // wrapper is the remaining follow-up for this entry.
1977        const KNOWN_GAPS: &[(FusedOpId, &str)] = &[(
1978            FusedOps::AWQ_MATMUL,
1979            "no CPU binding-table registration (GAP-367): realizes on CPU \
1980             only after an explicit lowering to its decompose",
1981        )];
1982
1983        let meta = default_registry();
1984        let kernels = default_kernel_registry();
1985
1986        let mut failures: Vec<String> = Vec::new();
1987        let mut covered = 0usize;
1988        let mut allowlisted = 0usize;
1989
1990        for entry in meta.entries_iter() {
1991            let id = entry.id;
1992            let name = entry.name;
1993
1994            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == id) {
1995                allowlisted += 1;
1996                // Sanity: a gap entry should have no CPU coverage.
1997                // If a CPU registration shows up for an
1998                // allowlisted id, the gap entry should be removed.
1999                let has_cpu = kernels
2000                    .impls_for(id)
2001                    .iter()
2002                    .any(|(b, _)| *b == BackendId::Cpu);
2003                if has_cpu {
2004                    failures.push(format!(
2005                        "FusedOpId {id:?} ({name}) is on the KNOWN_GAPS allowlist \
2006                         but DOES have a CPU registration now. Reason given was: \
2007                         {reason:?}. Remove the allowlist entry to enable the \
2008                         bit-stable lint.",
2009                    ));
2010                }
2011                continue;
2012            }
2013
2014            let impls = kernels.impls_for(id);
2015            let has_bit_stable_cpu = impls.iter().any(|(backend, impl_)| {
2016                *backend == BackendId::Cpu && impl_.precision.bit_stable_on_same_hardware
2017            });
2018            if has_bit_stable_cpu {
2019                covered += 1;
2020            } else {
2021                failures.push(format!(
2022                    "FusedOpId {id:?} ({name}) has no bit-stable CPU BackendImpl. \
2023                     Architecture v1.0 §05 requires the always-built backend \
2024                     (fuel-cpu-backend) to provide at least one \
2025                     `bit_stable_on_same_hardware: true` kernel per registered \
2026                     fused op. Either add a CPU registration in \
2027                     fuel-storage::dispatch::register_default_fused_kernels with \
2028                     a matching PrecisionGuarantee, or add a line to KNOWN_GAPS \
2029                     above with a documented reason.",
2030                ));
2031            }
2032        }
2033
2034        assert!(
2035            failures.is_empty(),
2036            "Architecture v1.0 bit-stable CPU coverage lint failed:\n{}",
2037            failures.join("\n"),
2038        );
2039        // Sanity: the lint should be exercising real ops. If both
2040        // counts are zero, something is wrong with the registry
2041        // population.
2042        assert!(
2043            covered > 0 || allowlisted > 0,
2044            "lint covered 0 ops — registry appears empty"
2045        );
2046        // Stronger commitment: exactly the one documented gap above,
2047        // no silent additions.
2048        assert_eq!(
2049            allowlisted, 1,
2050            "KNOWN_GAPS allowlist has exactly 1 documented entry (AwqMatmul); \
2051             saw {allowlisted} allowlisted",
2052        );
2053        // Sanity: we should see all 24 registered fused ops covered.
2054        // 14 from the original Phase 7.6 lineup + PowIBackward
2055        // (autograd switched from emitting the primitive decomposition
2056        // to emitting Op::Fused(POWI_BACKWARD, _)) + INPLACE_AFFINE
2057        // (Phase 3 of the in-place ops infrastructure) +
2058        // FUSED_SOFTMAX_CROSS_ENTROPY + CAUSAL_CONV1D + SELECTIVE_SCAN
2059        // + SSD_CHUNK_SCAN + NF4_MATMUL (the full CPU OpKind coverage
2060        // plan: FSCE + Mamba-adjacent trio + NF4) +
2061        // FLASH_ATTN_BACKWARD_{Q,K,V} (reusing the binding-table CPU
2062        // dispatch wrappers). AWQ_MATMUL is the registry's 25th entry
2063        // and is the one documented KNOWN_GAPS allowlist line above,
2064        // not counted here. ROW_SCALED_MATMUL (row 172 item 1) is the 26th
2065        // registry entry and the 25th covered op (delta +1, predicted).
2066        // TOP_K_LAST_DIM (row 172 item 2) is the 27th entry, the 26th covered
2067        // (delta +1, predicted). MATMUL_TOP_K (row 172 item 2 step B) is the
2068        // 28th entry, the 27th covered (delta +1, predicted).
2069        assert_eq!(
2070            covered, 27,
2071            "expected 27 fused ops covered by bit-stable CPU impls, got {covered}",
2072        );
2073    }
2074
2075    /// Negative-path check for the bit-stable lint logic: a
2076    /// `FusedKernelRegistry` with no CPU impl for a registered id
2077    /// must fail the bit-stable check. Verifies the lint's failure
2078    /// detection works rather than just relying on the positive
2079    /// path being green.
2080    ///
2081    /// Doesn't touch `default_kernel_registry()` — runs the check
2082    /// against a freshly-constructed empty registry so the failure
2083    /// is deterministic regardless of global state.
2084    #[test]
2085    fn precision_guarantee_lint_detects_missing_cpu() {
2086        use fuel_graph::registry::FusedOpId;
2087        let empty = FusedKernelRegistry::new();
2088        let id = FusedOpId(1);
2089        // Same predicate the production lint uses.
2090        let has_bit_stable_cpu = empty.impls_for(id).iter().any(|(backend, impl_)| {
2091            *backend == BackendId::Cpu && impl_.precision.bit_stable_on_same_hardware
2092        });
2093        assert!(
2094            !has_bit_stable_cpu,
2095            "empty registry must not report bit-stable CPU coverage"
2096        );
2097    }
2098
2099    /// Negative-path check: a CPU registration without
2100    /// `bit_stable_on_same_hardware: true` must NOT satisfy the
2101    /// lint. Captures the difference between "any CPU impl" and "a
2102    /// bit-stable CPU impl" — the architecture commits to the
2103    /// stronger property.
2104    #[test]
2105    fn precision_guarantee_lint_rejects_non_bit_stable_cpu() {
2106        use fuel_graph::registry::FusedOpId;
2107        let mut r = FusedKernelRegistry::new();
2108        let id = FusedOpId(42);
2109        let weak = BackendImpl {
2110            kernel: dummy_kernel,
2111            dtypes: DUMMY_DTYPES,
2112            cost: dummy_cost,
2113            // UNAUDITED has bit_stable_on_same_hardware: false.
2114            precision: PrecisionGuarantee::UNAUDITED,
2115            caps: KernelCaps::empty(),
2116            revision: KernelRevisionHash::UNTRACKED,
2117            cost_expr: None,
2118        };
2119        r.register(id, BackendId::Cpu, weak);
2120        let has_bit_stable_cpu = r.impls_for(id).iter().any(|(backend, impl_)| {
2121            *backend == BackendId::Cpu && impl_.precision.bit_stable_on_same_hardware
2122        });
2123        assert!(
2124            !has_bit_stable_cpu,
2125            "an UNAUDITED-precision CPU impl must not satisfy the bit-stable lint"
2126        );
2127    }
2128
2129    /// Step 6 + backward-helper follow-up — coverage assertion for
2130    /// the 12 ops that gained BackendImpls (8 forwards from step 6
2131    /// + 4 backward helpers from the follow-up), plus the
2132    ///
2133    /// FlashAttnBackward{Q,K,V} trio (4 dtypes × 2 alibi shapes
2134    /// each, reusing the binding-table CPU wrappers). Each entry
2135    /// should have at least the expected CPU impl count after
2136    /// `default_kernel_registry()` populates.
2137    #[test]
2138    fn default_kernel_registry_step6_coverage() {
2139        use fuel_graph::registry::FusedOps;
2140
2141        let r = default_kernel_registry();
2142        // (id, expected_impl_count) — derived from the dtype-tuple
2143        // shapes registered. SoftmaxLastDim/RmsNormLastDim/
2144        // LayerNormLastDim/Rope = 4 dtypes each. ConvTranspose2D /
2145        // FlashAttn / PagedAttn = 4 dtypes × 2 shapes = 8 each.
2146        // QMatMul = 1 (F32 only). The 4 backward helpers = 4 dtypes
2147        // each.
2148        for (id, want) in [
2149            (FusedOps::SOFTMAX_LAST_DIM, 4usize),
2150            (FusedOps::RMS_NORM_LAST_DIM, 4),
2151            (FusedOps::LAYER_NORM_LAST_DIM, 4),
2152            (FusedOps::ROPE, 4),
2153            (FusedOps::CONV_TRANSPOSE2D, 8),
2154            (FusedOps::FLASH_ATTN, 8),
2155            (FusedOps::FLASH_ATTN_BACKWARD_Q, 8),
2156            (FusedOps::FLASH_ATTN_BACKWARD_K, 8),
2157            (FusedOps::FLASH_ATTN_BACKWARD_V, 8),
2158            (FusedOps::PAGED_ATTN, 8),
2159            (FusedOps::QMATMUL, 1),
2160            (FusedOps::SOFTMAX_LAST_DIM_BACKWARD, 4),
2161            (FusedOps::LAYER_NORM_LAST_DIM_BACKWARD, 4),
2162            (FusedOps::RMS_NORM_LAST_DIM_BACKWARD, 4),
2163            (FusedOps::REDUCE_MAX_TO_BACKWARD, 4),
2164        ] {
2165            let impls = r.impls_for(id);
2166            assert_eq!(
2167                impls.len(),
2168                want,
2169                "expected {want} CPU impls for FusedOpId {id:?}, got {}",
2170                impls.len(),
2171            );
2172            for (backend, impl_) in impls {
2173                assert_eq!(*backend, BackendId::Cpu);
2174                assert!(
2175                    impl_.precision.bit_stable_on_same_hardware,
2176                    "CPU impl for {id:?} should be bit-stable on same hardware",
2177                );
2178            }
2179        }
2180    }
2181
2182    /// Conv2D cost — FLOPs scale with `2·N·Cout·Hout·Wave·(Cin/g)·Kh·Kw`
2183    /// + bias-add FLOPs (when bias is present).
2184    #[test]
2185    fn cost_conv2d_cpu_flops_scale() {
2186        use crate::fused::cost_conv2d_cpu;
2187        use fuel_ir::DeviceLocation;
2188        use std::collections::HashSet;
2189
2190        // x: [N=2, Cin=4, H=8, W=8], w: [Cout=6, Cin/g=4, Kh=3, Kw=3],
2191        // stride=(1,1), padding=(1,1), groups=1.
2192        // Hout = Wout = (8 + 2 - 3) + 1 = 8.
2193        // Conv FLOPs (FMA = 2): 2·N·Cout·Hout·Wout·Cin_per_g·Kh·Kw
2194        //                    = 2·2·6·8·8·4·3·3 = 55296.
2195        // Bias FLOPs: N·Cout·Hout·Wout = 2·6·8·8 = 768.
2196        let x = Shape::from_dims(&[2, 4, 8, 8]);
2197        let w = Shape::from_dims(&[6, 4, 3, 3]);
2198        let bias = Shape::from_dims(&[6]);
2199        let caps = BackendCapabilities {
2200            backend_id: BackendId::Cpu,
2201            device_location: DeviceLocation::Cpu,
2202            op_dtype_support: HashSet::new(),
2203            required_alignment: 1,
2204            access_granularity_bits: 8,
2205            transfer_paths: vec![],
2206            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
2207            compute_throughput_flops_per_ns: 1.0,
2208            mem_bandwidth_bytes_per_ns: 4.0,
2209        };
2210        let params = FusedOpParams::Conv2D {
2211            stride: (1, 1),
2212            padding: (1, 1),
2213            groups: 1,
2214        };
2215        let c = cost_conv2d_cpu(&[x, w, bias], &params, &caps);
2216        assert_eq!(c.flops, 55296 + 768);
2217        assert!(c.bytes_moved > 0);
2218    }
2219
2220    /// Cost model — FLOPs scale with 2·M·N·K + M·N, batch multiplies.
2221    #[test]
2222    fn cost_fused_linear_cpu_flops_scale() {
2223        use fuel_ir::DeviceLocation;
2224        use std::collections::HashSet;
2225
2226        let a = Shape::from_dims(&[2, 4, 8]); // batch=2, M=4, K=8
2227        let b = Shape::from_dims(&[2, 8, 16]); // batch=2, K=8, N=16
2228        let bias = Shape::from_dims(&[16]);
2229        let caps = BackendCapabilities {
2230            backend_id: BackendId::Cpu,
2231            device_location: DeviceLocation::Cpu,
2232            op_dtype_support: HashSet::new(),
2233            required_alignment: 1,
2234            access_granularity_bits: 8,
2235            transfer_paths: vec![],
2236            storage_substrate: fuel_ir::backend::SubstrateClass::HostBytes,
2237            compute_throughput_flops_per_ns: 1.0,
2238            mem_bandwidth_bytes_per_ns: 4.0,
2239        };
2240        let c = cost_fused_linear_cpu(&[a, b, bias], &FusedOpParams::FusedLinear, &caps);
2241        // 2 · 2 · 4 · 16 · 8 = 2048 matmul FLOPs + 2 · 4 · 16 = 128 bias FLOPs
2242        assert_eq!(c.flops, 2048 + 128);
2243        assert!(c.bytes_moved > 0);
2244    }
2245
2246    /// Finding 5.4 (FKC side, Task 3.6) — a `return.bundle`'s per-slot NAMES
2247    /// round-trip through a side-table keyed on `(FusedOpId, BackendId,
2248    /// dtypes)`. Before this task the names were parsed then discarded;
2249    /// `record_bundle_slot_names` / `bundle_slot_names` preserve them so a
2250    /// later consumer (e.g. FDX output-view labeling) can look them up by
2251    /// the same key the kernel itself was registered under. A different
2252    /// dtype key must miss (`None`), never fall back to an unrelated entry.
2253    #[test]
2254    fn bundle_slot_names_round_trip_through_the_fused_registry() {
2255        use fuel_graph::registry::FusedOps;
2256        use fuel_ir::{DType, probe::BackendId};
2257        let mut reg = FusedKernelRegistry::new();
2258        let dtypes = &[DType::F32, DType::F32][..];
2259        reg.record_bundle_slot_names(
2260            FusedOps::SELECTIVE_SCAN,
2261            BackendId::Cpu,
2262            dtypes,
2263            &["y".to_string(), "last_state".to_string()],
2264        );
2265        assert_eq!(
2266            reg.bundle_slot_names(FusedOps::SELECTIVE_SCAN, BackendId::Cpu, dtypes),
2267            Some(&["y".to_string(), "last_state".to_string()][..])
2268        );
2269        assert_eq!(
2270            reg.bundle_slot_names(FusedOps::SELECTIVE_SCAN, BackendId::Cpu, &[DType::F16][..]),
2271            None
2272        );
2273    }
2274}