Skip to main content

fuel_dispatch/
dispatch.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Capability-driven dispatch tables. Phase 7.5 A5.
3//!
4//! `CapabilityRegistry` collects [`BackendCapabilities`] from each
5//! registered backend; `TransferMatrix` encodes the cheapest path
6//! between every pair of registered devices.
7//!
8//! Together they let DAG construction (Phase B) answer two
9//! questions:
10//!
11//! 1. **Which backend should handle `(op, dtype)`?** — query
12//!    [`CapabilityRegistry::find_backends`] / [`crate::dispatch::CapabilityRegistry::find_backend_for`]
13//!    to get the set of registered backends that support the pair.
14//! 2. **How does data move between two devices?** — query
15//!    [`TransferMatrix::path`] for the chosen path; falls back to
16//!    `HostStaging` if no direct path exists.
17//!
18//! The registry is process-wide (typically initialized once at
19//! application startup via `OnceLock`) but exposed here as a value
20//! so tests and alternative dispatch policies can construct their
21//! own. The canonical process-wide instance lives below
22//! ([`global_registry`] / [`global_bindings`]).
23
24use std::collections::HashMap;
25use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, OnceLock, RwLock};
27
28use fuel_ir::backend::{BackendCapabilities, SubstrateClass, TransferPath};
29use fuel_ir::dispatch::OpKind;
30use fuel_ir::probe::BackendId;
31use fuel_ir::{DType, DeviceLocation, Error, Layout, Result};
32
33#[cfg(feature = "cuda")]
34use crate::kernel::KernelCaps;
35use crate::kernel::{KernelBindingTable, MatmulM, OpParams};
36use fuel_memory::{BackendStorage, Storage};
37
38/// Collection of backend capabilities, queried during DAG
39/// construction to pick which backend handles each op.
40#[derive(Debug, Default)]
41pub struct CapabilityRegistry {
42    backends: Vec<BackendCapabilities>,
43}
44
45impl CapabilityRegistry {
46    /// Construct an empty registry. Add backends with `register`.
47    pub fn new() -> Self {
48        Self {
49            backends: Vec::new(),
50        }
51    }
52
53    /// Register a backend's capabilities. Order of registration is
54    /// preserved; lookup methods return registrations in their
55    /// original order so callers can encode preference (CPU
56    /// fallback last; GPU first).
57    pub fn register(&mut self, caps: BackendCapabilities) {
58        self.backends.push(caps);
59    }
60
61    /// All registered backends.
62    pub fn backends(&self) -> &[BackendCapabilities] {
63        &self.backends
64    }
65
66    /// Backends supporting `(op, dtype)`, in registration order.
67    pub fn find_backends(&self, op: OpKind, dtype: DType) -> Vec<&BackendCapabilities> {
68        self.backends
69            .iter()
70            .filter(|caps| caps.op_dtype_support.contains(&(op, dtype)))
71            .collect()
72    }
73
74    /// Pick the first registered backend that supports
75    /// `(op, dtype)`. Returns
76    /// [`Error::NoBackendForOp`](fuel_ir::Error::NoBackendForOp)
77    /// with diagnostic data if none does. Production-correct: never
78    /// panics, always surfaces the gap as a typed error.
79    ///
80    /// "First" follows the order of `register` calls. Convention:
81    /// register GPU before CPU so GPU wins ties; the universal CPU
82    /// fallback gets picked iff no GPU registered for `(op, dtype)`.
83    pub fn find_backend_for(&self, op: OpKind, dtype: DType) -> Result<&BackendCapabilities> {
84        for caps in &self.backends {
85            if caps.op_dtype_support.contains(&(op, dtype)) {
86                return Ok(caps);
87            }
88        }
89        // Capability-level lookups still operate on a single output
90        // dtype (binding-table multi-dtype keys are an execution-time
91        // concern). Wrap the single dtype in a 1-vec for the error so
92        // both error sites share one variant shape.
93        Err(Error::NoBackendForOp {
94            op,
95            dtypes: vec![dtype],
96            available_backends: self.backends.iter().map(|c| c.backend_id).collect(),
97            supported_combinations: self
98                .backends
99                .iter()
100                .flat_map(|c| {
101                    c.op_dtype_support
102                        .iter()
103                        .map(|&(o, d)| (c.backend_id, o, vec![d]))
104                })
105                .collect(),
106        }
107        .bt())
108    }
109
110    /// Build a [`TransferMatrix`] from the registered backends'
111    /// advertised transfer paths. Each backend contributes its
112    /// outbound paths; the matrix consolidates them into a
113    /// `(src, dst) -> TransferPath` lookup.
114    pub fn build_transfer_matrix(&self) -> TransferMatrix {
115        let mut entries = HashMap::new();
116        for caps in &self.backends {
117            for (dst, path) in &caps.transfer_paths {
118                entries.insert((caps.device_location, *dst), *path);
119            }
120        }
121        TransferMatrix { entries }
122    }
123}
124
125/// Lookup table mapping `(source_device, dest_device)` pairs to the
126/// cheapest available [`TransferPath`]. Built once at registration
127/// time from each backend's advertised outbound paths; consulted
128/// every time the DAG inserts an `Op::Move` / `Op::Copy`.
129#[derive(Debug, Default)]
130pub struct TransferMatrix {
131    entries: HashMap<(DeviceLocation, DeviceLocation), TransferPath>,
132}
133
134impl TransferMatrix {
135    /// Look up the registered path between two devices. Returns
136    /// `None` if no direct path was advertised; the caller can
137    /// fall back to host-staging via the universal `HostStaging`
138    /// path.
139    pub fn path(&self, src: DeviceLocation, dst: DeviceLocation) -> Option<TransferPath> {
140        if src == dst {
141            return Some(TransferPath::SameDevice);
142        }
143        self.entries.get(&(src, dst)).copied()
144    }
145
146    /// Same as [`Self::path`] but always returns a path: falls back to
147    /// `TransferPath::HostStaging` (the universal fallback) when no
148    /// direct advertised path exists. CPU is reachable from every
149    /// backend through host-staging, so this never returns an error
150    /// for practical use cases — though see
151    /// [`Error::UnsupportedTransfer`](fuel_ir::Error::UnsupportedTransfer)
152    /// for the case when a backend can't even host-stage.
153    pub fn path_or_staging(&self, src: DeviceLocation, dst: DeviceLocation) -> TransferPath {
154        self.path(src, dst).unwrap_or(TransferPath::HostStaging)
155    }
156
157    /// All entries in the matrix.
158    pub fn entries(
159        &self,
160    ) -> impl Iterator<Item = (&(DeviceLocation, DeviceLocation), &TransferPath)> {
161        self.entries.iter()
162    }
163}
164
165/// Resolve which backend should handle `(op, dtype)` given the
166/// registry of available backends. Returns the chosen `BackendId`
167/// or [`Error::NoBackendForOp`] with diagnostic data on miss.
168///
169/// The chosen backend is the first registered backend that
170/// supports `(op, dtype)`. Convention: register GPU before CPU so
171/// GPU wins ties; the universal CPU fallback is picked iff no GPU
172/// registered.
173///
174/// Phase 7.5 B3 — used by op-builder methods to populate
175/// `Graph::target_backends` at DAG construction time. After the
176/// full migration, every Node has a target_backend set this way.
177pub fn resolve_target_backend(
178    registry: &CapabilityRegistry,
179    op: OpKind,
180    dtype: DType,
181) -> Result<BackendId> {
182    registry
183        .find_backend_for(op, dtype)
184        .map(|caps| caps.backend_id)
185}
186
187/// Residency-aware variant of [`resolve_target_backend`]. Prefers
188/// backends that have at least one input already resident on their
189/// device, breaking ties only on the residency axis (within the
190/// "supports (op, dtype)" set). Falls back to registration order
191/// when no candidate has local input residency.
192///
193/// `input_locations` is the list of input tensors' current
194/// `DeviceLocation`s; pass an empty slice for ops that take no
195/// inputs (constants / factories).
196///
197/// Phase 7.5 B3 — used when the dispatcher should avoid transfers
198/// when possible. A simpler dispatch policy is to call
199/// [`resolve_target_backend`] directly and let Router auto-insert
200/// transfers; the residency-aware version saves transfers when
201/// the choice is otherwise free.
202pub fn resolve_target_backend_residency_aware(
203    registry: &CapabilityRegistry,
204    op: OpKind,
205    dtype: DType,
206    input_locations: &[DeviceLocation],
207) -> Result<BackendId> {
208    let candidates = registry.find_backends(op, dtype);
209    if candidates.is_empty() {
210        // Reuse find_backend_for to construct the canonical error.
211        return registry.find_backend_for(op, dtype).map(|c| c.backend_id);
212    }
213    // Pick a candidate whose device matches at least one input
214    // location.
215    for caps in &candidates {
216        if input_locations.contains(&caps.device_location) {
217            return Ok(caps.backend_id);
218        }
219    }
220    // No residency match — fall back to first candidate
221    // (registration order).
222    Ok(candidates[0].backend_id)
223}
224
225// =============================================================================
226// Phase 7.5 B5 — CPU dispatch wrappers + registration
227// =============================================================================
228
229/// Helper: extract `&CpuStorageBytes` from `&Storage`. Returns
230/// Err if the variant isn't `BackendStorage::Cpu`.
231pub fn cpu_input(s: &Storage) -> Result<&fuel_cpu_backend::CpuStorageBytes> {
232    match &s.inner {
233        BackendStorage::Cpu(c) => Ok(c),
234        #[allow(unreachable_patterns)]
235        _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU input".to_string()).bt()),
236    }
237}
238
239/// Helper: extract `&mut CpuStorageBytes` from `&mut Storage`. `pub`
240/// (along with [`cpu_input`], [`read_storage`], [`write_storage`]) so
241/// external backend crates (fuel-mkl-cpu-backend, fuel-aocl-cpu-backend)
242/// can build their own binding-table wrappers without reimplementing
243/// the lock + dtype-match shape.
244pub fn cpu_output(s: &mut Storage) -> Result<&mut fuel_cpu_backend::CpuStorageBytes> {
245    match &mut s.inner {
246        BackendStorage::Cpu(c) => Ok(c),
247        #[allow(unreachable_patterns)]
248        _ => Err(Error::Msg("cpu kernel wrapper called with non-CPU output".to_string()).bt()),
249    }
250}
251
252/// Acquire a poisoned-lock-aware read guard. Lock poisoning is a
253/// programming bug (a previous writer panicked while holding the
254/// lock); production code surfaces it as a typed error rather than
255/// re-panicking through `unwrap`.
256pub fn read_storage(arc: &Arc<RwLock<Storage>>) -> Result<std::sync::RwLockReadGuard<'_, Storage>> {
257    arc.read()
258        .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (read)".to_string()).bt())
259}
260
261pub fn write_storage(
262    arc: &Arc<RwLock<Storage>>,
263) -> Result<std::sync::RwLockWriteGuard<'_, Storage>> {
264    arc.write()
265        .map_err(|_| Error::Msg("kernel wrapper: storage RwLock poisoned (write)".to_string()).bt())
266}
267
268/// Build a `(2 inputs, 1 output)` CPU dispatch wrapper that calls a
269/// typed binary kernel. The expanded function matches the
270/// [`KernelRef`] signature and is suitable for direct registration
271/// in the binding table.
272macro_rules! cpu_binary_wrapper {
273    ($wrapper:ident, $kernel:path, $op_name:literal) => {
274        // pub(crate) so the FKC vertical-slice test (fkc::register) can name
275        // the real production wrapper and assert an imported binding IS it.
276        pub(crate) fn $wrapper(
277            inputs: &[Arc<RwLock<Storage>>],
278            outputs: &mut [Arc<RwLock<Storage>>],
279            _layouts: &[Layout],
280            _params: &OpParams,
281        ) -> Result<()> {
282            if inputs.len() != 2 {
283                return Err(Error::Msg(format!(
284                    "{} wrapper expects 2 inputs, got {}",
285                    $op_name,
286                    inputs.len(),
287                ))
288                .bt());
289            }
290            if outputs.len() != 1 {
291                return Err(Error::Msg(format!(
292                    "{} wrapper expects 1 output, got {}",
293                    $op_name,
294                    outputs.len(),
295                ))
296                .bt());
297            }
298            let lhs_guard = read_storage(&inputs[0])?;
299            let rhs_guard = read_storage(&inputs[1])?;
300            let mut out_guard = write_storage(&outputs[0])?;
301            let lhs_cpu = cpu_input(&lhs_guard)?;
302            let rhs_cpu = cpu_input(&rhs_guard)?;
303            let out_cpu = cpu_output(&mut out_guard)?;
304            $kernel(lhs_cpu, rhs_cpu, out_cpu)
305        }
306    };
307}
308
309/// Build a `(1 input, 1 output)` CPU dispatch wrapper that calls a
310/// typed unary kernel.
311macro_rules! cpu_unary_wrapper {
312    ($wrapper:ident, $kernel:path, $op_name:literal) => {
313        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the real
314        // production wrapper for the elementwise-unary contract's entry points.
315        pub(crate) fn $wrapper(
316            inputs: &[Arc<RwLock<Storage>>],
317            outputs: &mut [Arc<RwLock<Storage>>],
318            _layouts: &[Layout],
319            _params: &OpParams,
320        ) -> Result<()> {
321            if inputs.len() != 1 {
322                return Err(Error::Msg(format!(
323                    "{} wrapper expects 1 input, got {}",
324                    $op_name,
325                    inputs.len(),
326                ))
327                .bt());
328            }
329            if outputs.len() != 1 {
330                return Err(Error::Msg(format!(
331                    "{} wrapper expects 1 output, got {}",
332                    $op_name,
333                    outputs.len(),
334                ))
335                .bt());
336            }
337            let in_guard = read_storage(&inputs[0])?;
338            let mut out_guard = write_storage(&outputs[0])?;
339            let in_cpu = cpu_input(&in_guard)?;
340            let out_cpu = cpu_output(&mut out_guard)?;
341            $kernel(in_cpu, out_cpu)
342        }
343    };
344}
345
346cpu_binary_wrapper!(
347    add_elementwise_f32_cpu_wrapper,
348    fuel_cpu_backend::byte_kernels::add_f32,
349    "add_elementwise"
350);
351cpu_binary_wrapper!(
352    sub_elementwise_f32_cpu_wrapper,
353    fuel_cpu_backend::byte_kernels::sub_f32,
354    "sub_elementwise"
355);
356cpu_binary_wrapper!(
357    mul_elementwise_f32_cpu_wrapper,
358    fuel_cpu_backend::byte_kernels::mul_f32,
359    "mul_elementwise"
360);
361cpu_binary_wrapper!(
362    div_elementwise_f32_cpu_wrapper,
363    fuel_cpu_backend::byte_kernels::div_f32,
364    "div_elementwise"
365);
366
367cpu_unary_wrapper!(
368    relu_elementwise_f32_cpu_wrapper,
369    fuel_cpu_backend::byte_kernels::relu_f32,
370    "relu_elementwise"
371);
372cpu_unary_wrapper!(
373    neg_elementwise_f32_cpu_wrapper,
374    fuel_cpu_backend::byte_kernels::neg_f32,
375    "neg_elementwise"
376);
377cpu_unary_wrapper!(
378    sqr_elementwise_f32_cpu_wrapper,
379    fuel_cpu_backend::byte_kernels::sqr_f32,
380    "sqr_elementwise"
381);
382cpu_unary_wrapper!(
383    sqrt_elementwise_f32_cpu_wrapper,
384    fuel_cpu_backend::byte_kernels::sqrt_f32,
385    "sqrt_elementwise"
386);
387cpu_unary_wrapper!(
388    recip_elementwise_f32_cpu_wrapper,
389    fuel_cpu_backend::byte_kernels::recip_f32,
390    "recip_elementwise"
391);
392cpu_unary_wrapper!(
393    abs_elementwise_f32_cpu_wrapper,
394    fuel_cpu_backend::byte_kernels::abs_f32,
395    "abs_elementwise"
396);
397cpu_unary_wrapper!(
398    tanh_elementwise_f32_cpu_wrapper,
399    fuel_cpu_backend::byte_kernels::tanh_f32,
400    "tanh_elementwise"
401);
402cpu_unary_wrapper!(
403    exp_elementwise_f32_cpu_wrapper,
404    fuel_cpu_backend::byte_kernels::exp_f32,
405    "exp_elementwise"
406);
407cpu_unary_wrapper!(
408    log_elementwise_f32_cpu_wrapper,
409    fuel_cpu_backend::byte_kernels::log_f32,
410    "log_elementwise"
411);
412cpu_unary_wrapper!(
413    sin_elementwise_f32_cpu_wrapper,
414    fuel_cpu_backend::byte_kernels::sin_f32,
415    "sin_elementwise"
416);
417cpu_unary_wrapper!(
418    cos_elementwise_f32_cpu_wrapper,
419    fuel_cpu_backend::byte_kernels::cos_f32,
420    "cos_elementwise"
421);
422cpu_unary_wrapper!(
423    sigmoid_elementwise_f32_cpu_wrapper,
424    fuel_cpu_backend::byte_kernels::sigmoid_f32,
425    "sigmoid_elementwise"
426);
427cpu_unary_wrapper!(
428    silu_elementwise_f32_cpu_wrapper,
429    fuel_cpu_backend::byte_kernels::silu_f32,
430    "silu_elementwise"
431);
432cpu_unary_wrapper!(
433    gelu_elementwise_f32_cpu_wrapper,
434    fuel_cpu_backend::byte_kernels::gelu_f32,
435    "gelu_elementwise"
436);
437cpu_unary_wrapper!(
438    step_elementwise_f32_cpu_wrapper,
439    fuel_cpu_backend::byte_kernels::step_f32,
440    "step_elementwise"
441);
442
443// f64 elementwise wrappers — same wrapper macros, different
444// underlying kernels. The dispatch wrappers themselves are
445// dtype-agnostic (they just call the typed kernel); the
446// (op, dtype, backend) registration in `register_cpu_kernels`
447// is what selects the right one at lookup time.
448cpu_binary_wrapper!(
449    add_elementwise_f64_cpu_wrapper,
450    fuel_cpu_backend::byte_kernels::add_f64,
451    "add_elementwise"
452);
453cpu_binary_wrapper!(
454    sub_elementwise_f64_cpu_wrapper,
455    fuel_cpu_backend::byte_kernels::sub_f64,
456    "sub_elementwise"
457);
458cpu_binary_wrapper!(
459    mul_elementwise_f64_cpu_wrapper,
460    fuel_cpu_backend::byte_kernels::mul_f64,
461    "mul_elementwise"
462);
463cpu_binary_wrapper!(
464    div_elementwise_f64_cpu_wrapper,
465    fuel_cpu_backend::byte_kernels::div_f64,
466    "div_elementwise"
467);
468
469cpu_unary_wrapper!(
470    relu_elementwise_f64_cpu_wrapper,
471    fuel_cpu_backend::byte_kernels::relu_f64,
472    "relu_elementwise"
473);
474cpu_unary_wrapper!(
475    neg_elementwise_f64_cpu_wrapper,
476    fuel_cpu_backend::byte_kernels::neg_f64,
477    "neg_elementwise"
478);
479cpu_unary_wrapper!(
480    sqr_elementwise_f64_cpu_wrapper,
481    fuel_cpu_backend::byte_kernels::sqr_f64,
482    "sqr_elementwise"
483);
484cpu_unary_wrapper!(
485    sqrt_elementwise_f64_cpu_wrapper,
486    fuel_cpu_backend::byte_kernels::sqrt_f64,
487    "sqrt_elementwise"
488);
489cpu_unary_wrapper!(
490    recip_elementwise_f64_cpu_wrapper,
491    fuel_cpu_backend::byte_kernels::recip_f64,
492    "recip_elementwise"
493);
494cpu_unary_wrapper!(
495    abs_elementwise_f64_cpu_wrapper,
496    fuel_cpu_backend::byte_kernels::abs_f64,
497    "abs_elementwise"
498);
499cpu_unary_wrapper!(
500    tanh_elementwise_f64_cpu_wrapper,
501    fuel_cpu_backend::byte_kernels::tanh_f64,
502    "tanh_elementwise"
503);
504cpu_unary_wrapper!(
505    exp_elementwise_f64_cpu_wrapper,
506    fuel_cpu_backend::byte_kernels::exp_f64,
507    "exp_elementwise"
508);
509cpu_unary_wrapper!(
510    log_elementwise_f64_cpu_wrapper,
511    fuel_cpu_backend::byte_kernels::log_f64,
512    "log_elementwise"
513);
514cpu_unary_wrapper!(
515    sin_elementwise_f64_cpu_wrapper,
516    fuel_cpu_backend::byte_kernels::sin_f64,
517    "sin_elementwise"
518);
519cpu_unary_wrapper!(
520    cos_elementwise_f64_cpu_wrapper,
521    fuel_cpu_backend::byte_kernels::cos_f64,
522    "cos_elementwise"
523);
524cpu_unary_wrapper!(
525    sigmoid_elementwise_f64_cpu_wrapper,
526    fuel_cpu_backend::byte_kernels::sigmoid_f64,
527    "sigmoid_elementwise"
528);
529cpu_unary_wrapper!(
530    silu_elementwise_f64_cpu_wrapper,
531    fuel_cpu_backend::byte_kernels::silu_f64,
532    "silu_elementwise"
533);
534cpu_unary_wrapper!(
535    gelu_elementwise_f64_cpu_wrapper,
536    fuel_cpu_backend::byte_kernels::gelu_f64,
537    "gelu_elementwise"
538);
539cpu_unary_wrapper!(
540    step_elementwise_f64_cpu_wrapper,
541    fuel_cpu_backend::byte_kernels::step_f64,
542    "step_elementwise"
543);
544
545cpu_binary_wrapper!(
546    maximum_elementwise_f32_cpu_wrapper,
547    fuel_cpu_backend::byte_kernels::maximum_f32,
548    "maximum_elementwise"
549);
550cpu_binary_wrapper!(
551    minimum_elementwise_f32_cpu_wrapper,
552    fuel_cpu_backend::byte_kernels::minimum_f32,
553    "minimum_elementwise"
554);
555cpu_binary_wrapper!(
556    maximum_elementwise_f64_cpu_wrapper,
557    fuel_cpu_backend::byte_kernels::maximum_f64,
558    "maximum_elementwise"
559);
560cpu_binary_wrapper!(
561    minimum_elementwise_f64_cpu_wrapper,
562    fuel_cpu_backend::byte_kernels::minimum_f64,
563    "minimum_elementwise"
564);
565
566// bf16 elementwise wrappers (via-f32 round-trip kernels).
567cpu_binary_wrapper!(
568    add_elementwise_bf16_cpu_wrapper,
569    fuel_cpu_backend::byte_kernels::add_bf16,
570    "add_elementwise"
571);
572cpu_binary_wrapper!(
573    sub_elementwise_bf16_cpu_wrapper,
574    fuel_cpu_backend::byte_kernels::sub_bf16,
575    "sub_elementwise"
576);
577cpu_binary_wrapper!(
578    mul_elementwise_bf16_cpu_wrapper,
579    fuel_cpu_backend::byte_kernels::mul_bf16,
580    "mul_elementwise"
581);
582cpu_binary_wrapper!(
583    div_elementwise_bf16_cpu_wrapper,
584    fuel_cpu_backend::byte_kernels::div_bf16,
585    "div_elementwise"
586);
587cpu_binary_wrapper!(
588    maximum_elementwise_bf16_cpu_wrapper,
589    fuel_cpu_backend::byte_kernels::maximum_bf16,
590    "maximum_elementwise"
591);
592cpu_binary_wrapper!(
593    minimum_elementwise_bf16_cpu_wrapper,
594    fuel_cpu_backend::byte_kernels::minimum_bf16,
595    "minimum_elementwise"
596);
597
598cpu_unary_wrapper!(
599    relu_elementwise_bf16_cpu_wrapper,
600    fuel_cpu_backend::byte_kernels::relu_bf16,
601    "relu_elementwise"
602);
603cpu_unary_wrapper!(
604    neg_elementwise_bf16_cpu_wrapper,
605    fuel_cpu_backend::byte_kernels::neg_bf16,
606    "neg_elementwise"
607);
608cpu_unary_wrapper!(
609    sqr_elementwise_bf16_cpu_wrapper,
610    fuel_cpu_backend::byte_kernels::sqr_bf16,
611    "sqr_elementwise"
612);
613cpu_unary_wrapper!(
614    sqrt_elementwise_bf16_cpu_wrapper,
615    fuel_cpu_backend::byte_kernels::sqrt_bf16,
616    "sqrt_elementwise"
617);
618cpu_unary_wrapper!(
619    recip_elementwise_bf16_cpu_wrapper,
620    fuel_cpu_backend::byte_kernels::recip_bf16,
621    "recip_elementwise"
622);
623cpu_unary_wrapper!(
624    abs_elementwise_bf16_cpu_wrapper,
625    fuel_cpu_backend::byte_kernels::abs_bf16,
626    "abs_elementwise"
627);
628cpu_unary_wrapper!(
629    tanh_elementwise_bf16_cpu_wrapper,
630    fuel_cpu_backend::byte_kernels::tanh_bf16,
631    "tanh_elementwise"
632);
633cpu_unary_wrapper!(
634    exp_elementwise_bf16_cpu_wrapper,
635    fuel_cpu_backend::byte_kernels::exp_bf16,
636    "exp_elementwise"
637);
638cpu_unary_wrapper!(
639    log_elementwise_bf16_cpu_wrapper,
640    fuel_cpu_backend::byte_kernels::log_bf16,
641    "log_elementwise"
642);
643cpu_unary_wrapper!(
644    sin_elementwise_bf16_cpu_wrapper,
645    fuel_cpu_backend::byte_kernels::sin_bf16,
646    "sin_elementwise"
647);
648cpu_unary_wrapper!(
649    cos_elementwise_bf16_cpu_wrapper,
650    fuel_cpu_backend::byte_kernels::cos_bf16,
651    "cos_elementwise"
652);
653cpu_unary_wrapper!(
654    sigmoid_elementwise_bf16_cpu_wrapper,
655    fuel_cpu_backend::byte_kernels::sigmoid_bf16,
656    "sigmoid_elementwise"
657);
658cpu_unary_wrapper!(
659    silu_elementwise_bf16_cpu_wrapper,
660    fuel_cpu_backend::byte_kernels::silu_bf16,
661    "silu_elementwise"
662);
663cpu_unary_wrapper!(
664    gelu_elementwise_bf16_cpu_wrapper,
665    fuel_cpu_backend::byte_kernels::gelu_bf16,
666    "gelu_elementwise"
667);
668cpu_unary_wrapper!(
669    step_elementwise_bf16_cpu_wrapper,
670    fuel_cpu_backend::byte_kernels::step_bf16,
671    "step_elementwise"
672);
673
674// f16 elementwise wrappers — direct mirrors of bf16.
675cpu_binary_wrapper!(
676    add_elementwise_f16_cpu_wrapper,
677    fuel_cpu_backend::byte_kernels::add_f16,
678    "add_elementwise"
679);
680cpu_binary_wrapper!(
681    sub_elementwise_f16_cpu_wrapper,
682    fuel_cpu_backend::byte_kernels::sub_f16,
683    "sub_elementwise"
684);
685cpu_binary_wrapper!(
686    mul_elementwise_f16_cpu_wrapper,
687    fuel_cpu_backend::byte_kernels::mul_f16,
688    "mul_elementwise"
689);
690cpu_binary_wrapper!(
691    div_elementwise_f16_cpu_wrapper,
692    fuel_cpu_backend::byte_kernels::div_f16,
693    "div_elementwise"
694);
695cpu_binary_wrapper!(
696    maximum_elementwise_f16_cpu_wrapper,
697    fuel_cpu_backend::byte_kernels::maximum_f16,
698    "maximum_elementwise"
699);
700cpu_binary_wrapper!(
701    minimum_elementwise_f16_cpu_wrapper,
702    fuel_cpu_backend::byte_kernels::minimum_f16,
703    "minimum_elementwise"
704);
705
706cpu_unary_wrapper!(
707    relu_elementwise_f16_cpu_wrapper,
708    fuel_cpu_backend::byte_kernels::relu_f16,
709    "relu_elementwise"
710);
711cpu_unary_wrapper!(
712    neg_elementwise_f16_cpu_wrapper,
713    fuel_cpu_backend::byte_kernels::neg_f16,
714    "neg_elementwise"
715);
716cpu_unary_wrapper!(
717    sqr_elementwise_f16_cpu_wrapper,
718    fuel_cpu_backend::byte_kernels::sqr_f16,
719    "sqr_elementwise"
720);
721cpu_unary_wrapper!(
722    sqrt_elementwise_f16_cpu_wrapper,
723    fuel_cpu_backend::byte_kernels::sqrt_f16,
724    "sqrt_elementwise"
725);
726cpu_unary_wrapper!(
727    recip_elementwise_f16_cpu_wrapper,
728    fuel_cpu_backend::byte_kernels::recip_f16,
729    "recip_elementwise"
730);
731cpu_unary_wrapper!(
732    abs_elementwise_f16_cpu_wrapper,
733    fuel_cpu_backend::byte_kernels::abs_f16,
734    "abs_elementwise"
735);
736cpu_unary_wrapper!(
737    tanh_elementwise_f16_cpu_wrapper,
738    fuel_cpu_backend::byte_kernels::tanh_f16,
739    "tanh_elementwise"
740);
741cpu_unary_wrapper!(
742    exp_elementwise_f16_cpu_wrapper,
743    fuel_cpu_backend::byte_kernels::exp_f16,
744    "exp_elementwise"
745);
746cpu_unary_wrapper!(
747    log_elementwise_f16_cpu_wrapper,
748    fuel_cpu_backend::byte_kernels::log_f16,
749    "log_elementwise"
750);
751cpu_unary_wrapper!(
752    sin_elementwise_f16_cpu_wrapper,
753    fuel_cpu_backend::byte_kernels::sin_f16,
754    "sin_elementwise"
755);
756cpu_unary_wrapper!(
757    cos_elementwise_f16_cpu_wrapper,
758    fuel_cpu_backend::byte_kernels::cos_f16,
759    "cos_elementwise"
760);
761cpu_unary_wrapper!(
762    sigmoid_elementwise_f16_cpu_wrapper,
763    fuel_cpu_backend::byte_kernels::sigmoid_f16,
764    "sigmoid_elementwise"
765);
766cpu_unary_wrapper!(
767    silu_elementwise_f16_cpu_wrapper,
768    fuel_cpu_backend::byte_kernels::silu_f16,
769    "silu_elementwise"
770);
771cpu_unary_wrapper!(
772    gelu_elementwise_f16_cpu_wrapper,
773    fuel_cpu_backend::byte_kernels::gelu_f16,
774    "gelu_elementwise"
775);
776cpu_unary_wrapper!(
777    step_elementwise_f16_cpu_wrapper,
778    fuel_cpu_backend::byte_kernels::step_f16,
779    "step_elementwise"
780);
781
782// Comparison family — typed input, U8 output. The wrapper signature
783// is identical to a regular binary wrapper (3 byte buffers); only the
784// kernel internally casts inputs to `&[T]` and output to `&mut [u8]`.
785// Binding-table key is `[T, T, U8]` so the executor allocates a U8-
786// sized output buffer (1 byte per element) instead of T-sized.
787cpu_binary_wrapper!(
788    eq_elementwise_f32_cpu_wrapper,
789    fuel_cpu_backend::byte_kernels::eq_f32_u8,
790    "eq_elementwise"
791);
792cpu_binary_wrapper!(
793    eq_elementwise_f64_cpu_wrapper,
794    fuel_cpu_backend::byte_kernels::eq_f64_u8,
795    "eq_elementwise"
796);
797cpu_binary_wrapper!(
798    eq_elementwise_bf16_cpu_wrapper,
799    fuel_cpu_backend::byte_kernels::eq_bf16_u8,
800    "eq_elementwise"
801);
802cpu_binary_wrapper!(
803    eq_elementwise_f16_cpu_wrapper,
804    fuel_cpu_backend::byte_kernels::eq_f16_u8,
805    "eq_elementwise"
806);
807
808cpu_binary_wrapper!(
809    ne_elementwise_f32_cpu_wrapper,
810    fuel_cpu_backend::byte_kernels::ne_f32_u8,
811    "ne_elementwise"
812);
813cpu_binary_wrapper!(
814    ne_elementwise_f64_cpu_wrapper,
815    fuel_cpu_backend::byte_kernels::ne_f64_u8,
816    "ne_elementwise"
817);
818cpu_binary_wrapper!(
819    ne_elementwise_bf16_cpu_wrapper,
820    fuel_cpu_backend::byte_kernels::ne_bf16_u8,
821    "ne_elementwise"
822);
823cpu_binary_wrapper!(
824    ne_elementwise_f16_cpu_wrapper,
825    fuel_cpu_backend::byte_kernels::ne_f16_u8,
826    "ne_elementwise"
827);
828
829cpu_binary_wrapper!(
830    lt_elementwise_f32_cpu_wrapper,
831    fuel_cpu_backend::byte_kernels::lt_f32_u8,
832    "lt_elementwise"
833);
834cpu_binary_wrapper!(
835    lt_elementwise_f64_cpu_wrapper,
836    fuel_cpu_backend::byte_kernels::lt_f64_u8,
837    "lt_elementwise"
838);
839cpu_binary_wrapper!(
840    lt_elementwise_bf16_cpu_wrapper,
841    fuel_cpu_backend::byte_kernels::lt_bf16_u8,
842    "lt_elementwise"
843);
844cpu_binary_wrapper!(
845    lt_elementwise_f16_cpu_wrapper,
846    fuel_cpu_backend::byte_kernels::lt_f16_u8,
847    "lt_elementwise"
848);
849
850cpu_binary_wrapper!(
851    le_elementwise_f32_cpu_wrapper,
852    fuel_cpu_backend::byte_kernels::le_f32_u8,
853    "le_elementwise"
854);
855cpu_binary_wrapper!(
856    le_elementwise_f64_cpu_wrapper,
857    fuel_cpu_backend::byte_kernels::le_f64_u8,
858    "le_elementwise"
859);
860cpu_binary_wrapper!(
861    le_elementwise_bf16_cpu_wrapper,
862    fuel_cpu_backend::byte_kernels::le_bf16_u8,
863    "le_elementwise"
864);
865cpu_binary_wrapper!(
866    le_elementwise_f16_cpu_wrapper,
867    fuel_cpu_backend::byte_kernels::le_f16_u8,
868    "le_elementwise"
869);
870
871cpu_binary_wrapper!(
872    gt_elementwise_f32_cpu_wrapper,
873    fuel_cpu_backend::byte_kernels::gt_f32_u8,
874    "gt_elementwise"
875);
876cpu_binary_wrapper!(
877    gt_elementwise_f64_cpu_wrapper,
878    fuel_cpu_backend::byte_kernels::gt_f64_u8,
879    "gt_elementwise"
880);
881cpu_binary_wrapper!(
882    gt_elementwise_bf16_cpu_wrapper,
883    fuel_cpu_backend::byte_kernels::gt_bf16_u8,
884    "gt_elementwise"
885);
886cpu_binary_wrapper!(
887    gt_elementwise_f16_cpu_wrapper,
888    fuel_cpu_backend::byte_kernels::gt_f16_u8,
889    "gt_elementwise"
890);
891
892cpu_binary_wrapper!(
893    ge_elementwise_f32_cpu_wrapper,
894    fuel_cpu_backend::byte_kernels::ge_f32_u8,
895    "ge_elementwise"
896);
897cpu_binary_wrapper!(
898    ge_elementwise_f64_cpu_wrapper,
899    fuel_cpu_backend::byte_kernels::ge_f64_u8,
900    "ge_elementwise"
901);
902cpu_binary_wrapper!(
903    ge_elementwise_bf16_cpu_wrapper,
904    fuel_cpu_backend::byte_kernels::ge_bf16_u8,
905    "ge_elementwise"
906);
907cpu_binary_wrapper!(
908    ge_elementwise_f16_cpu_wrapper,
909    fuel_cpu_backend::byte_kernels::ge_f16_u8,
910    "ge_elementwise"
911);
912
913/// Build a `(3 inputs, 1 output)` CPU dispatch wrapper for the
914/// ternary [`Op::Where`] family. Inputs are `(cond, a, b)` byte
915/// buffers; output is the typed `T` result. The wrapper signature
916/// matches [`KernelRef`]; the kernel itself does the typed casts
917/// internally.
918macro_rules! cpu_where_wrapper {
919    ($wrapper:ident, $kernel:path, $op_name:literal) => {
920        // pub(crate) so the FKC link table (fkc::cpu_link) can name the real
921        // production wrapper as `crate::dispatch::where_<dt>_cpu_wrapper`.
922        pub(crate) fn $wrapper(
923            inputs: &[Arc<RwLock<Storage>>],
924            outputs: &mut [Arc<RwLock<Storage>>],
925            _layouts: &[Layout],
926            _params: &OpParams,
927        ) -> Result<()> {
928            if inputs.len() != 3 {
929                return Err(Error::Msg(format!(
930                    "{} wrapper expects 3 inputs (cond, a, b), got {}",
931                    $op_name,
932                    inputs.len(),
933                ))
934                .bt());
935            }
936            if outputs.len() != 1 {
937                return Err(Error::Msg(format!(
938                    "{} wrapper expects 1 output, got {}",
939                    $op_name,
940                    outputs.len(),
941                ))
942                .bt());
943            }
944            let cond_guard = read_storage(&inputs[0])?;
945            // GAP-168(c): the cond mask is Bool. This is the RUNTIME arm of the
946            // same rule the graph builder and the Tensor wrapper enforce —
947            // three layers, and each had to be flipped separately. Bool and U8
948            // are byte-identical, so this check is the only thing keeping a U8
949            // buffer from being consumed here as if it were a mask.
950            if cond_guard.dtype != DType::Bool {
951                return Err(Error::Msg(format!(
952                    "{}: cond must be Bool, got {:?} (GAP-168(c))",
953                    $op_name, cond_guard.dtype,
954                ))
955                .bt());
956            }
957            let a_guard = read_storage(&inputs[1])?;
958            let b_guard = read_storage(&inputs[2])?;
959            let mut out_guard = write_storage(&outputs[0])?;
960            let cond_cpu = cpu_input(&cond_guard)?;
961            let a_cpu = cpu_input(&a_guard)?;
962            let b_cpu = cpu_input(&b_guard)?;
963            let out_cpu = cpu_output(&mut out_guard)?;
964            $kernel(cond_cpu, a_cpu, b_cpu, out_cpu)
965        }
966    };
967}
968
969cpu_where_wrapper!(
970    where_f32_cpu_wrapper,
971    fuel_cpu_backend::byte_kernels::where_f32,
972    "where"
973);
974cpu_where_wrapper!(
975    where_f64_cpu_wrapper,
976    fuel_cpu_backend::byte_kernels::where_f64,
977    "where"
978);
979cpu_where_wrapper!(
980    where_bf16_cpu_wrapper,
981    fuel_cpu_backend::byte_kernels::where_bf16,
982    "where"
983);
984cpu_where_wrapper!(
985    where_f16_cpu_wrapper,
986    fuel_cpu_backend::byte_kernels::where_f16,
987    "where"
988);
989
990// Rounding family (Floor / Ceil / Round) — same-dtype unary; standard
991// `cpu_unary_wrapper!`.
992cpu_unary_wrapper!(
993    floor_elementwise_f32_cpu_wrapper,
994    fuel_cpu_backend::byte_kernels::floor_f32,
995    "floor_elementwise"
996);
997cpu_unary_wrapper!(
998    floor_elementwise_f64_cpu_wrapper,
999    fuel_cpu_backend::byte_kernels::floor_f64,
1000    "floor_elementwise"
1001);
1002cpu_unary_wrapper!(
1003    floor_elementwise_bf16_cpu_wrapper,
1004    fuel_cpu_backend::byte_kernels::floor_bf16,
1005    "floor_elementwise"
1006);
1007cpu_unary_wrapper!(
1008    floor_elementwise_f16_cpu_wrapper,
1009    fuel_cpu_backend::byte_kernels::floor_f16,
1010    "floor_elementwise"
1011);
1012
1013cpu_unary_wrapper!(
1014    ceil_elementwise_f32_cpu_wrapper,
1015    fuel_cpu_backend::byte_kernels::ceil_f32,
1016    "ceil_elementwise"
1017);
1018cpu_unary_wrapper!(
1019    ceil_elementwise_f64_cpu_wrapper,
1020    fuel_cpu_backend::byte_kernels::ceil_f64,
1021    "ceil_elementwise"
1022);
1023cpu_unary_wrapper!(
1024    ceil_elementwise_bf16_cpu_wrapper,
1025    fuel_cpu_backend::byte_kernels::ceil_bf16,
1026    "ceil_elementwise"
1027);
1028cpu_unary_wrapper!(
1029    ceil_elementwise_f16_cpu_wrapper,
1030    fuel_cpu_backend::byte_kernels::ceil_f16,
1031    "ceil_elementwise"
1032);
1033
1034cpu_unary_wrapper!(
1035    round_elementwise_f32_cpu_wrapper,
1036    fuel_cpu_backend::byte_kernels::round_f32,
1037    "round_elementwise"
1038);
1039cpu_unary_wrapper!(
1040    round_elementwise_f64_cpu_wrapper,
1041    fuel_cpu_backend::byte_kernels::round_f64,
1042    "round_elementwise"
1043);
1044cpu_unary_wrapper!(
1045    round_elementwise_bf16_cpu_wrapper,
1046    fuel_cpu_backend::byte_kernels::round_bf16,
1047    "round_elementwise"
1048);
1049cpu_unary_wrapper!(
1050    round_elementwise_f16_cpu_wrapper,
1051    fuel_cpu_backend::byte_kernels::round_f16,
1052    "round_elementwise"
1053);
1054
1055cpu_unary_wrapper!(
1056    sign_elementwise_f32_cpu_wrapper,
1057    fuel_cpu_backend::byte_kernels::sign_f32,
1058    "sign_elementwise"
1059);
1060cpu_unary_wrapper!(
1061    sign_elementwise_f64_cpu_wrapper,
1062    fuel_cpu_backend::byte_kernels::sign_f64,
1063    "sign_elementwise"
1064);
1065cpu_unary_wrapper!(
1066    sign_elementwise_bf16_cpu_wrapper,
1067    fuel_cpu_backend::byte_kernels::sign_bf16,
1068    "sign_elementwise"
1069);
1070cpu_unary_wrapper!(
1071    sign_elementwise_f16_cpu_wrapper,
1072    fuel_cpu_backend::byte_kernels::sign_f16,
1073    "sign_elementwise"
1074);
1075
1076cpu_unary_wrapper!(
1077    erf_elementwise_f32_cpu_wrapper,
1078    fuel_cpu_backend::byte_kernels::erf_f32,
1079    "erf_elementwise"
1080);
1081cpu_unary_wrapper!(
1082    erf_elementwise_f64_cpu_wrapper,
1083    fuel_cpu_backend::byte_kernels::erf_f64,
1084    "erf_elementwise"
1085);
1086cpu_unary_wrapper!(
1087    erf_elementwise_bf16_cpu_wrapper,
1088    fuel_cpu_backend::byte_kernels::erf_bf16,
1089    "erf_elementwise"
1090);
1091cpu_unary_wrapper!(
1092    erf_elementwise_f16_cpu_wrapper,
1093    fuel_cpu_backend::byte_kernels::erf_f16,
1094    "erf_elementwise"
1095);
1096
1097cpu_unary_wrapper!(
1098    gelu_erf_elementwise_f32_cpu_wrapper,
1099    fuel_cpu_backend::byte_kernels::gelu_erf_f32,
1100    "gelu_erf_elementwise"
1101);
1102cpu_unary_wrapper!(
1103    gelu_erf_elementwise_f64_cpu_wrapper,
1104    fuel_cpu_backend::byte_kernels::gelu_erf_f64,
1105    "gelu_erf_elementwise"
1106);
1107cpu_unary_wrapper!(
1108    gelu_erf_elementwise_bf16_cpu_wrapper,
1109    fuel_cpu_backend::byte_kernels::gelu_erf_bf16,
1110    "gelu_erf_elementwise"
1111);
1112cpu_unary_wrapper!(
1113    gelu_erf_elementwise_f16_cpu_wrapper,
1114    fuel_cpu_backend::byte_kernels::gelu_erf_f16,
1115    "gelu_erf_elementwise"
1116);
1117
1118cpu_binary_wrapper!(
1119    pow_elementwise_f32_cpu_wrapper,
1120    fuel_cpu_backend::byte_kernels::pow_f32,
1121    "pow_elementwise"
1122);
1123cpu_binary_wrapper!(
1124    pow_elementwise_f64_cpu_wrapper,
1125    fuel_cpu_backend::byte_kernels::pow_f64,
1126    "pow_elementwise"
1127);
1128cpu_binary_wrapper!(
1129    pow_elementwise_bf16_cpu_wrapper,
1130    fuel_cpu_backend::byte_kernels::pow_bf16,
1131    "pow_elementwise"
1132);
1133cpu_binary_wrapper!(
1134    pow_elementwise_f16_cpu_wrapper,
1135    fuel_cpu_backend::byte_kernels::pow_f16,
1136    "pow_elementwise"
1137);
1138
1139cpu_unary_wrapper!(
1140    rsqrt_elementwise_f32_cpu_wrapper,
1141    fuel_cpu_backend::byte_kernels::rsqrt_f32,
1142    "rsqrt_elementwise"
1143);
1144cpu_unary_wrapper!(
1145    rsqrt_elementwise_f64_cpu_wrapper,
1146    fuel_cpu_backend::byte_kernels::rsqrt_f64,
1147    "rsqrt_elementwise"
1148);
1149cpu_unary_wrapper!(
1150    rsqrt_elementwise_bf16_cpu_wrapper,
1151    fuel_cpu_backend::byte_kernels::rsqrt_bf16,
1152    "rsqrt_elementwise"
1153);
1154cpu_unary_wrapper!(
1155    rsqrt_elementwise_f16_cpu_wrapper,
1156    fuel_cpu_backend::byte_kernels::rsqrt_f16,
1157    "rsqrt_elementwise"
1158);
1159
1160cpu_binary_wrapper!(
1161    rem_elementwise_f32_cpu_wrapper,
1162    fuel_cpu_backend::byte_kernels::rem_f32,
1163    "rem_elementwise"
1164);
1165cpu_binary_wrapper!(
1166    rem_elementwise_f64_cpu_wrapper,
1167    fuel_cpu_backend::byte_kernels::rem_f64,
1168    "rem_elementwise"
1169);
1170cpu_binary_wrapper!(
1171    rem_elementwise_bf16_cpu_wrapper,
1172    fuel_cpu_backend::byte_kernels::rem_bf16,
1173    "rem_elementwise"
1174);
1175cpu_binary_wrapper!(
1176    rem_elementwise_f16_cpu_wrapper,
1177    fuel_cpu_backend::byte_kernels::rem_f16,
1178    "rem_elementwise"
1179);
1180
1181/// Dispatch wrapper for `(Flip, *, Cpu)`. Dtype-agnostic at the byte
1182/// level — `dtype_size` flows from the output Storage. Geometry
1183/// (`outer_count`, `dim_size`, `inner_count`) is precomputed by
1184/// `op_to_op_params` from the input shape + flip dim.
1185pub(crate) fn flip_cpu_wrapper(
1186    inputs: &[Arc<RwLock<Storage>>],
1187    outputs: &mut [Arc<RwLock<Storage>>],
1188    _layouts: &[Layout],
1189    params: &OpParams,
1190) -> Result<()> {
1191    if inputs.len() != 1 || outputs.len() != 1 {
1192        return Err(Error::Msg(format!(
1193            "flip wrapper expects 1 input + 1 output, got {} + {}",
1194            inputs.len(),
1195            outputs.len(),
1196        ))
1197        .bt());
1198    }
1199    let (outer, dim_size, inner) = match params {
1200        OpParams::Flip {
1201            outer_count,
1202            dim_size,
1203            inner_count,
1204            ..
1205        } => (*outer_count, *dim_size, *inner_count),
1206        other => {
1207            return Err(Error::Msg(format!(
1208                "flip wrapper expects OpParams::Flip, got {other:?}",
1209            ))
1210            .bt());
1211        }
1212    };
1213    let in_guard = read_storage(&inputs[0])?;
1214    let mut out_guard = write_storage(&outputs[0])?;
1215    let dtype_size = out_guard.dtype.size_in_bytes();
1216    let in_cpu = cpu_input(&in_guard)?;
1217    let out_cpu = cpu_output(&mut out_guard)?;
1218    fuel_cpu_backend::byte_kernels::flip_cpu(in_cpu, out_cpu, outer, dim_size, inner, dtype_size)
1219}
1220
1221/// Build a `(1 input, 1 output)` CPU dispatch wrapper for the
1222/// per-dtype CumSum kernels. The kernel name is bound at macro
1223/// invocation; geometry comes from `OpParams::CumSum`.
1224macro_rules! cpu_cumsum_wrapper {
1225    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1226        pub(crate) fn $wrapper(
1227            inputs: &[Arc<RwLock<Storage>>],
1228            outputs: &mut [Arc<RwLock<Storage>>],
1229            _layouts: &[Layout],
1230            params: &OpParams,
1231        ) -> Result<()> {
1232            if inputs.len() != 1 || outputs.len() != 1 {
1233                return Err(Error::Msg(format!(
1234                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1235                    $op_name,
1236                    inputs.len(),
1237                    outputs.len(),
1238                ))
1239                .bt());
1240            }
1241            let (outer, dim_size, inner) = match params {
1242                OpParams::CumSum {
1243                    outer_count,
1244                    dim_size,
1245                    inner_count,
1246                    ..
1247                } => (*outer_count, *dim_size, *inner_count),
1248                other => {
1249                    return Err(Error::Msg(format!(
1250                        "{} wrapper expects OpParams::CumSum, got {other:?}",
1251                        $op_name,
1252                    ))
1253                    .bt())
1254                }
1255            };
1256            let in_guard = read_storage(&inputs[0])?;
1257            let mut out_guard = write_storage(&outputs[0])?;
1258            let in_cpu = cpu_input(&in_guard)?;
1259            let out_cpu = cpu_output(&mut out_guard)?;
1260            $kernel(in_cpu, out_cpu, outer, dim_size, inner)
1261        }
1262    };
1263}
1264
1265cpu_cumsum_wrapper!(
1266    cumsum_f32_cpu_wrapper,
1267    fuel_cpu_backend::byte_kernels::cumsum_f32,
1268    "cumsum_f32"
1269);
1270cpu_cumsum_wrapper!(
1271    cumsum_f64_cpu_wrapper,
1272    fuel_cpu_backend::byte_kernels::cumsum_f64,
1273    "cumsum_f64"
1274);
1275cpu_cumsum_wrapper!(
1276    cumsum_bf16_cpu_wrapper,
1277    fuel_cpu_backend::byte_kernels::cumsum_bf16,
1278    "cumsum_bf16"
1279);
1280cpu_cumsum_wrapper!(
1281    cumsum_f16_cpu_wrapper,
1282    fuel_cpu_backend::byte_kernels::cumsum_f16,
1283    "cumsum_f16"
1284);
1285
1286/// Triu / Tril share one byte-level kernel; the wrapper picks
1287/// keep_upper from the OpKind at dispatch time. Dtype-agnostic.
1288fn triu_cpu_wrapper(
1289    inputs: &[Arc<RwLock<Storage>>],
1290    outputs: &mut [Arc<RwLock<Storage>>],
1291    _layouts: &[Layout],
1292    params: &OpParams,
1293) -> Result<()> {
1294    triangular_wrapper_inner(
1295        inputs,
1296        outputs,
1297        params,
1298        /*keep_upper*/ true,
1299        "triu_cpu_wrapper",
1300    )
1301}
1302
1303fn tril_cpu_wrapper(
1304    inputs: &[Arc<RwLock<Storage>>],
1305    outputs: &mut [Arc<RwLock<Storage>>],
1306    _layouts: &[Layout],
1307    params: &OpParams,
1308) -> Result<()> {
1309    triangular_wrapper_inner(
1310        inputs,
1311        outputs,
1312        params,
1313        /*keep_upper*/ false,
1314        "tril_cpu_wrapper",
1315    )
1316}
1317
1318fn triangular_wrapper_inner(
1319    inputs: &[Arc<RwLock<Storage>>],
1320    outputs: &mut [Arc<RwLock<Storage>>],
1321    params: &OpParams,
1322    keep_upper: bool,
1323    op_name: &str,
1324) -> Result<()> {
1325    if inputs.len() != 1 || outputs.len() != 1 {
1326        return Err(Error::Msg(format!(
1327            "{op_name}: expects 1 input + 1 output, got {} + {}",
1328            inputs.len(),
1329            outputs.len(),
1330        ))
1331        .bt());
1332    }
1333    let (batch, rows, cols, diag) = match params {
1334        OpParams::Triangular {
1335            batch_count,
1336            rows,
1337            cols,
1338            diagonal,
1339        } => (*batch_count, *rows, *cols, *diagonal),
1340        other => {
1341            return Err(Error::Msg(format!(
1342                "{op_name}: expects OpParams::Triangular, got {other:?}",
1343            ))
1344            .bt());
1345        }
1346    };
1347    let in_guard = read_storage(&inputs[0])?;
1348    let mut out_guard = write_storage(&outputs[0])?;
1349    let dtype_size = out_guard.dtype.size_in_bytes();
1350    let in_cpu = cpu_input(&in_guard)?;
1351    let out_cpu = cpu_output(&mut out_guard)?;
1352    fuel_cpu_backend::byte_kernels::triangular_cpu(
1353        in_cpu, out_cpu, batch, rows, cols, diag, keep_upper, dtype_size,
1354    )
1355}
1356
1357/// Per-dtype log-softmax wrapper. Geometry comes from
1358/// `OpParams::LogSoftmaxLastDim`.
1359macro_rules! cpu_log_softmax_wrapper {
1360    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1361        pub(crate) fn $wrapper(
1362            inputs: &[Arc<RwLock<Storage>>],
1363            outputs: &mut [Arc<RwLock<Storage>>],
1364            _layouts: &[Layout],
1365            params: &OpParams,
1366        ) -> Result<()> {
1367            if inputs.len() != 1 || outputs.len() != 1 {
1368                return Err(Error::Msg(format!(
1369                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1370                    $op_name,
1371                    inputs.len(),
1372                    outputs.len(),
1373                ))
1374                .bt());
1375            }
1376            let (outer, last_dim) = match params {
1377                OpParams::LogSoftmaxLastDim {
1378                    outer_count,
1379                    last_dim,
1380                } => (*outer_count, *last_dim),
1381                other => {
1382                    return Err(Error::Msg(format!(
1383                        "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1384                        $op_name,
1385                    ))
1386                    .bt());
1387                }
1388            };
1389            let in_guard = read_storage(&inputs[0])?;
1390            let mut out_guard = write_storage(&outputs[0])?;
1391            let in_cpu = cpu_input(&in_guard)?;
1392            let out_cpu = cpu_output(&mut out_guard)?;
1393            $kernel(in_cpu, out_cpu, outer, last_dim)
1394        }
1395    };
1396}
1397
1398cpu_log_softmax_wrapper!(
1399    log_softmax_f32_cpu_wrapper,
1400    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f32,
1401    "log_softmax_f32"
1402);
1403cpu_log_softmax_wrapper!(
1404    log_softmax_f64_cpu_wrapper,
1405    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f64,
1406    "log_softmax_f64"
1407);
1408cpu_log_softmax_wrapper!(
1409    log_softmax_bf16_cpu_wrapper,
1410    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_bf16,
1411    "log_softmax_bf16"
1412);
1413cpu_log_softmax_wrapper!(
1414    log_softmax_f16_cpu_wrapper,
1415    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_f16,
1416    "log_softmax_f16"
1417);
1418
1419/// Per-dtype log-softmax-backward wrapper. Two inputs (y, g); same
1420/// geometry as forward.
1421macro_rules! cpu_log_softmax_backward_wrapper {
1422    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1423        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1424        // real production wrapper and the importer can bind it FROM the contract.
1425        pub(crate) fn $wrapper(
1426            inputs: &[Arc<RwLock<Storage>>],
1427            outputs: &mut [Arc<RwLock<Storage>>],
1428            _layouts: &[Layout],
1429            params: &OpParams,
1430        ) -> Result<()> {
1431            if inputs.len() != 2 || outputs.len() != 1 {
1432                return Err(Error::Msg(format!(
1433                    "{} wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1434                    $op_name,
1435                    inputs.len(),
1436                    outputs.len(),
1437                ))
1438                .bt());
1439            }
1440            let (outer, last_dim) = match params {
1441                OpParams::LogSoftmaxLastDim {
1442                    outer_count,
1443                    last_dim,
1444                } => (*outer_count, *last_dim),
1445                other => {
1446                    return Err(Error::Msg(format!(
1447                        "{} wrapper expects OpParams::LogSoftmaxLastDim, got {other:?}",
1448                        $op_name,
1449                    ))
1450                    .bt());
1451                }
1452            };
1453            let y_guard = read_storage(&inputs[0])?;
1454            let g_guard = read_storage(&inputs[1])?;
1455            let mut out_guard = write_storage(&outputs[0])?;
1456            let y_cpu = cpu_input(&y_guard)?;
1457            let g_cpu = cpu_input(&g_guard)?;
1458            let out_cpu = cpu_output(&mut out_guard)?;
1459            $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1460        }
1461    };
1462}
1463
1464cpu_log_softmax_backward_wrapper!(
1465    log_softmax_backward_f32_cpu_wrapper,
1466    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f32,
1467    "log_softmax_backward_f32"
1468);
1469cpu_log_softmax_backward_wrapper!(
1470    log_softmax_backward_f64_cpu_wrapper,
1471    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f64,
1472    "log_softmax_backward_f64"
1473);
1474cpu_log_softmax_backward_wrapper!(
1475    log_softmax_backward_bf16_cpu_wrapper,
1476    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_bf16,
1477    "log_softmax_backward_bf16"
1478);
1479cpu_log_softmax_backward_wrapper!(
1480    log_softmax_backward_f16_cpu_wrapper,
1481    fuel_cpu_backend::byte_kernels::log_softmax_last_dim_backward_f16,
1482    "log_softmax_backward_f16"
1483);
1484
1485/// Softmax-last-dim backward — 2 inputs (y, g) + 1 output, reuses
1486/// `OpParams::SoftmaxLastDim` (same outer × last_dim shape contract
1487/// as the forward).
1488macro_rules! cpu_softmax_last_dim_backward_wrapper {
1489    ($wrapper:ident, $kernel:path) => {
1490        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1491        // real production wrapper and the importer can bind it FROM the contract.
1492        pub(crate) fn $wrapper(
1493            inputs: &[Arc<RwLock<Storage>>],
1494            outputs: &mut [Arc<RwLock<Storage>>],
1495            _layouts: &[Layout],
1496            params: &OpParams,
1497        ) -> Result<()> {
1498            if inputs.len() != 2 || outputs.len() != 1 {
1499                return Err(Error::Msg(format!(
1500                    "softmax_last_dim_backward wrapper expects 2 inputs (y, g) + 1 output, got {} + {}",
1501                    inputs.len(), outputs.len(),
1502                )).bt());
1503            }
1504            let (outer, last_dim) = match params {
1505                OpParams::SoftmaxLastDim { outer_count, last_dim } => (*outer_count, *last_dim),
1506                other => {
1507                    return Err(Error::Msg(format!(
1508                        "softmax_last_dim_backward wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
1509                    )).bt());
1510                }
1511            };
1512            let y_guard = read_storage(&inputs[0])?;
1513            let g_guard = read_storage(&inputs[1])?;
1514            let mut out_guard = write_storage(&outputs[0])?;
1515            let y_cpu = cpu_input(&y_guard)?;
1516            let g_cpu = cpu_input(&g_guard)?;
1517            let out_cpu = cpu_output(&mut out_guard)?;
1518            $kernel(y_cpu, g_cpu, out_cpu, outer, last_dim)
1519        }
1520    };
1521}
1522
1523cpu_softmax_last_dim_backward_wrapper!(
1524    softmax_last_dim_backward_f32_cpu_wrapper,
1525    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f32
1526);
1527cpu_softmax_last_dim_backward_wrapper!(
1528    softmax_last_dim_backward_f64_cpu_wrapper,
1529    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f64
1530);
1531cpu_softmax_last_dim_backward_wrapper!(
1532    softmax_last_dim_backward_bf16_cpu_wrapper,
1533    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_bf16
1534);
1535cpu_softmax_last_dim_backward_wrapper!(
1536    softmax_last_dim_backward_f16_cpu_wrapper,
1537    fuel_cpu_backend::byte_kernels::softmax_last_dim_backward_f16
1538);
1539
1540/// LayerNorm / RmsNorm backward share `OpParams::NormLastDim` (with
1541/// eps). Two inputs (x, g) + 1 output, same outer × last_dim shape.
1542macro_rules! cpu_norm_last_dim_backward_wrapper {
1543    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1544        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
1545        // real production wrapper and the importer can bind it FROM the contract.
1546        pub(crate) fn $wrapper(
1547            inputs: &[Arc<RwLock<Storage>>],
1548            outputs: &mut [Arc<RwLock<Storage>>],
1549            _layouts: &[Layout],
1550            params: &OpParams,
1551        ) -> Result<()> {
1552            if inputs.len() != 2 || outputs.len() != 1 {
1553                return Err(Error::Msg(format!(
1554                    "{} wrapper expects 2 inputs (x, g) + 1 output, got {} + {}",
1555                    $op_name,
1556                    inputs.len(),
1557                    outputs.len(),
1558                ))
1559                .bt());
1560            }
1561            let (outer, last_dim, eps) = match params {
1562                OpParams::NormLastDim {
1563                    outer_count,
1564                    last_dim,
1565                    eps,
1566                } => (*outer_count, *last_dim, *eps),
1567                other => {
1568                    return Err(Error::Msg(format!(
1569                        "{} wrapper expects OpParams::NormLastDim, got {other:?}",
1570                        $op_name,
1571                    ))
1572                    .bt());
1573                }
1574            };
1575            let x_guard = read_storage(&inputs[0])?;
1576            let g_guard = read_storage(&inputs[1])?;
1577            let mut out_guard = write_storage(&outputs[0])?;
1578            let x_cpu = cpu_input(&x_guard)?;
1579            let g_cpu = cpu_input(&g_guard)?;
1580            let out_cpu = cpu_output(&mut out_guard)?;
1581            $kernel(x_cpu, g_cpu, out_cpu, outer, last_dim, eps)
1582        }
1583    };
1584}
1585
1586cpu_norm_last_dim_backward_wrapper!(
1587    layer_norm_last_dim_backward_f32_cpu_wrapper,
1588    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f32,
1589    "layer_norm_backward_f32"
1590);
1591cpu_norm_last_dim_backward_wrapper!(
1592    layer_norm_last_dim_backward_f64_cpu_wrapper,
1593    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f64,
1594    "layer_norm_backward_f64"
1595);
1596cpu_norm_last_dim_backward_wrapper!(
1597    layer_norm_last_dim_backward_bf16_cpu_wrapper,
1598    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_bf16,
1599    "layer_norm_backward_bf16"
1600);
1601cpu_norm_last_dim_backward_wrapper!(
1602    layer_norm_last_dim_backward_f16_cpu_wrapper,
1603    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_backward_f16,
1604    "layer_norm_backward_f16"
1605);
1606
1607cpu_norm_last_dim_backward_wrapper!(
1608    rms_norm_last_dim_backward_f32_cpu_wrapper,
1609    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f32,
1610    "rms_norm_backward_f32"
1611);
1612cpu_norm_last_dim_backward_wrapper!(
1613    rms_norm_last_dim_backward_f64_cpu_wrapper,
1614    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f64,
1615    "rms_norm_backward_f64"
1616);
1617cpu_norm_last_dim_backward_wrapper!(
1618    rms_norm_last_dim_backward_bf16_cpu_wrapper,
1619    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_bf16,
1620    "rms_norm_backward_bf16"
1621);
1622cpu_norm_last_dim_backward_wrapper!(
1623    rms_norm_last_dim_backward_f16_cpu_wrapper,
1624    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_backward_f16,
1625    "rms_norm_backward_f16"
1626);
1627
1628/// ReduceMaxTo backward — 2 inputs (x, upstream) + 1 output. Carries
1629/// the shape pair via `OpParams::ReduceMaxToBackward`.
1630/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
1631/// production wrapper and the importer can bind it FROM the contract.
1632macro_rules! cpu_reduce_max_to_backward_wrapper {
1633    ($wrapper:ident, $kernel:path) => {
1634        pub(crate) fn $wrapper(
1635            inputs: &[Arc<RwLock<Storage>>],
1636            outputs: &mut [Arc<RwLock<Storage>>],
1637            _layouts: &[Layout],
1638            params: &OpParams,
1639        ) -> Result<()> {
1640            if inputs.len() != 2 || outputs.len() != 1 {
1641                return Err(Error::Msg(format!(
1642                    "reduce_max_to_backward wrapper expects 2 inputs (x, upstream) + 1 output, got {} + {}",
1643                    inputs.len(), outputs.len(),
1644                )).bt());
1645            }
1646            let (input_shape, output_shape) = match params {
1647                OpParams::ReduceMaxToBackward { input_shape, output_shape } => {
1648                    (input_shape.as_slice(), output_shape.as_slice())
1649                }
1650                other => {
1651                    return Err(Error::Msg(format!(
1652                        "reduce_max_to_backward wrapper expects OpParams::ReduceMaxToBackward, got {other:?}",
1653                    )).bt());
1654                }
1655            };
1656            let x_guard = read_storage(&inputs[0])?;
1657            let up_guard = read_storage(&inputs[1])?;
1658            let mut out_guard = write_storage(&outputs[0])?;
1659            let x_cpu = cpu_input(&x_guard)?;
1660            let up_cpu = cpu_input(&up_guard)?;
1661            let out_cpu = cpu_output(&mut out_guard)?;
1662            $kernel(x_cpu, up_cpu, out_cpu, input_shape, output_shape)
1663        }
1664    };
1665}
1666
1667cpu_reduce_max_to_backward_wrapper!(
1668    reduce_max_to_backward_f32_cpu_wrapper,
1669    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f32
1670);
1671cpu_reduce_max_to_backward_wrapper!(
1672    reduce_max_to_backward_f64_cpu_wrapper,
1673    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f64
1674);
1675cpu_reduce_max_to_backward_wrapper!(
1676    reduce_max_to_backward_bf16_cpu_wrapper,
1677    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_bf16
1678);
1679cpu_reduce_max_to_backward_wrapper!(
1680    reduce_max_to_backward_f16_cpu_wrapper,
1681    fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f16
1682);
1683
1684/// Single dtype-agnostic MaskedFill wrapper. Reads `fill_bytes`
1685/// (pre-encoded by `op_to_op_params`) and dtype_size from the output.
1686pub(crate) fn masked_fill_cpu_wrapper(
1687    inputs: &[Arc<RwLock<Storage>>],
1688    outputs: &mut [Arc<RwLock<Storage>>],
1689    _layouts: &[Layout],
1690    params: &OpParams,
1691) -> Result<()> {
1692    if inputs.len() != 2 || outputs.len() != 1 {
1693        return Err(Error::Msg(format!(
1694            "masked_fill_cpu_wrapper: expects 2 inputs (x, mask) + 1 output, got {} + {}",
1695            inputs.len(),
1696            outputs.len(),
1697        ))
1698        .bt());
1699    }
1700    let fill_bytes = match params {
1701        OpParams::MaskedFill { fill_bytes } => fill_bytes.clone(),
1702        other => {
1703            return Err(Error::Msg(format!(
1704                "masked_fill_cpu_wrapper: expects OpParams::MaskedFill, got {other:?}",
1705            ))
1706            .bt());
1707        }
1708    };
1709    let in_guard = read_storage(&inputs[0])?;
1710    let mask_guard = read_storage(&inputs[1])?;
1711    // GAP-168(c): validate the mask dtype at RUNTIME, matching `where`'s wrapper
1712    // and the Vulkan masked_fill. This wrapper previously did NOT check, so a U8
1713    // buffer flowed in under a Bool node and worked — the byte-identity hazard
1714    // exactly: `Bool` and `U8` are the same bytes, so the wrong wiring produces
1715    // the right answer and nothing complains. The graph builder already rejects a
1716    // non-Bool mask; this is the second line, for storage assembled directly.
1717    if mask_guard.dtype != DType::Bool {
1718        return Err(Error::Msg(format!(
1719            "masked_fill_cpu_wrapper: mask must be Bool, got {:?} (GAP-168(c))",
1720            mask_guard.dtype,
1721        ))
1722        .bt());
1723    }
1724    let mut out_guard = write_storage(&outputs[0])?;
1725    let dtype_size = out_guard.dtype.size_in_bytes();
1726    let in_cpu = cpu_input(&in_guard)?;
1727    let mask_cpu = cpu_input(&mask_guard)?;
1728    let out_cpu = cpu_output(&mut out_guard)?;
1729    fuel_cpu_backend::byte_kernels::masked_fill_cpu(
1730        in_cpu,
1731        mask_cpu,
1732        out_cpu,
1733        &fill_bytes,
1734        dtype_size,
1735    )
1736}
1737
1738/// Single dtype-agnostic dispatch wrapper for Pad. The kernel is
1739/// byte-level (`fill_bytes` is pre-encoded for the output dtype in
1740/// `op_to_op_params`); this wrapper just reads dtype_size from the
1741/// output Storage and passes through. One wrapper covers every
1742/// dtype the binding-table is registered for.
1743pub(crate) fn pad_cpu_wrapper(
1744    inputs: &[Arc<RwLock<Storage>>],
1745    outputs: &mut [Arc<RwLock<Storage>>],
1746    _layouts: &[Layout],
1747    params: &OpParams,
1748) -> Result<()> {
1749    if inputs.len() != 1 || outputs.len() != 1 {
1750        return Err(Error::Msg(format!(
1751            "pad wrapper expects 1 input + 1 output, got {} + {}",
1752            inputs.len(),
1753            outputs.len(),
1754        ))
1755        .bt());
1756    }
1757    let (in_shape, out_shape, padding, mode_tag, fill_bytes) = match params {
1758        OpParams::Pad {
1759            in_shape,
1760            out_shape,
1761            padding,
1762            mode_tag,
1763            fill_bytes,
1764        } => (in_shape, out_shape, padding, *mode_tag, fill_bytes),
1765        other => {
1766            return Err(
1767                Error::Msg(format!("pad wrapper expects OpParams::Pad, got {other:?}",)).bt(),
1768            );
1769        }
1770    };
1771    let in_guard = read_storage(&inputs[0])?;
1772    let mut out_guard = write_storage(&outputs[0])?;
1773    let dtype_size = out_guard.dtype.size_in_bytes();
1774    let in_cpu = cpu_input(&in_guard)?;
1775    let out_cpu = cpu_output(&mut out_guard)?;
1776    // Per-mode forward dispatch.
1777    match mode_tag {
1778        0 => fuel_cpu_backend::byte_kernels::pad_const_cpu(
1779            in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size, fill_bytes,
1780        ),
1781        1 => {
1782            // Reflect: validate before/after <= n-1 per axis (otherwise
1783            // the reflection runs off the input).
1784            for (k, (&n, &(b, a))) in in_shape.iter().zip(padding.iter()).enumerate() {
1785                if n > 0 && (b > n - 1 || a > n - 1) {
1786                    return Err(Error::Msg(format!(
1787                        "pad reflect: axis {k} has dim_size {n}; before ({b}) and \
1788                         after ({a}) must each be <= dim_size - 1",
1789                    ))
1790                    .bt());
1791                }
1792            }
1793            fuel_cpu_backend::byte_kernels::pad_reflect_cpu(
1794                in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1795            )
1796        }
1797        2 => fuel_cpu_backend::byte_kernels::pad_replicate_cpu(
1798            in_cpu, out_cpu, in_shape, out_shape, padding, dtype_size,
1799        ),
1800        other => Err(Error::Msg(format!("pad: unknown mode_tag {other}",)).bt()),
1801    }
1802}
1803
1804/// Build a `(1 input, 1 output)` per-dtype dispatch wrapper for
1805/// `Op::PadBackward`. Per-dtype (unlike forward Pad) because the
1806/// backward kernel does typed addition (accumulation per input slot).
1807macro_rules! cpu_pad_backward_wrapper {
1808    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1809        pub(crate) fn $wrapper(
1810            inputs: &[Arc<RwLock<Storage>>],
1811            outputs: &mut [Arc<RwLock<Storage>>],
1812            _layouts: &[Layout],
1813            params: &OpParams,
1814        ) -> Result<()> {
1815            if inputs.len() != 1 || outputs.len() != 1 {
1816                return Err(Error::Msg(format!(
1817                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1818                    $op_name,
1819                    inputs.len(),
1820                    outputs.len(),
1821                ))
1822                .bt());
1823            }
1824            let (in_shape, out_shape, padding, mode_tag) = match params {
1825                OpParams::PadBackward {
1826                    in_shape,
1827                    out_shape,
1828                    padding,
1829                    mode_tag,
1830                } => (in_shape, out_shape, padding, *mode_tag),
1831                other => {
1832                    return Err(Error::Msg(format!(
1833                        "{} wrapper expects OpParams::PadBackward, got {other:?}",
1834                        $op_name,
1835                    ))
1836                    .bt())
1837                }
1838            };
1839            let in_guard = read_storage(&inputs[0])?;
1840            let mut out_guard = write_storage(&outputs[0])?;
1841            let in_cpu = cpu_input(&in_guard)?;
1842            let out_cpu = cpu_output(&mut out_guard)?;
1843            $kernel(in_cpu, out_cpu, in_shape, out_shape, padding, mode_tag)
1844        }
1845    };
1846}
1847
1848cpu_pad_backward_wrapper!(
1849    pad_backward_f32_cpu_wrapper,
1850    fuel_cpu_backend::byte_kernels::pad_backward_f32,
1851    "pad_backward_f32"
1852);
1853cpu_pad_backward_wrapper!(
1854    pad_backward_f64_cpu_wrapper,
1855    fuel_cpu_backend::byte_kernels::pad_backward_f64,
1856    "pad_backward_f64"
1857);
1858cpu_pad_backward_wrapper!(
1859    pad_backward_bf16_cpu_wrapper,
1860    fuel_cpu_backend::byte_kernels::pad_backward_bf16,
1861    "pad_backward_bf16"
1862);
1863cpu_pad_backward_wrapper!(
1864    pad_backward_f16_cpu_wrapper,
1865    fuel_cpu_backend::byte_kernels::pad_backward_f16,
1866    "pad_backward_f16"
1867);
1868
1869/// Dispatch wrapper for `(Roll, *, Cpu)`. Dtype-agnostic at the byte
1870/// level. Same shape as Flip plus a signed `shift`.
1871pub(crate) fn roll_cpu_wrapper(
1872    inputs: &[Arc<RwLock<Storage>>],
1873    outputs: &mut [Arc<RwLock<Storage>>],
1874    _layouts: &[Layout],
1875    params: &OpParams,
1876) -> Result<()> {
1877    if inputs.len() != 1 || outputs.len() != 1 {
1878        return Err(Error::Msg(format!(
1879            "roll wrapper expects 1 input + 1 output, got {} + {}",
1880            inputs.len(),
1881            outputs.len(),
1882        ))
1883        .bt());
1884    }
1885    let (outer, dim_size, inner, shift) = match params {
1886        OpParams::Roll {
1887            outer_count,
1888            dim_size,
1889            inner_count,
1890            shift,
1891            ..
1892        } => (*outer_count, *dim_size, *inner_count, *shift),
1893        other => {
1894            return Err(Error::Msg(format!(
1895                "roll wrapper expects OpParams::Roll, got {other:?}",
1896            ))
1897            .bt());
1898        }
1899    };
1900    let in_guard = read_storage(&inputs[0])?;
1901    let mut out_guard = write_storage(&outputs[0])?;
1902    let dtype_size = out_guard.dtype.size_in_bytes();
1903    let in_cpu = cpu_input(&in_guard)?;
1904    let out_cpu = cpu_output(&mut out_guard)?;
1905    fuel_cpu_backend::byte_kernels::roll_cpu(
1906        in_cpu, out_cpu, outer, dim_size, inner, shift, dtype_size,
1907    )
1908}
1909
1910/// Generate a CPU argextremum wrapper. Output dtype is U32; the
1911/// binding-table key is keyed on the OUTPUT dtype = U32. The
1912/// wrapper validates the input is F32 (only F32 is wired today).
1913macro_rules! cpu_arg_dim_wrapper {
1914    ($wrapper:ident, $kernel:path, $op_name:literal) => {
1915        fn $wrapper(
1916            inputs: &[Arc<RwLock<Storage>>],
1917            outputs: &mut [Arc<RwLock<Storage>>],
1918            layouts: &[Layout],
1919            params: &OpParams,
1920        ) -> Result<()> {
1921            if inputs.len() != 1 || outputs.len() != 1 {
1922                return Err(Error::Msg(format!(
1923                    "{} wrapper expects 1 input + 1 output, got {} + {}",
1924                    $op_name,
1925                    inputs.len(),
1926                    outputs.len(),
1927                ))
1928                .bt());
1929            }
1930            let dims = match params {
1931                OpParams::Reduce { dims, .. } => dims,
1932                other => {
1933                    return Err(Error::Msg(format!(
1934                        "{} wrapper expects OpParams::Reduce, got {other:?}",
1935                        $op_name,
1936                    ))
1937                    .bt())
1938                }
1939            };
1940            if dims.len() != 1 {
1941                return Err(Error::Msg(format!(
1942                    "{} wrapper expects exactly 1 reduce dim, got {dims:?}",
1943                    $op_name,
1944                ))
1945                .bt());
1946            }
1947            let dim = dims[0];
1948            let input_layout = layouts.first().ok_or_else(|| {
1949                Error::Msg(format!(
1950                    "{} wrapper: layouts empty (executor must pass input layout at [0])",
1951                    $op_name,
1952                ))
1953                .bt()
1954            })?;
1955            let in_guard = read_storage(&inputs[0])?;
1956            if in_guard.dtype != DType::F32 {
1957                return Err(Error::Msg(format!(
1958                    "{}: only F32 input is wired today, got {:?}",
1959                    $op_name, in_guard.dtype,
1960                ))
1961                .bt());
1962            }
1963            let mut out_guard = write_storage(&outputs[0])?;
1964            let in_cpu = cpu_input(&in_guard)?;
1965            let out_cpu = cpu_output(&mut out_guard)?;
1966            $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
1967        }
1968    };
1969}
1970
1971cpu_arg_dim_wrapper!(
1972    argmax_dim_u32_cpu_wrapper,
1973    fuel_cpu_backend::byte_kernels::argmax_dim_f32,
1974    "argmax_dim"
1975);
1976cpu_arg_dim_wrapper!(
1977    argmin_dim_u32_cpu_wrapper,
1978    fuel_cpu_backend::byte_kernels::argmin_dim_f32,
1979    "argmin_dim"
1980);
1981
1982/// Dispatch wrapper for `(IndexAdd, F32, Cpu)`. Three inputs:
1983/// `(base, indices, src)` (rank-1 U32 indices). Output shape == base.
1984/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
1985/// indexing contract.
1986pub(crate) fn index_add_f32_cpu_wrapper(
1987    inputs: &[Arc<RwLock<Storage>>],
1988    outputs: &mut [Arc<RwLock<Storage>>],
1989    _layouts: &[Layout],
1990    params: &OpParams,
1991) -> Result<()> {
1992    if inputs.len() != 3 || outputs.len() != 1 {
1993        return Err(Error::Msg(format!(
1994            "index_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
1995            inputs.len(),
1996            outputs.len(),
1997        ))
1998        .bt());
1999    }
2000    let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2001        OpParams::IndexAdd {
2002            outer_count,
2003            base_dim_size,
2004            n_indices,
2005            inner_count,
2006        } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2007        other => {
2008            return Err(Error::Msg(format!(
2009                "index_add wrapper expects OpParams::IndexAdd, got {other:?}",
2010            ))
2011            .bt());
2012        }
2013    };
2014    let base_guard = read_storage(&inputs[0])?;
2015    let idx_guard = read_storage(&inputs[1])?;
2016    if idx_guard.dtype != DType::U32 {
2017        return Err(Error::Msg(format!(
2018            "index_add: indices must be U32, got {:?}",
2019            idx_guard.dtype,
2020        ))
2021        .bt());
2022    }
2023    let src_guard = read_storage(&inputs[2])?;
2024    let mut out_guard = write_storage(&outputs[0])?;
2025    let base_cpu = cpu_input(&base_guard)?;
2026    let idx_cpu = cpu_input(&idx_guard)?;
2027    let src_cpu = cpu_input(&src_guard)?;
2028    let out_cpu = cpu_output(&mut out_guard)?;
2029    fuel_cpu_backend::byte_kernels::index_add_f32(
2030        base_cpu,
2031        idx_cpu,
2032        src_cpu,
2033        out_cpu,
2034        outer_count,
2035        base_dim_size,
2036        n_indices,
2037        inner_count,
2038    )
2039}
2040
2041/// Dispatch wrapper for `(ScatterAdd, F32, Cpu)`. Three inputs:
2042/// `(base, indices, src)` (same-rank U32 indices). Output shape == base.
2043/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2044/// indexing contract.
2045pub(crate) fn scatter_add_f32_cpu_wrapper(
2046    inputs: &[Arc<RwLock<Storage>>],
2047    outputs: &mut [Arc<RwLock<Storage>>],
2048    _layouts: &[Layout],
2049    params: &OpParams,
2050) -> Result<()> {
2051    if inputs.len() != 3 || outputs.len() != 1 {
2052        return Err(Error::Msg(format!(
2053            "scatter_add wrapper expects 3 inputs (base, indices, src) + 1 output, got {} + {}",
2054            inputs.len(),
2055            outputs.len(),
2056        ))
2057        .bt());
2058    }
2059    let (base_shape, src_shape, dim) = match params {
2060        OpParams::ScatterAdd {
2061            base_shape,
2062            src_shape,
2063            dim,
2064        } => (base_shape, src_shape, *dim),
2065        other => {
2066            return Err(Error::Msg(format!(
2067                "scatter_add wrapper expects OpParams::ScatterAdd, got {other:?}",
2068            ))
2069            .bt());
2070        }
2071    };
2072    let base_guard = read_storage(&inputs[0])?;
2073    let idx_guard = read_storage(&inputs[1])?;
2074    if idx_guard.dtype != DType::U32 {
2075        return Err(Error::Msg(format!(
2076            "scatter_add: indices must be U32, got {:?}",
2077            idx_guard.dtype,
2078        ))
2079        .bt());
2080    }
2081    let src_guard = read_storage(&inputs[2])?;
2082    let mut out_guard = write_storage(&outputs[0])?;
2083    let base_cpu = cpu_input(&base_guard)?;
2084    let idx_cpu = cpu_input(&idx_guard)?;
2085    let src_cpu = cpu_input(&src_guard)?;
2086    let out_cpu = cpu_output(&mut out_guard)?;
2087    fuel_cpu_backend::byte_kernels::scatter_add_f32(
2088        base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2089    )
2090}
2091
2092/// Dispatch wrapper for `(Rope, F32, Cpu)`. Three inputs:
2093/// `(x, cos, sin)`. `OpParams::Rope` carries the geometry.
2094/// `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`) can bind this
2095/// symbol from the rope contract.
2096pub(crate) fn rope_f32_cpu_wrapper(
2097    inputs: &[Arc<RwLock<Storage>>],
2098    outputs: &mut [Arc<RwLock<Storage>>],
2099    _layouts: &[Layout],
2100    params: &OpParams,
2101) -> Result<()> {
2102    if inputs.len() != 3 || outputs.len() != 1 {
2103        return Err(Error::Msg(format!(
2104            "rope wrapper expects 3 inputs (x, cos, sin) + 1 output, got {} + {}",
2105            inputs.len(),
2106            outputs.len(),
2107        ))
2108        .bt());
2109    }
2110    let (outer_count, seq, head_dim) = match params {
2111        OpParams::Rope {
2112            outer_count,
2113            seq,
2114            head_dim,
2115        } => (*outer_count, *seq, *head_dim),
2116        other => {
2117            return Err(Error::Msg(format!(
2118                "rope wrapper expects OpParams::Rope, got {other:?}",
2119            ))
2120            .bt());
2121        }
2122    };
2123    let x_guard = read_storage(&inputs[0])?;
2124    let cos_guard = read_storage(&inputs[1])?;
2125    let sin_guard = read_storage(&inputs[2])?;
2126    let mut out_guard = write_storage(&outputs[0])?;
2127    let x_cpu = cpu_input(&x_guard)?;
2128    let cos_cpu = cpu_input(&cos_guard)?;
2129    let sin_cpu = cpu_input(&sin_guard)?;
2130    let out_cpu = cpu_output(&mut out_guard)?;
2131    fuel_cpu_backend::byte_kernels::rope_f32(
2132        x_cpu,
2133        cos_cpu,
2134        sin_cpu,
2135        out_cpu,
2136        outer_count,
2137        seq,
2138        head_dim,
2139    )
2140}
2141
2142/// Dispatch wrapper for `(Gather, *, Cpu)`. Dtype-agnostic at
2143/// the byte level — `dtype_size` flows from the output Storage.
2144/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2145/// indexing contract (the fabricated `gather_cpu_<dt>` symbols all resolve here).
2146pub(crate) fn gather_cpu_wrapper(
2147    inputs: &[Arc<RwLock<Storage>>],
2148    outputs: &mut [Arc<RwLock<Storage>>],
2149    _layouts: &[Layout],
2150    params: &OpParams,
2151) -> Result<()> {
2152    if inputs.len() != 2 || outputs.len() != 1 {
2153        return Err(Error::Msg(format!(
2154            "gather wrapper expects 2 inputs + 1 output, got {} + {}",
2155            inputs.len(),
2156            outputs.len(),
2157        ))
2158        .bt());
2159    }
2160    let (source_shape, output_shape, dim) = match params {
2161        OpParams::Gather {
2162            source_shape,
2163            output_shape,
2164            dim,
2165        } => (source_shape, output_shape, *dim),
2166        other => {
2167            return Err(Error::Msg(format!(
2168                "gather wrapper expects OpParams::Gather, got {other:?}",
2169            ))
2170            .bt());
2171        }
2172    };
2173    let src_guard = read_storage(&inputs[0])?;
2174    let idx_guard = read_storage(&inputs[1])?;
2175    if idx_guard.dtype != DType::U32 {
2176        return Err(Error::Msg(format!(
2177            "gather: indices must be U32, got {:?}",
2178            idx_guard.dtype,
2179        ))
2180        .bt());
2181    }
2182    let mut out_guard = write_storage(&outputs[0])?;
2183    let dtype_size = out_guard.dtype.size_in_bytes();
2184    let src_cpu = cpu_input(&src_guard)?;
2185    let idx_cpu = cpu_input(&idx_guard)?;
2186    let out_cpu = cpu_output(&mut out_guard)?;
2187    fuel_cpu_backend::byte_kernels::gather_cpu(
2188        src_cpu,
2189        idx_cpu,
2190        out_cpu,
2191        source_shape,
2192        output_shape,
2193        dim,
2194        dtype_size,
2195    )
2196}
2197
2198/// Dispatch wrapper for `(IndexSelect, *, Cpu)`. Dtype-agnostic
2199/// at the byte level — `dtype_size` flows from the output Storage.
2200/// Indices are always U32 (validated at runtime).
2201/// `pub(crate)` so the FKC `CpuLinkRegistry` can bind this symbol from the
2202/// indexing contract (the fabricated `index_select_cpu_<dt>` symbols resolve here).
2203pub(crate) fn index_select_cpu_wrapper(
2204    inputs: &[Arc<RwLock<Storage>>],
2205    outputs: &mut [Arc<RwLock<Storage>>],
2206    _layouts: &[Layout],
2207    params: &OpParams,
2208) -> Result<()> {
2209    if inputs.len() != 2 {
2210        return Err(Error::Msg(format!(
2211            "index_select wrapper expects 2 inputs (source, indices), got {}",
2212            inputs.len(),
2213        ))
2214        .bt());
2215    }
2216    if outputs.len() != 1 {
2217        return Err(Error::Msg(format!(
2218            "index_select wrapper expects 1 output, got {}",
2219            outputs.len(),
2220        ))
2221        .bt());
2222    }
2223    let (outer_count, source_dim_size, n_indices, inner_count) = match params {
2224        OpParams::IndexSelect {
2225            outer_count,
2226            source_dim_size,
2227            n_indices,
2228            inner_count,
2229        } => (*outer_count, *source_dim_size, *n_indices, *inner_count),
2230        other => {
2231            return Err(Error::Msg(format!(
2232                "index_select wrapper expects OpParams::IndexSelect, got {other:?}",
2233            ))
2234            .bt());
2235        }
2236    };
2237    let src_guard = read_storage(&inputs[0])?;
2238    let idx_guard = read_storage(&inputs[1])?;
2239    if idx_guard.dtype != DType::U32 {
2240        return Err(Error::Msg(format!(
2241            "index_select: indices must be U32, got {:?}",
2242            idx_guard.dtype,
2243        ))
2244        .bt());
2245    }
2246    let mut out_guard = write_storage(&outputs[0])?;
2247    let dtype_size = out_guard.dtype.size_in_bytes();
2248    let src_cpu = cpu_input(&src_guard)?;
2249    let idx_cpu = cpu_input(&idx_guard)?;
2250    let out_cpu = cpu_output(&mut out_guard)?;
2251    fuel_cpu_backend::byte_kernels::index_select_cpu(
2252        src_cpu,
2253        idx_cpu,
2254        out_cpu,
2255        outer_count,
2256        source_dim_size,
2257        n_indices,
2258        inner_count,
2259        dtype_size,
2260    )
2261}
2262
2263/// Generate a CPU last-dim norm wrapper that pulls
2264/// `(outer_count, last_dim, eps)` from `OpParams::NormLastDim`
2265/// and forwards to a typed kernel.
2266macro_rules! cpu_norm_last_dim_wrapper {
2267    ($wrapper:ident, $kernel:path, $op_name:literal) => {
2268        pub(crate) fn $wrapper(
2269            inputs: &[Arc<RwLock<Storage>>],
2270            outputs: &mut [Arc<RwLock<Storage>>],
2271            _layouts: &[Layout],
2272            params: &OpParams,
2273        ) -> Result<()> {
2274            if inputs.len() != 1 || outputs.len() != 1 {
2275                return Err(Error::Msg(format!(
2276                    "{} wrapper expects 1 input + 1 output, got {} + {}",
2277                    $op_name,
2278                    inputs.len(),
2279                    outputs.len(),
2280                ))
2281                .bt());
2282            }
2283            let (outer_count, last_dim, eps) = match params {
2284                OpParams::NormLastDim {
2285                    outer_count,
2286                    last_dim,
2287                    eps,
2288                } => (*outer_count, *last_dim, *eps),
2289                other => {
2290                    return Err(Error::Msg(format!(
2291                        "{} wrapper expects OpParams::NormLastDim, got {other:?}",
2292                        $op_name,
2293                    ))
2294                    .bt())
2295                }
2296            };
2297            let in_guard = read_storage(&inputs[0])?;
2298            let mut out_guard = write_storage(&outputs[0])?;
2299            let in_cpu = cpu_input(&in_guard)?;
2300            let out_cpu = cpu_output(&mut out_guard)?;
2301            $kernel(in_cpu, out_cpu, outer_count, last_dim, eps)
2302        }
2303    };
2304}
2305
2306cpu_norm_last_dim_wrapper!(
2307    rms_norm_last_dim_f32_cpu_wrapper,
2308    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f32,
2309    "rms_norm_last_dim"
2310);
2311cpu_norm_last_dim_wrapper!(
2312    layer_norm_last_dim_f32_cpu_wrapper,
2313    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f32,
2314    "layer_norm_last_dim"
2315);
2316cpu_norm_last_dim_wrapper!(
2317    rms_norm_last_dim_bf16_cpu_wrapper,
2318    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_bf16,
2319    "rms_norm_last_dim"
2320);
2321cpu_norm_last_dim_wrapper!(
2322    rms_norm_last_dim_f16_cpu_wrapper,
2323    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f16,
2324    "rms_norm_last_dim"
2325);
2326cpu_norm_last_dim_wrapper!(
2327    layer_norm_last_dim_bf16_cpu_wrapper,
2328    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_bf16,
2329    "layer_norm_last_dim"
2330);
2331cpu_norm_last_dim_wrapper!(
2332    layer_norm_last_dim_f16_cpu_wrapper,
2333    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f16,
2334    "layer_norm_last_dim"
2335);
2336cpu_norm_last_dim_wrapper!(
2337    rms_norm_last_dim_f64_cpu_wrapper,
2338    fuel_cpu_backend::byte_kernels::rms_norm_last_dim_f64,
2339    "rms_norm_last_dim"
2340);
2341cpu_norm_last_dim_wrapper!(
2342    layer_norm_last_dim_f64_cpu_wrapper,
2343    fuel_cpu_backend::byte_kernels::layer_norm_last_dim_f64,
2344    "layer_norm_last_dim"
2345);
2346
2347/// Dispatch wrapper for `(SoftmaxLastDim, F32, Cpu)`. Single
2348/// input + single output; (outer_count, last_dim) flow through
2349/// `OpParams::SoftmaxLastDim`.
2350/// Generate a CPU SoftmaxLastDim wrapper for any element type.
2351/// All entries share the (1 input, 1 output, OpParams::SoftmaxLastDim)
2352/// shape; only the underlying typed kernel differs.
2353macro_rules! cpu_softmax_last_dim_wrapper {
2354    ($wrapper:ident, $kernel:path) => {
2355        pub(crate) fn $wrapper(
2356            inputs: &[Arc<RwLock<Storage>>],
2357            outputs: &mut [Arc<RwLock<Storage>>],
2358            _layouts: &[Layout],
2359            params: &OpParams,
2360        ) -> Result<()> {
2361            if inputs.len() != 1 || outputs.len() != 1 {
2362                return Err(Error::Msg(format!(
2363                    "softmax_last_dim wrapper expects 1 input + 1 output, got {} + {}",
2364                    inputs.len(),
2365                    outputs.len(),
2366                ))
2367                .bt());
2368            }
2369            let (outer_count, last_dim) =
2370                match params {
2371                    OpParams::SoftmaxLastDim {
2372                        outer_count,
2373                        last_dim,
2374                    } => (*outer_count, *last_dim),
2375                    other => return Err(Error::Msg(format!(
2376                        "softmax_last_dim wrapper expects OpParams::SoftmaxLastDim, got {other:?}",
2377                    ))
2378                    .bt()),
2379                };
2380            let in_guard = read_storage(&inputs[0])?;
2381            let mut out_guard = write_storage(&outputs[0])?;
2382            let in_cpu = cpu_input(&in_guard)?;
2383            let out_cpu = cpu_output(&mut out_guard)?;
2384            $kernel(in_cpu, out_cpu, outer_count, last_dim)
2385        }
2386    };
2387}
2388
2389cpu_softmax_last_dim_wrapper!(
2390    softmax_last_dim_f32_cpu_wrapper,
2391    fuel_cpu_backend::byte_kernels::softmax_last_dim_f32
2392);
2393cpu_softmax_last_dim_wrapper!(
2394    softmax_last_dim_f64_cpu_wrapper,
2395    fuel_cpu_backend::byte_kernels::softmax_last_dim_f64
2396);
2397cpu_softmax_last_dim_wrapper!(
2398    softmax_last_dim_bf16_cpu_wrapper,
2399    fuel_cpu_backend::byte_kernels::softmax_last_dim_bf16
2400);
2401cpu_softmax_last_dim_wrapper!(
2402    softmax_last_dim_f16_cpu_wrapper,
2403    fuel_cpu_backend::byte_kernels::softmax_last_dim_f16
2404);
2405
2406/// Generate a CPU Rope wrapper for any element type. The wrapper
2407/// shape is identical across dtypes — three inputs (x, cos, sin)
2408/// and `OpParams::Rope` carries the geometry. `pub(crate)` so the FKC
2409/// `CpuLinkRegistry` (`fkc::cpu_link`) can bind these symbols from the rope
2410/// contract.
2411macro_rules! cpu_rope_wrapper {
2412    ($wrapper:ident, $kernel:path) => {
2413        pub(crate) fn $wrapper(
2414            inputs: &[Arc<RwLock<Storage>>],
2415            outputs: &mut [Arc<RwLock<Storage>>],
2416            _layouts: &[Layout],
2417            params: &OpParams,
2418        ) -> Result<()> {
2419            if inputs.len() != 3 || outputs.len() != 1 {
2420                return Err(Error::Msg(format!(
2421                    "rope wrapper expects 3 inputs + 1 output, got {} + {}",
2422                    inputs.len(),
2423                    outputs.len(),
2424                ))
2425                .bt());
2426            }
2427            let (outer_count, seq, head_dim) = match params {
2428                OpParams::Rope {
2429                    outer_count,
2430                    seq,
2431                    head_dim,
2432                } => (*outer_count, *seq, *head_dim),
2433                other => {
2434                    return Err(Error::Msg(format!(
2435                        "rope wrapper expects OpParams::Rope, got {other:?}",
2436                    ))
2437                    .bt())
2438                }
2439            };
2440            let x_guard = read_storage(&inputs[0])?;
2441            let cos_guard = read_storage(&inputs[1])?;
2442            let sin_guard = read_storage(&inputs[2])?;
2443            let mut out_guard = write_storage(&outputs[0])?;
2444            let x_cpu = cpu_input(&x_guard)?;
2445            let cos_cpu = cpu_input(&cos_guard)?;
2446            let sin_cpu = cpu_input(&sin_guard)?;
2447            let out_cpu = cpu_output(&mut out_guard)?;
2448            $kernel(x_cpu, cos_cpu, sin_cpu, out_cpu, outer_count, seq, head_dim)
2449        }
2450    };
2451}
2452
2453cpu_rope_wrapper!(
2454    rope_bf16_cpu_wrapper,
2455    fuel_cpu_backend::byte_kernels::rope_bf16
2456);
2457cpu_rope_wrapper!(
2458    rope_f16_cpu_wrapper,
2459    fuel_cpu_backend::byte_kernels::rope_f16
2460);
2461cpu_rope_wrapper!(
2462    rope_f64_cpu_wrapper,
2463    fuel_cpu_backend::byte_kernels::rope_f64
2464);
2465
2466/// The per-`QuantType` host kernel choice shared by [`qmatmul_f32_cpu_wrapper`] and the CUDA
2467/// wrapper's host fallback (`baracuda_dispatch`).
2468#[allow(clippy::too_many_arguments)]
2469pub fn qmatmul_cpu_by_type(
2470    quant_type: fuel_graph::QuantType,
2471    act_cpu: &fuel_cpu_backend::CpuStorageBytes,
2472    w_cpu: &fuel_cpu_backend::CpuStorageBytes,
2473    out_cpu: &mut fuel_cpu_backend::CpuStorageBytes,
2474    batch_count: usize,
2475    m: usize,
2476    n: usize,
2477    k: usize,
2478) -> Result<()> {
2479    use fuel_graph::QuantType;
2480    match quant_type {
2481        QuantType::Q4_0 => fuel_cpu_backend::byte_kernels::qmatmul_q4_0_f32(
2482            act_cpu,
2483            w_cpu,
2484            out_cpu,
2485            batch_count,
2486            m,
2487            n,
2488            k,
2489        ),
2490        QuantType::Q4_1 => fuel_cpu_backend::byte_kernels::qmatmul_q4_1_f32(
2491            act_cpu,
2492            w_cpu,
2493            out_cpu,
2494            batch_count,
2495            m,
2496            n,
2497            k,
2498        ),
2499        QuantType::Q5_0 => fuel_cpu_backend::byte_kernels::qmatmul_q5_0_f32(
2500            act_cpu,
2501            w_cpu,
2502            out_cpu,
2503            batch_count,
2504            m,
2505            n,
2506            k,
2507        ),
2508        QuantType::Q5_1 => fuel_cpu_backend::byte_kernels::qmatmul_q5_1_f32(
2509            act_cpu,
2510            w_cpu,
2511            out_cpu,
2512            batch_count,
2513            m,
2514            n,
2515            k,
2516        ),
2517        QuantType::Q8_0 => fuel_cpu_backend::byte_kernels::qmatmul_q8_0_f32(
2518            act_cpu,
2519            w_cpu,
2520            out_cpu,
2521            batch_count,
2522            m,
2523            n,
2524            k,
2525        ),
2526        QuantType::Q8_1 => fuel_cpu_backend::byte_kernels::qmatmul_q8_1_f32(
2527            act_cpu,
2528            w_cpu,
2529            out_cpu,
2530            batch_count,
2531            m,
2532            n,
2533            k,
2534        ),
2535        QuantType::Q2K => fuel_cpu_backend::byte_kernels::qmatmul_q2k_f32(
2536            act_cpu,
2537            w_cpu,
2538            out_cpu,
2539            batch_count,
2540            m,
2541            n,
2542            k,
2543        ),
2544        QuantType::Q3K => fuel_cpu_backend::byte_kernels::qmatmul_q3k_f32(
2545            act_cpu,
2546            w_cpu,
2547            out_cpu,
2548            batch_count,
2549            m,
2550            n,
2551            k,
2552        ),
2553        QuantType::Q4_K_M => fuel_cpu_backend::byte_kernels::qmatmul_q4_k_m_f32(
2554            act_cpu,
2555            w_cpu,
2556            out_cpu,
2557            batch_count,
2558            m,
2559            n,
2560            k,
2561        ),
2562        QuantType::Q5K => fuel_cpu_backend::byte_kernels::qmatmul_q5k_f32(
2563            act_cpu,
2564            w_cpu,
2565            out_cpu,
2566            batch_count,
2567            m,
2568            n,
2569            k,
2570        ),
2571        QuantType::Q6K => fuel_cpu_backend::byte_kernels::qmatmul_q6k_f32(
2572            act_cpu,
2573            w_cpu,
2574            out_cpu,
2575            batch_count,
2576            m,
2577            n,
2578            k,
2579        ),
2580        QuantType::Iq4Nl => fuel_cpu_backend::byte_kernels::qmatmul_iq4_nl_f32(
2581            act_cpu,
2582            w_cpu,
2583            out_cpu,
2584            batch_count,
2585            m,
2586            n,
2587            k,
2588        ),
2589        QuantType::Iq4Xs => fuel_cpu_backend::byte_kernels::qmatmul_iq4_xs_f32(
2590            act_cpu,
2591            w_cpu,
2592            out_cpu,
2593            batch_count,
2594            m,
2595            n,
2596            k,
2597        ),
2598        QuantType::Iq3S => fuel_cpu_backend::byte_kernels::qmatmul_iq3_s_f32(
2599            act_cpu,
2600            w_cpu,
2601            out_cpu,
2602            batch_count,
2603            m,
2604            n,
2605            k,
2606        ),
2607    }
2608}
2609
2610/// Dispatch wrapper for `(QMatMul, F32, Cpu)`. Two inputs:
2611/// activations (F32) and quantized weight bytes (U32-typed).
2612/// `OpParams::QMatMul` carries the quant_type + (batch, m, n, k);
2613/// the wrapper picks the right typed kernel based on quant_type.
2614///
2615/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the linear-quant fused
2616/// bundle's `qmatmul_cpu` `entry_point` symbol to this wrapper
2617/// (`CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`).
2618pub(crate) fn qmatmul_f32_cpu_wrapper(
2619    inputs: &[Arc<RwLock<Storage>>],
2620    outputs: &mut [Arc<RwLock<Storage>>],
2621    _layouts: &[Layout],
2622    params: &OpParams,
2623) -> Result<()> {
2624    if inputs.len() != 2 {
2625        return Err(Error::Msg(format!(
2626            "qmatmul wrapper expects 2 inputs (activations, weight_bytes), got {}",
2627            inputs.len(),
2628        ))
2629        .bt());
2630    }
2631    if outputs.len() != 1 {
2632        return Err(Error::Msg(format!(
2633            "qmatmul wrapper expects 1 output, got {}",
2634            outputs.len(),
2635        ))
2636        .bt());
2637    }
2638    let (quant_type, batch_count, m, n, k) = match params {
2639        OpParams::QMatMul {
2640            quant_type,
2641            batch_count,
2642            m,
2643            n,
2644            k,
2645        } => (*quant_type, *batch_count, *m, *n, *k),
2646        other => {
2647            return Err(Error::Msg(format!(
2648                "qmatmul wrapper expects OpParams::QMatMul, got {other:?}",
2649            ))
2650            .bt());
2651        }
2652    };
2653    let act_guard = read_storage(&inputs[0])?;
2654    let w_guard = read_storage(&inputs[1])?;
2655    if w_guard.dtype != DType::U32 {
2656        return Err(Error::Msg(format!(
2657            "qmatmul: weight bytes must be U32-typed (raw block stream), got {:?}",
2658            w_guard.dtype,
2659        ))
2660        .bt());
2661    }
2662    let mut out_guard = write_storage(&outputs[0])?;
2663    let act_cpu = cpu_input(&act_guard)?;
2664    let w_cpu = cpu_input(&w_guard)?;
2665    let out_cpu = cpu_output(&mut out_guard)?;
2666    qmatmul_cpu_by_type(quant_type, act_cpu, w_cpu, out_cpu, batch_count, m, n, k)
2667}
2668
2669/// Dispatch wrapper for `(WriteSlice, *, Cpu)`. Dtype-agnostic — the
2670/// underlying kernel is `write_slice_cpu(... dtype_size)`. The wrapper
2671/// reads dtype_size from the output (dest) Storage's dtype tag. Takes
2672/// 1 input (source) + 1 output (dest, mutated in place); the slab
2673/// offset rides in `OpParams::WriteSlice`. `pub(crate)` so the
2674/// shape-ops FKC contract can resolve its `write_slice_cpu` entry point
2675/// to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2676pub(crate) fn write_slice_cpu_wrapper(
2677    inputs: &[Arc<RwLock<Storage>>],
2678    outputs: &mut [Arc<RwLock<Storage>>],
2679    _layouts: &[Layout],
2680    params: &OpParams,
2681) -> Result<()> {
2682    if inputs.len() != 1 || outputs.len() != 1 {
2683        return Err(Error::Msg(format!(
2684            "write_slice wrapper expects 1 input (source) + 1 output (dest), \
2685             got {} + {}",
2686            inputs.len(),
2687            outputs.len(),
2688        ))
2689        .bt());
2690    }
2691    let (dest_shape, ranges) = match params {
2692        OpParams::WriteSlice {
2693            dest_shape, ranges, ..
2694        } => (dest_shape, ranges),
2695        other => {
2696            return Err(Error::Msg(format!(
2697                "write_slice wrapper expects OpParams::WriteSlice, got {other:?}",
2698            ))
2699            .bt());
2700        }
2701    };
2702    let src_guard = read_storage(&inputs[0])?;
2703    let src_cpu = cpu_input(&src_guard)?;
2704    let mut dest_guard = write_storage(&outputs[0])?;
2705    let dtype_size = dest_guard.dtype.size_in_bytes();
2706    let dest_cpu = cpu_output(&mut dest_guard)?;
2707    fuel_cpu_backend::byte_kernels::write_slice_cpu(
2708        src_cpu, dest_cpu, dest_shape, ranges, dtype_size,
2709    )
2710}
2711
2712/// Dispatch wrapper for `(WriteSliceRotating, *, Cpu)`. Same shape
2713/// as `write_slice_cpu_wrapper` plus a second input carrying the
2714/// dynamic position scalar (a runtime U32 operand, NOT part of the
2715/// binding-table lookup key — see `build_lookup_dtypes`). `pub(crate)`
2716/// so the shape-ops FKC contract can resolve its
2717/// `write_slice_rotating_cpu` entry point to this fn via
2718/// [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2719pub(crate) fn write_slice_rotating_cpu_wrapper(
2720    inputs: &[Arc<RwLock<Storage>>],
2721    outputs: &mut [Arc<RwLock<Storage>>],
2722    _layouts: &[Layout],
2723    params: &OpParams,
2724) -> Result<()> {
2725    if inputs.len() != 2 || outputs.len() != 1 {
2726        return Err(Error::Msg(format!(
2727            "write_slice_rotating wrapper expects 2 inputs (source, position) + 1 output (dest), \
2728             got {} + {}",
2729            inputs.len(),
2730            outputs.len(),
2731        ))
2732        .bt());
2733    }
2734    let (dest_shape, axis, modulus, ranges) =
2735        match params {
2736            OpParams::WriteSliceRotating {
2737                dest_shape,
2738                axis,
2739                modulus,
2740                ranges,
2741            } => (dest_shape, *axis, *modulus, ranges),
2742            other => return Err(Error::Msg(format!(
2743                "write_slice_rotating wrapper expects OpParams::WriteSliceRotating, got {other:?}",
2744            ))
2745            .bt()),
2746        };
2747    let src_guard = read_storage(&inputs[0])?;
2748    let src_cpu = cpu_input(&src_guard)?;
2749    let pos_guard = read_storage(&inputs[1])?;
2750    let pos_cpu = cpu_input(&pos_guard)?;
2751    let mut dest_guard = write_storage(&outputs[0])?;
2752    let dtype_size = dest_guard.dtype.size_in_bytes();
2753    let dest_cpu = cpu_output(&mut dest_guard)?;
2754    fuel_cpu_backend::byte_kernels::write_slice_rotating_cpu(
2755        src_cpu, pos_cpu, dest_cpu, dest_shape, axis, modulus, ranges, dtype_size,
2756    )
2757}
2758
2759/// Dispatch wrapper for `(WriteSliceDoff, *, Cpu)`. Like
2760/// `write_slice_rotating_cpu_wrapper` but the second input is a
2761/// rank-0 `I64` offset (the device-resident start on `axis`; read
2762/// host-side here on CPU) and there is no modulus/wrap. `pub(crate)`
2763/// so the shape-ops FKC contract can resolve its `write_slice_doff_cpu`
2764/// entry point to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2765pub(crate) fn write_slice_doff_cpu_wrapper(
2766    inputs: &[Arc<RwLock<Storage>>],
2767    outputs: &mut [Arc<RwLock<Storage>>],
2768    _layouts: &[Layout],
2769    params: &OpParams,
2770) -> Result<()> {
2771    if inputs.len() != 2 || outputs.len() != 1 {
2772        return Err(Error::Msg(format!(
2773            "write_slice_doff wrapper expects 2 inputs (source, offset) + 1 output (dest), \
2774             got {} + {}",
2775            inputs.len(),
2776            outputs.len(),
2777        ))
2778        .bt());
2779    }
2780    let (dest_shape, axis, ranges) = match params {
2781        OpParams::WriteSliceDoff {
2782            dest_shape,
2783            axis,
2784            ranges,
2785        } => (dest_shape, *axis, ranges),
2786        other => {
2787            return Err(Error::Msg(format!(
2788                "write_slice_doff wrapper expects OpParams::WriteSliceDoff, got {other:?}",
2789            ))
2790            .bt());
2791        }
2792    };
2793    let src_guard = read_storage(&inputs[0])?;
2794    let src_cpu = cpu_input(&src_guard)?;
2795    let off_guard = read_storage(&inputs[1])?;
2796    let off_cpu = cpu_input(&off_guard)?;
2797    let mut dest_guard = write_storage(&outputs[0])?;
2798    let dtype_size = dest_guard.dtype.size_in_bytes();
2799    let dest_cpu = cpu_output(&mut dest_guard)?;
2800    fuel_cpu_backend::byte_kernels::write_slice_doff_cpu(
2801        src_cpu, off_cpu, dest_cpu, dest_shape, axis, ranges, dtype_size,
2802    )
2803}
2804
2805pub(crate) fn concat_cpu_wrapper(
2806    inputs: &[Arc<RwLock<Storage>>],
2807    outputs: &mut [Arc<RwLock<Storage>>],
2808    _layouts: &[Layout],
2809    params: &OpParams,
2810) -> Result<()> {
2811    if inputs.is_empty() {
2812        return Err(Error::Msg("concat wrapper expects ≥ 1 input, got 0".to_string()).bt());
2813    }
2814    if outputs.len() != 1 {
2815        return Err(Error::Msg(format!(
2816            "concat wrapper expects 1 output, got {}",
2817            outputs.len(),
2818        ))
2819        .bt());
2820    }
2821    let (outer_count, input_dim_sizes, inner_count) = match params {
2822        OpParams::Concat {
2823            outer_count,
2824            input_dim_sizes,
2825            inner_count,
2826            ..
2827        } => (*outer_count, input_dim_sizes, *inner_count),
2828        other => {
2829            return Err(Error::Msg(format!(
2830                "concat wrapper expects OpParams::Concat, got {other:?}",
2831            ))
2832            .bt());
2833        }
2834    };
2835    if input_dim_sizes.len() != inputs.len() {
2836        return Err(Error::Msg(format!(
2837            "concat wrapper: OpParams declares {} inputs but the work item \
2838             carries {}",
2839            input_dim_sizes.len(),
2840            inputs.len(),
2841        ))
2842        .bt());
2843    }
2844    let in_guards: Vec<_> = inputs
2845        .iter()
2846        .map(read_storage)
2847        .collect::<Result<Vec<_>>>()?;
2848    let mut in_cpus: Vec<&fuel_cpu_backend::CpuStorageBytes> = Vec::with_capacity(in_guards.len());
2849    for g in &in_guards {
2850        in_cpus.push(cpu_input(g)?);
2851    }
2852    let mut out_guard = write_storage(&outputs[0])?;
2853    let dtype_size = out_guard.dtype.size_in_bytes();
2854    let out_cpu = cpu_output(&mut out_guard)?;
2855    fuel_cpu_backend::byte_kernels::concat_cpu(
2856        &in_cpus,
2857        out_cpu,
2858        outer_count,
2859        input_dim_sizes,
2860        inner_count,
2861        dtype_size,
2862    )
2863}
2864
2865/// Generate a CPU IndexAdd wrapper. Same shape across all dtypes;
2866/// only the underlying typed kernel differs.
2867macro_rules! cpu_index_add_wrapper {
2868    ($wrapper:ident, $kernel:path, $idx_ck:literal) => {
2869        // `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`) can bind
2870        // these symbols from the indexing contract.
2871        pub(crate) fn $wrapper(
2872            inputs: &[Arc<RwLock<Storage>>],
2873            outputs: &mut [Arc<RwLock<Storage>>],
2874            _layouts: &[Layout],
2875            params: &OpParams,
2876        ) -> Result<()> {
2877            if inputs.len() != 3 || outputs.len() != 1 {
2878                return Err(Error::Msg(format!(
2879                    "{}: expects 3 inputs + 1 output, got {} + {}",
2880                    $idx_ck,
2881                    inputs.len(),
2882                    outputs.len(),
2883                ))
2884                .bt());
2885            }
2886            let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2887                OpParams::IndexAdd {
2888                    outer_count,
2889                    base_dim_size,
2890                    n_indices,
2891                    inner_count,
2892                } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2893                other => {
2894                    return Err(Error::Msg(format!(
2895                        "{}: expects OpParams::IndexAdd, got {other:?}",
2896                        $idx_ck,
2897                    ))
2898                    .bt())
2899                }
2900            };
2901            let base_guard = read_storage(&inputs[0])?;
2902            let idx_guard = read_storage(&inputs[1])?;
2903            if idx_guard.dtype != DType::U32 {
2904                return Err(Error::Msg(format!("{}: indices must be U32", $idx_ck,)).bt());
2905            }
2906            let src_guard = read_storage(&inputs[2])?;
2907            let mut out_guard = write_storage(&outputs[0])?;
2908            let base_cpu = cpu_input(&base_guard)?;
2909            let idx_cpu = cpu_input(&idx_guard)?;
2910            let src_cpu = cpu_input(&src_guard)?;
2911            let out_cpu = cpu_output(&mut out_guard)?;
2912            $kernel(
2913                base_cpu,
2914                idx_cpu,
2915                src_cpu,
2916                out_cpu,
2917                outer_count,
2918                base_dim_size,
2919                n_indices,
2920                inner_count,
2921            )
2922        }
2923    };
2924}
2925
2926cpu_index_add_wrapper!(
2927    index_add_f64_cpu_wrapper,
2928    fuel_cpu_backend::byte_kernels::index_add_f64,
2929    "index_add_f64"
2930);
2931cpu_index_add_wrapper!(
2932    index_add_bf16_cpu_wrapper,
2933    fuel_cpu_backend::byte_kernels::index_add_bf16,
2934    "index_add_bf16"
2935);
2936cpu_index_add_wrapper!(
2937    index_add_f16_cpu_wrapper,
2938    fuel_cpu_backend::byte_kernels::index_add_f16,
2939    "index_add_f16"
2940);
2941
2942/// Generate a CPU ScatterAdd wrapper.
2943macro_rules! cpu_scatter_add_wrapper {
2944    ($wrapper:ident, $kernel:path, $name_str:literal) => {
2945        // `pub(crate)` so the FKC `CpuLinkRegistry` can bind these symbols.
2946        pub(crate) fn $wrapper(
2947            inputs: &[Arc<RwLock<Storage>>],
2948            outputs: &mut [Arc<RwLock<Storage>>],
2949            _layouts: &[Layout],
2950            params: &OpParams,
2951        ) -> Result<()> {
2952            if inputs.len() != 3 || outputs.len() != 1 {
2953                return Err(Error::Msg(format!(
2954                    "{}: expects 3 inputs + 1 output, got {} + {}",
2955                    $name_str,
2956                    inputs.len(),
2957                    outputs.len(),
2958                ))
2959                .bt());
2960            }
2961            let (base_shape, src_shape, dim) = match params {
2962                OpParams::ScatterAdd {
2963                    base_shape,
2964                    src_shape,
2965                    dim,
2966                } => (base_shape, src_shape, *dim),
2967                other => {
2968                    return Err(Error::Msg(format!(
2969                        "{}: expects OpParams::ScatterAdd, got {other:?}",
2970                        $name_str,
2971                    ))
2972                    .bt())
2973                }
2974            };
2975            let base_guard = read_storage(&inputs[0])?;
2976            let idx_guard = read_storage(&inputs[1])?;
2977            if idx_guard.dtype != DType::U32 {
2978                return Err(Error::Msg(format!("{}: indices must be U32", $name_str,)).bt());
2979            }
2980            let src_guard = read_storage(&inputs[2])?;
2981            let mut out_guard = write_storage(&outputs[0])?;
2982            let base_cpu = cpu_input(&base_guard)?;
2983            let idx_cpu = cpu_input(&idx_guard)?;
2984            let src_cpu = cpu_input(&src_guard)?;
2985            let out_cpu = cpu_output(&mut out_guard)?;
2986            $kernel(
2987                base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2988            )
2989        }
2990    };
2991}
2992
2993cpu_scatter_add_wrapper!(
2994    scatter_add_f64_cpu_wrapper,
2995    fuel_cpu_backend::byte_kernels::scatter_add_f64,
2996    "scatter_add_f64"
2997);
2998cpu_scatter_add_wrapper!(
2999    scatter_add_bf16_cpu_wrapper,
3000    fuel_cpu_backend::byte_kernels::scatter_add_bf16,
3001    "scatter_add_bf16"
3002);
3003cpu_scatter_add_wrapper!(
3004    scatter_add_f16_cpu_wrapper,
3005    fuel_cpu_backend::byte_kernels::scatter_add_f16,
3006    "scatter_add_f16"
3007);
3008
3009/// Build a CPU Affine wrapper for any element type. Cast from f64
3010/// scalars in OpParams::Affine to the target arithmetic type
3011/// happens inside the macro (different cast for f64 vs half).
3012macro_rules! cpu_affine_wrapper_native {
3013    ($wrapper:ident, $kernel:path, $T:ty) => {
3014        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3015        // real production wrapper for the affine-clamp-powi contract import.
3016        pub(crate) fn $wrapper(
3017            inputs: &[Arc<RwLock<Storage>>],
3018            outputs: &mut [Arc<RwLock<Storage>>],
3019            _layouts: &[Layout],
3020            params: &OpParams,
3021        ) -> Result<()> {
3022            if inputs.len() != 1 || outputs.len() != 1 {
3023                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3024            }
3025            let (mul, add) = match params {
3026                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3027                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3028            };
3029            let in_guard = read_storage(&inputs[0])?;
3030            let mut out_guard = write_storage(&outputs[0])?;
3031            let in_cpu = cpu_input(&in_guard)?;
3032            let out_cpu = cpu_output(&mut out_guard)?;
3033            $kernel(in_cpu, out_cpu, mul, add)
3034        }
3035    };
3036}
3037
3038cpu_affine_wrapper_native!(
3039    affine_f64_cpu_wrapper,
3040    fuel_cpu_backend::byte_kernels::affine_f64,
3041    f64
3042);
3043
3044macro_rules! cpu_affine_wrapper_half {
3045    ($wrapper:ident, $kernel:path) => {
3046        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3047        // real production wrapper for the affine-clamp-powi contract import.
3048        pub(crate) fn $wrapper(
3049            inputs: &[Arc<RwLock<Storage>>],
3050            outputs: &mut [Arc<RwLock<Storage>>],
3051            _layouts: &[Layout],
3052            params: &OpParams,
3053        ) -> Result<()> {
3054            if inputs.len() != 1 || outputs.len() != 1 {
3055                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3056            }
3057            let (mul, add) = match params {
3058                OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3059                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3060            };
3061            let in_guard = read_storage(&inputs[0])?;
3062            let mut out_guard = write_storage(&outputs[0])?;
3063            let in_cpu = cpu_input(&in_guard)?;
3064            let out_cpu = cpu_output(&mut out_guard)?;
3065            $kernel(in_cpu, out_cpu, mul, add)
3066        }
3067    };
3068}
3069
3070cpu_affine_wrapper_half!(
3071    affine_bf16_cpu_wrapper,
3072    fuel_cpu_backend::byte_kernels::affine_bf16
3073);
3074cpu_affine_wrapper_half!(
3075    affine_f16_cpu_wrapper,
3076    fuel_cpu_backend::byte_kernels::affine_f16
3077);
3078
3079macro_rules! cpu_clamp_wrapper {
3080    ($wrapper:ident, $kernel:path, $T:ty) => {
3081        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3082        // real production wrapper for the affine-clamp-powi contract import.
3083        pub(crate) fn $wrapper(
3084            inputs: &[Arc<RwLock<Storage>>],
3085            outputs: &mut [Arc<RwLock<Storage>>],
3086            _layouts: &[Layout],
3087            params: &OpParams,
3088        ) -> Result<()> {
3089            if inputs.len() != 1 || outputs.len() != 1 {
3090                return Err(Error::Msg("clamp: 1 input + 1 output".to_string()).bt());
3091            }
3092            let (min, max) = match params {
3093                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3094                other => return Err(Error::Msg(format!("clamp: bad params {other:?}")).bt()),
3095            };
3096            let in_guard = read_storage(&inputs[0])?;
3097            let mut out_guard = write_storage(&outputs[0])?;
3098            let in_cpu = cpu_input(&in_guard)?;
3099            let out_cpu = cpu_output(&mut out_guard)?;
3100            $kernel(in_cpu, out_cpu, min, max)
3101        }
3102    };
3103}
3104
3105cpu_clamp_wrapper!(
3106    clamp_f64_cpu_wrapper,
3107    fuel_cpu_backend::byte_kernels::clamp_f64,
3108    f64
3109);
3110cpu_clamp_wrapper!(
3111    clamp_bf16_cpu_wrapper,
3112    fuel_cpu_backend::byte_kernels::clamp_bf16,
3113    f32
3114);
3115cpu_clamp_wrapper!(
3116    clamp_f16_cpu_wrapper,
3117    fuel_cpu_backend::byte_kernels::clamp_f16,
3118    f32
3119);
3120
3121macro_rules! cpu_powi_wrapper {
3122    ($wrapper:ident, $kernel:path) => {
3123        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3124        // real production wrapper for the affine-clamp-powi contract import.
3125        pub(crate) fn $wrapper(
3126            inputs: &[Arc<RwLock<Storage>>],
3127            outputs: &mut [Arc<RwLock<Storage>>],
3128            _layouts: &[Layout],
3129            params: &OpParams,
3130        ) -> Result<()> {
3131            if inputs.len() != 1 || outputs.len() != 1 {
3132                return Err(Error::Msg("powi: 1 input + 1 output".to_string()).bt());
3133            }
3134            let exp = match params {
3135                OpParams::PowI { exp } => *exp,
3136                other => return Err(Error::Msg(format!("powi: bad params {other:?}")).bt()),
3137            };
3138            let in_guard = read_storage(&inputs[0])?;
3139            let mut out_guard = write_storage(&outputs[0])?;
3140            let in_cpu = cpu_input(&in_guard)?;
3141            let out_cpu = cpu_output(&mut out_guard)?;
3142            $kernel(in_cpu, out_cpu, exp)
3143        }
3144    };
3145}
3146
3147cpu_powi_wrapper!(
3148    powi_f64_cpu_wrapper,
3149    fuel_cpu_backend::byte_kernels::powi_f64
3150);
3151cpu_powi_wrapper!(
3152    powi_bf16_cpu_wrapper,
3153    fuel_cpu_backend::byte_kernels::powi_bf16
3154);
3155cpu_powi_wrapper!(
3156    powi_f16_cpu_wrapper,
3157    fuel_cpu_backend::byte_kernels::powi_f16
3158);
3159
3160// ArgMax/ArgMin per-input-dtype wrappers. The existing
3161// `cpu_arg_dim_wrapper!` macro hardcodes F32 input — generalize it
3162// for non-F32 input dtypes.
3163macro_rules! cpu_arg_dim_wrapper_typed {
3164    ($wrapper:ident, $kernel:path, $expected_in_dtype:expr, $op_name:literal) => {
3165        fn $wrapper(
3166            inputs: &[Arc<RwLock<Storage>>],
3167            outputs: &mut [Arc<RwLock<Storage>>],
3168            layouts: &[Layout],
3169            params: &OpParams,
3170        ) -> Result<()> {
3171            if inputs.len() != 1 || outputs.len() != 1 {
3172                return Err(Error::Msg(format!("{}: 1 input + 1 output", $op_name,)).bt());
3173            }
3174            let dims = match params {
3175                OpParams::Reduce { dims, .. } => dims,
3176                other => {
3177                    return Err(Error::Msg(format!(
3178                        "{}: expects OpParams::Reduce, got {other:?}",
3179                        $op_name,
3180                    ))
3181                    .bt())
3182                }
3183            };
3184            if dims.len() != 1 {
3185                return Err(Error::Msg(format!(
3186                    "{}: expects exactly 1 reduce dim, got {dims:?}",
3187                    $op_name,
3188                ))
3189                .bt());
3190            }
3191            let dim = dims[0];
3192            let input_layout = layouts.first().ok_or_else(|| {
3193                Error::Msg(format!(
3194                    "{}: layouts empty (executor must pass input layout at [0])",
3195                    $op_name,
3196                ))
3197                .bt()
3198            })?;
3199            let in_guard = read_storage(&inputs[0])?;
3200            if in_guard.dtype != $expected_in_dtype {
3201                return Err(Error::Msg(format!(
3202                    "{}: expects input dtype {:?}, got {:?}",
3203                    $op_name, $expected_in_dtype, in_guard.dtype,
3204                ))
3205                .bt());
3206            }
3207            let mut out_guard = write_storage(&outputs[0])?;
3208            let in_cpu = cpu_input(&in_guard)?;
3209            let out_cpu = cpu_output(&mut out_guard)?;
3210            $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
3211        }
3212    };
3213}
3214
3215// New ArgMax/ArgMin entries are keyed on output U32 like the
3216// existing ones, but we need separate wrappers per input dtype.
3217// Use a dispatch macro that combines them.
3218fn argmax_dim_u32_cpu_dispatch(
3219    inputs: &[Arc<RwLock<Storage>>],
3220    outputs: &mut [Arc<RwLock<Storage>>],
3221    _layouts: &[Layout],
3222    params: &OpParams,
3223) -> Result<()> {
3224    let in_dtype = read_storage(&inputs[0])?.dtype;
3225    match in_dtype {
3226        DType::F32 => argmax_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3227        DType::F64 => argmax_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3228        DType::BF16 => argmax_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3229        DType::F16 => argmax_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3230        other => Err(Error::Msg(format!("argmax_dim: unsupported input dtype {other:?}",)).bt()),
3231    }
3232}
3233
3234fn argmin_dim_u32_cpu_dispatch(
3235    inputs: &[Arc<RwLock<Storage>>],
3236    outputs: &mut [Arc<RwLock<Storage>>],
3237    _layouts: &[Layout],
3238    params: &OpParams,
3239) -> Result<()> {
3240    let in_dtype = read_storage(&inputs[0])?.dtype;
3241    match in_dtype {
3242        DType::F32 => argmin_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3243        DType::F64 => argmin_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3244        DType::BF16 => argmin_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3245        DType::F16 => argmin_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3246        other => Err(Error::Msg(format!("argmin_dim: unsupported input dtype {other:?}",)).bt()),
3247    }
3248}
3249
3250cpu_arg_dim_wrapper_typed!(
3251    argmax_dim_f64_only_wrapper,
3252    fuel_cpu_backend::byte_kernels::argmax_dim_f64,
3253    DType::F64,
3254    "argmax_dim_f64"
3255);
3256cpu_arg_dim_wrapper_typed!(
3257    argmin_dim_f64_only_wrapper,
3258    fuel_cpu_backend::byte_kernels::argmin_dim_f64,
3259    DType::F64,
3260    "argmin_dim_f64"
3261);
3262cpu_arg_dim_wrapper_typed!(
3263    argmax_dim_bf16_only_wrapper,
3264    fuel_cpu_backend::byte_kernels::argmax_dim_bf16,
3265    DType::BF16,
3266    "argmax_dim_bf16"
3267);
3268cpu_arg_dim_wrapper_typed!(
3269    argmin_dim_bf16_only_wrapper,
3270    fuel_cpu_backend::byte_kernels::argmin_dim_bf16,
3271    DType::BF16,
3272    "argmin_dim_bf16"
3273);
3274cpu_arg_dim_wrapper_typed!(
3275    argmax_dim_f16_only_wrapper,
3276    fuel_cpu_backend::byte_kernels::argmax_dim_f16,
3277    DType::F16,
3278    "argmax_dim_f16"
3279);
3280cpu_arg_dim_wrapper_typed!(
3281    argmin_dim_f16_only_wrapper,
3282    fuel_cpu_backend::byte_kernels::argmin_dim_f16,
3283    DType::F16,
3284    "argmin_dim_f16"
3285);
3286
3287/// Dispatch wrapper for `(Affine, F32, Cpu)`. Extracts scalar
3288/// coefficients from `OpParams::Affine`.
3289pub(crate) fn affine_f32_cpu_wrapper(
3290    inputs: &[Arc<RwLock<Storage>>],
3291    outputs: &mut [Arc<RwLock<Storage>>],
3292    _layouts: &[Layout],
3293    params: &OpParams,
3294) -> Result<()> {
3295    if inputs.len() != 1 || outputs.len() != 1 {
3296        return Err(Error::Msg(format!(
3297            "affine wrapper expects 1 input + 1 output, got {} + {}",
3298            inputs.len(),
3299            outputs.len(),
3300        ))
3301        .bt());
3302    }
3303    let (mul, add) = match params {
3304        OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3305        other => {
3306            return Err(Error::Msg(format!(
3307                "affine wrapper expects OpParams::Affine, got {other:?}",
3308            ))
3309            .bt());
3310        }
3311    };
3312    let in_guard = read_storage(&inputs[0])?;
3313    let mut out_guard = write_storage(&outputs[0])?;
3314    let in_cpu = cpu_input(&in_guard)?;
3315    let out_cpu = cpu_output(&mut out_guard)?;
3316    fuel_cpu_backend::byte_kernels::affine_f32(in_cpu, out_cpu, mul, add)
3317}
3318
3319/// Dispatch wrapper macro for in-place affine on CPU. Inputs is
3320/// empty (the executor's `WorkItemKind::InplaceKernel` arm passes the
3321/// target Arc as `outputs[0]`); the kernel reads + writes through the
3322/// single write lock.
3323macro_rules! cpu_affine_inplace_wrapper {
3324    ($name:ident, $kernel:ident, $T:ty) => {
3325        pub(crate) fn $name(
3326            inputs: &[Arc<RwLock<Storage>>],
3327            outputs: &mut [Arc<RwLock<Storage>>],
3328            _layouts: &[Layout],
3329            params: &OpParams,
3330        ) -> Result<()> {
3331            if !inputs.is_empty() || outputs.len() != 1 {
3332                return Err(Error::Msg(format!(
3333                    concat!(
3334                        stringify!($name),
3335                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3336                    ),
3337                    inputs.len(),
3338                    outputs.len(),
3339                ))
3340                .bt());
3341            }
3342            let (mul, add) = match params {
3343                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3344                other => {
3345                    return Err(Error::Msg(format!(
3346                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3347                        other,
3348                    ))
3349                    .bt())
3350                }
3351            };
3352            let mut out_guard = write_storage(&outputs[0])?;
3353            let out_cpu = cpu_output(&mut out_guard)?;
3354            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3355        }
3356    };
3357    ($name:ident, $kernel:ident, $T:ty, half) => {
3358        pub(crate) fn $name(
3359            inputs: &[Arc<RwLock<Storage>>],
3360            outputs: &mut [Arc<RwLock<Storage>>],
3361            _layouts: &[Layout],
3362            params: &OpParams,
3363        ) -> Result<()> {
3364            if !inputs.is_empty() || outputs.len() != 1 {
3365                return Err(Error::Msg(format!(
3366                    concat!(
3367                        stringify!($name),
3368                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3369                    ),
3370                    inputs.len(),
3371                    outputs.len(),
3372                ))
3373                .bt());
3374            }
3375            let (mul, add) = match params {
3376                OpParams::Affine { mul, add } => (*mul, *add),
3377                other => {
3378                    return Err(Error::Msg(format!(
3379                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3380                        other,
3381                    ))
3382                    .bt())
3383                }
3384            };
3385            let mut out_guard = write_storage(&outputs[0])?;
3386            let out_cpu = cpu_output(&mut out_guard)?;
3387            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3388        }
3389    };
3390}
3391
3392cpu_affine_inplace_wrapper!(inplace_affine_f32_cpu_wrapper, affine_inplace_f32, f32);
3393cpu_affine_inplace_wrapper!(inplace_affine_f64_cpu_wrapper, affine_inplace_f64, f64);
3394cpu_affine_inplace_wrapper!(
3395    inplace_affine_bf16_cpu_wrapper,
3396    affine_inplace_bf16,
3397    f64,
3398    half
3399);
3400cpu_affine_inplace_wrapper!(
3401    inplace_affine_f16_cpu_wrapper,
3402    affine_inplace_f16,
3403    f64,
3404    half
3405);
3406
3407/// Dispatch wrapper macro for in-place clamp on CPU. Same shape as
3408/// `cpu_affine_inplace_wrapper!` (no inputs, target as outputs[0]),
3409/// but pulls `(min, max)` from `OpParams::Clamp`.
3410macro_rules! cpu_clamp_inplace_wrapper {
3411    ($name:ident, $kernel:ident, $T:ty) => {
3412        pub(crate) fn $name(
3413            inputs: &[Arc<RwLock<Storage>>],
3414            outputs: &mut [Arc<RwLock<Storage>>],
3415            _layouts: &[Layout],
3416            params: &OpParams,
3417        ) -> Result<()> {
3418            if !inputs.is_empty() || outputs.len() != 1 {
3419                return Err(Error::Msg(format!(
3420                    concat!(
3421                        stringify!($name),
3422                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3423                    ),
3424                    inputs.len(),
3425                    outputs.len(),
3426                ))
3427                .bt());
3428            }
3429            let (min, max) = match params {
3430                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3431                other => {
3432                    return Err(Error::Msg(format!(
3433                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3434                        other,
3435                    ))
3436                    .bt())
3437                }
3438            };
3439            let mut out_guard = write_storage(&outputs[0])?;
3440            let out_cpu = cpu_output(&mut out_guard)?;
3441            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3442        }
3443    };
3444    ($name:ident, $kernel:ident, $T:ty, half) => {
3445        pub(crate) fn $name(
3446            inputs: &[Arc<RwLock<Storage>>],
3447            outputs: &mut [Arc<RwLock<Storage>>],
3448            _layouts: &[Layout],
3449            params: &OpParams,
3450        ) -> Result<()> {
3451            if !inputs.is_empty() || outputs.len() != 1 {
3452                return Err(Error::Msg(format!(
3453                    concat!(
3454                        stringify!($name),
3455                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3456                    ),
3457                    inputs.len(),
3458                    outputs.len(),
3459                ))
3460                .bt());
3461            }
3462            let (min, max) = match params {
3463                OpParams::Clamp { min, max } => (*min, *max),
3464                other => {
3465                    return Err(Error::Msg(format!(
3466                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3467                        other,
3468                    ))
3469                    .bt())
3470                }
3471            };
3472            let mut out_guard = write_storage(&outputs[0])?;
3473            let out_cpu = cpu_output(&mut out_guard)?;
3474            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3475        }
3476    };
3477}
3478
3479cpu_clamp_inplace_wrapper!(clamp_inplace_f32_cpu_wrapper, clamp_inplace_f32, f32);
3480cpu_clamp_inplace_wrapper!(clamp_inplace_f64_cpu_wrapper, clamp_inplace_f64, f64);
3481cpu_clamp_inplace_wrapper!(
3482    clamp_inplace_bf16_cpu_wrapper,
3483    clamp_inplace_bf16,
3484    f64,
3485    half
3486);
3487cpu_clamp_inplace_wrapper!(clamp_inplace_f16_cpu_wrapper, clamp_inplace_f16, f64, half);
3488
3489/// Dispatch wrapper macro for in-place powi on CPU. Pulls `exp` from
3490/// `OpParams::PowI`.
3491macro_rules! cpu_powi_inplace_wrapper {
3492    ($name:ident, $kernel:ident) => {
3493        pub(crate) fn $name(
3494            inputs: &[Arc<RwLock<Storage>>],
3495            outputs: &mut [Arc<RwLock<Storage>>],
3496            _layouts: &[Layout],
3497            params: &OpParams,
3498        ) -> Result<()> {
3499            if !inputs.is_empty() || outputs.len() != 1 {
3500                return Err(Error::Msg(format!(
3501                    concat!(
3502                        stringify!($name),
3503                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3504                    ),
3505                    inputs.len(),
3506                    outputs.len(),
3507                ))
3508                .bt());
3509            }
3510            let exp = match params {
3511                OpParams::PowI { exp } => *exp,
3512                other => {
3513                    return Err(Error::Msg(format!(
3514                        concat!(stringify!($name), ": expected OpParams::PowI, got {:?}"),
3515                        other,
3516                    ))
3517                    .bt())
3518                }
3519            };
3520            let mut out_guard = write_storage(&outputs[0])?;
3521            let out_cpu = cpu_output(&mut out_guard)?;
3522            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, exp)
3523        }
3524    };
3525}
3526
3527cpu_powi_inplace_wrapper!(powi_inplace_f32_cpu_wrapper, powi_inplace_f32);
3528cpu_powi_inplace_wrapper!(powi_inplace_f64_cpu_wrapper, powi_inplace_f64);
3529cpu_powi_inplace_wrapper!(powi_inplace_bf16_cpu_wrapper, powi_inplace_bf16);
3530cpu_powi_inplace_wrapper!(powi_inplace_f16_cpu_wrapper, powi_inplace_f16);
3531
3532/// Dispatch wrapper macro for in-place elementwise unary ops on CPU.
3533/// Same shape as `cpu_affine_inplace_wrapper!` (inputs empty, target
3534/// adopted as outputs[0] by the executor), but the kernel takes no
3535/// scalar params — just the target buffer.
3536macro_rules! cpu_unary_inplace_wrapper {
3537    ($name:ident, $kernel:ident) => {
3538        pub(crate) fn $name(
3539            inputs: &[Arc<RwLock<Storage>>],
3540            outputs: &mut [Arc<RwLock<Storage>>],
3541            _layouts: &[Layout],
3542            _params: &OpParams,
3543        ) -> Result<()> {
3544            if !inputs.is_empty() || outputs.len() != 1 {
3545                return Err(Error::Msg(format!(
3546                    concat!(
3547                        stringify!($name),
3548                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3549                    ),
3550                    inputs.len(),
3551                    outputs.len(),
3552                ))
3553                .bt());
3554            }
3555            let mut out_guard = write_storage(&outputs[0])?;
3556            let out_cpu = cpu_output(&mut out_guard)?;
3557            fuel_cpu_backend::byte_kernels::$kernel(out_cpu)
3558        }
3559    };
3560}
3561
3562cpu_unary_inplace_wrapper!(relu_inplace_f32_cpu_wrapper, relu_inplace_f32);
3563cpu_unary_inplace_wrapper!(silu_inplace_f32_cpu_wrapper, silu_inplace_f32);
3564cpu_unary_inplace_wrapper!(gelu_inplace_f32_cpu_wrapper, gelu_inplace_f32);
3565cpu_unary_inplace_wrapper!(tanh_inplace_f32_cpu_wrapper, tanh_inplace_f32);
3566cpu_unary_inplace_wrapper!(sigmoid_inplace_f32_cpu_wrapper, sigmoid_inplace_f32);
3567
3568cpu_unary_inplace_wrapper!(relu_inplace_f64_cpu_wrapper, relu_inplace_f64);
3569cpu_unary_inplace_wrapper!(silu_inplace_f64_cpu_wrapper, silu_inplace_f64);
3570cpu_unary_inplace_wrapper!(gelu_inplace_f64_cpu_wrapper, gelu_inplace_f64);
3571cpu_unary_inplace_wrapper!(tanh_inplace_f64_cpu_wrapper, tanh_inplace_f64);
3572cpu_unary_inplace_wrapper!(sigmoid_inplace_f64_cpu_wrapper, sigmoid_inplace_f64);
3573
3574cpu_unary_inplace_wrapper!(relu_inplace_bf16_cpu_wrapper, relu_inplace_bf16);
3575cpu_unary_inplace_wrapper!(silu_inplace_bf16_cpu_wrapper, silu_inplace_bf16);
3576cpu_unary_inplace_wrapper!(gelu_inplace_bf16_cpu_wrapper, gelu_inplace_bf16);
3577cpu_unary_inplace_wrapper!(tanh_inplace_bf16_cpu_wrapper, tanh_inplace_bf16);
3578cpu_unary_inplace_wrapper!(sigmoid_inplace_bf16_cpu_wrapper, sigmoid_inplace_bf16);
3579
3580cpu_unary_inplace_wrapper!(relu_inplace_f16_cpu_wrapper, relu_inplace_f16);
3581cpu_unary_inplace_wrapper!(silu_inplace_f16_cpu_wrapper, silu_inplace_f16);
3582cpu_unary_inplace_wrapper!(gelu_inplace_f16_cpu_wrapper, gelu_inplace_f16);
3583cpu_unary_inplace_wrapper!(tanh_inplace_f16_cpu_wrapper, tanh_inplace_f16);
3584cpu_unary_inplace_wrapper!(sigmoid_inplace_f16_cpu_wrapper, sigmoid_inplace_f16);
3585
3586// In-place unary op family expansion (2026-05-30) — 16 new ops × 4
3587// dtypes. Each wrapper is identical in shape to the original 5-op
3588// starter set; the chassis handles per-dtype math.
3589cpu_unary_inplace_wrapper!(neg_inplace_f32_cpu_wrapper, neg_inplace_f32);
3590cpu_unary_inplace_wrapper!(neg_inplace_f64_cpu_wrapper, neg_inplace_f64);
3591cpu_unary_inplace_wrapper!(neg_inplace_bf16_cpu_wrapper, neg_inplace_bf16);
3592cpu_unary_inplace_wrapper!(neg_inplace_f16_cpu_wrapper, neg_inplace_f16);
3593
3594cpu_unary_inplace_wrapper!(abs_inplace_f32_cpu_wrapper, abs_inplace_f32);
3595cpu_unary_inplace_wrapper!(abs_inplace_f64_cpu_wrapper, abs_inplace_f64);
3596cpu_unary_inplace_wrapper!(abs_inplace_bf16_cpu_wrapper, abs_inplace_bf16);
3597cpu_unary_inplace_wrapper!(abs_inplace_f16_cpu_wrapper, abs_inplace_f16);
3598
3599cpu_unary_inplace_wrapper!(sqr_inplace_f32_cpu_wrapper, sqr_inplace_f32);
3600cpu_unary_inplace_wrapper!(sqr_inplace_f64_cpu_wrapper, sqr_inplace_f64);
3601cpu_unary_inplace_wrapper!(sqr_inplace_bf16_cpu_wrapper, sqr_inplace_bf16);
3602cpu_unary_inplace_wrapper!(sqr_inplace_f16_cpu_wrapper, sqr_inplace_f16);
3603
3604cpu_unary_inplace_wrapper!(sqrt_inplace_f32_cpu_wrapper, sqrt_inplace_f32);
3605cpu_unary_inplace_wrapper!(sqrt_inplace_f64_cpu_wrapper, sqrt_inplace_f64);
3606cpu_unary_inplace_wrapper!(sqrt_inplace_bf16_cpu_wrapper, sqrt_inplace_bf16);
3607cpu_unary_inplace_wrapper!(sqrt_inplace_f16_cpu_wrapper, sqrt_inplace_f16);
3608
3609cpu_unary_inplace_wrapper!(rsqrt_inplace_f32_cpu_wrapper, rsqrt_inplace_f32);
3610cpu_unary_inplace_wrapper!(rsqrt_inplace_f64_cpu_wrapper, rsqrt_inplace_f64);
3611cpu_unary_inplace_wrapper!(rsqrt_inplace_bf16_cpu_wrapper, rsqrt_inplace_bf16);
3612cpu_unary_inplace_wrapper!(rsqrt_inplace_f16_cpu_wrapper, rsqrt_inplace_f16);
3613
3614cpu_unary_inplace_wrapper!(recip_inplace_f32_cpu_wrapper, recip_inplace_f32);
3615cpu_unary_inplace_wrapper!(recip_inplace_f64_cpu_wrapper, recip_inplace_f64);
3616cpu_unary_inplace_wrapper!(recip_inplace_bf16_cpu_wrapper, recip_inplace_bf16);
3617cpu_unary_inplace_wrapper!(recip_inplace_f16_cpu_wrapper, recip_inplace_f16);
3618
3619cpu_unary_inplace_wrapper!(exp_inplace_f32_cpu_wrapper, exp_inplace_f32);
3620cpu_unary_inplace_wrapper!(exp_inplace_f64_cpu_wrapper, exp_inplace_f64);
3621cpu_unary_inplace_wrapper!(exp_inplace_bf16_cpu_wrapper, exp_inplace_bf16);
3622cpu_unary_inplace_wrapper!(exp_inplace_f16_cpu_wrapper, exp_inplace_f16);
3623
3624cpu_unary_inplace_wrapper!(log_inplace_f32_cpu_wrapper, log_inplace_f32);
3625cpu_unary_inplace_wrapper!(log_inplace_f64_cpu_wrapper, log_inplace_f64);
3626cpu_unary_inplace_wrapper!(log_inplace_bf16_cpu_wrapper, log_inplace_bf16);
3627cpu_unary_inplace_wrapper!(log_inplace_f16_cpu_wrapper, log_inplace_f16);
3628
3629cpu_unary_inplace_wrapper!(sin_inplace_f32_cpu_wrapper, sin_inplace_f32);
3630cpu_unary_inplace_wrapper!(sin_inplace_f64_cpu_wrapper, sin_inplace_f64);
3631cpu_unary_inplace_wrapper!(sin_inplace_bf16_cpu_wrapper, sin_inplace_bf16);
3632cpu_unary_inplace_wrapper!(sin_inplace_f16_cpu_wrapper, sin_inplace_f16);
3633
3634cpu_unary_inplace_wrapper!(cos_inplace_f32_cpu_wrapper, cos_inplace_f32);
3635cpu_unary_inplace_wrapper!(cos_inplace_f64_cpu_wrapper, cos_inplace_f64);
3636cpu_unary_inplace_wrapper!(cos_inplace_bf16_cpu_wrapper, cos_inplace_bf16);
3637cpu_unary_inplace_wrapper!(cos_inplace_f16_cpu_wrapper, cos_inplace_f16);
3638
3639cpu_unary_inplace_wrapper!(sign_inplace_f32_cpu_wrapper, sign_inplace_f32);
3640cpu_unary_inplace_wrapper!(sign_inplace_f64_cpu_wrapper, sign_inplace_f64);
3641cpu_unary_inplace_wrapper!(sign_inplace_bf16_cpu_wrapper, sign_inplace_bf16);
3642cpu_unary_inplace_wrapper!(sign_inplace_f16_cpu_wrapper, sign_inplace_f16);
3643
3644cpu_unary_inplace_wrapper!(floor_inplace_f32_cpu_wrapper, floor_inplace_f32);
3645cpu_unary_inplace_wrapper!(floor_inplace_f64_cpu_wrapper, floor_inplace_f64);
3646cpu_unary_inplace_wrapper!(floor_inplace_bf16_cpu_wrapper, floor_inplace_bf16);
3647cpu_unary_inplace_wrapper!(floor_inplace_f16_cpu_wrapper, floor_inplace_f16);
3648
3649cpu_unary_inplace_wrapper!(ceil_inplace_f32_cpu_wrapper, ceil_inplace_f32);
3650cpu_unary_inplace_wrapper!(ceil_inplace_f64_cpu_wrapper, ceil_inplace_f64);
3651cpu_unary_inplace_wrapper!(ceil_inplace_bf16_cpu_wrapper, ceil_inplace_bf16);
3652cpu_unary_inplace_wrapper!(ceil_inplace_f16_cpu_wrapper, ceil_inplace_f16);
3653
3654cpu_unary_inplace_wrapper!(round_inplace_f32_cpu_wrapper, round_inplace_f32);
3655cpu_unary_inplace_wrapper!(round_inplace_f64_cpu_wrapper, round_inplace_f64);
3656cpu_unary_inplace_wrapper!(round_inplace_bf16_cpu_wrapper, round_inplace_bf16);
3657cpu_unary_inplace_wrapper!(round_inplace_f16_cpu_wrapper, round_inplace_f16);
3658
3659cpu_unary_inplace_wrapper!(erf_inplace_f32_cpu_wrapper, erf_inplace_f32);
3660cpu_unary_inplace_wrapper!(erf_inplace_f64_cpu_wrapper, erf_inplace_f64);
3661cpu_unary_inplace_wrapper!(erf_inplace_bf16_cpu_wrapper, erf_inplace_bf16);
3662cpu_unary_inplace_wrapper!(erf_inplace_f16_cpu_wrapper, erf_inplace_f16);
3663
3664cpu_unary_inplace_wrapper!(gelu_erf_inplace_f32_cpu_wrapper, gelu_erf_inplace_f32);
3665cpu_unary_inplace_wrapper!(gelu_erf_inplace_f64_cpu_wrapper, gelu_erf_inplace_f64);
3666cpu_unary_inplace_wrapper!(gelu_erf_inplace_bf16_cpu_wrapper, gelu_erf_inplace_bf16);
3667cpu_unary_inplace_wrapper!(gelu_erf_inplace_f16_cpu_wrapper, gelu_erf_inplace_f16);
3668
3669/// Dispatch wrapper for `(ClampElementwise, F32, Cpu)`.
3670pub(crate) fn clamp_elementwise_f32_cpu_wrapper(
3671    inputs: &[Arc<RwLock<Storage>>],
3672    outputs: &mut [Arc<RwLock<Storage>>],
3673    _layouts: &[Layout],
3674    params: &OpParams,
3675) -> Result<()> {
3676    if inputs.len() != 1 || outputs.len() != 1 {
3677        return Err(Error::Msg(format!(
3678            "clamp wrapper expects 1 input + 1 output, got {} + {}",
3679            inputs.len(),
3680            outputs.len(),
3681        ))
3682        .bt());
3683    }
3684    let (min, max) = match params {
3685        OpParams::Clamp { min, max } => (*min as f32, *max as f32),
3686        other => {
3687            return Err(Error::Msg(format!(
3688                "clamp wrapper expects OpParams::Clamp, got {other:?}",
3689            ))
3690            .bt());
3691        }
3692    };
3693    let in_guard = read_storage(&inputs[0])?;
3694    let mut out_guard = write_storage(&outputs[0])?;
3695    let in_cpu = cpu_input(&in_guard)?;
3696    let out_cpu = cpu_output(&mut out_guard)?;
3697    fuel_cpu_backend::byte_kernels::clamp_f32(in_cpu, out_cpu, min, max)
3698}
3699
3700/// Dispatch wrapper for `(PowIElementwise, F32, Cpu)`.
3701pub(crate) fn powi_elementwise_f32_cpu_wrapper(
3702    inputs: &[Arc<RwLock<Storage>>],
3703    outputs: &mut [Arc<RwLock<Storage>>],
3704    _layouts: &[Layout],
3705    params: &OpParams,
3706) -> Result<()> {
3707    if inputs.len() != 1 || outputs.len() != 1 {
3708        return Err(Error::Msg(format!(
3709            "powi wrapper expects 1 input + 1 output, got {} + {}",
3710            inputs.len(),
3711            outputs.len(),
3712        ))
3713        .bt());
3714    }
3715    let exp = match params {
3716        OpParams::PowI { exp } => *exp,
3717        other => {
3718            return Err(Error::Msg(format!(
3719                "powi wrapper expects OpParams::PowI, got {other:?}",
3720            ))
3721            .bt());
3722        }
3723    };
3724    let in_guard = read_storage(&inputs[0])?;
3725    let mut out_guard = write_storage(&outputs[0])?;
3726    let in_cpu = cpu_input(&in_guard)?;
3727    let out_cpu = cpu_output(&mut out_guard)?;
3728    fuel_cpu_backend::byte_kernels::powi_f32(in_cpu, out_cpu, exp)
3729}
3730
3731/// Build a `(2 inputs `(x, upstream)`, 1 output, OpParams::PowI)` CPU
3732/// dispatch wrapper for the per-dtype PowIBackward kernels.
3733macro_rules! cpu_powi_backward_wrapper {
3734    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3735        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3736        // real production wrapper for the affine-clamp-powi contract import.
3737        pub(crate) fn $wrapper(
3738            inputs: &[Arc<RwLock<Storage>>],
3739            outputs: &mut [Arc<RwLock<Storage>>],
3740            _layouts: &[Layout],
3741            params: &OpParams,
3742        ) -> Result<()> {
3743            if inputs.len() != 2 || outputs.len() != 1 {
3744                return Err(Error::Msg(format!(
3745                    "{} wrapper expects 2 inputs + 1 output, got {} + {}",
3746                    $op_name,
3747                    inputs.len(),
3748                    outputs.len(),
3749                ))
3750                .bt());
3751            }
3752            let exp = match params {
3753                OpParams::PowI { exp } => *exp,
3754                other => {
3755                    return Err(Error::Msg(format!(
3756                        "{} wrapper expects OpParams::PowI, got {other:?}",
3757                        $op_name,
3758                    ))
3759                    .bt())
3760                }
3761            };
3762            let x_guard = read_storage(&inputs[0])?;
3763            let up_guard = read_storage(&inputs[1])?;
3764            let mut out_guard = write_storage(&outputs[0])?;
3765            let x_cpu = cpu_input(&x_guard)?;
3766            let up_cpu = cpu_input(&up_guard)?;
3767            let out_cpu = cpu_output(&mut out_guard)?;
3768            $kernel(x_cpu, up_cpu, out_cpu, exp)
3769        }
3770    };
3771}
3772
3773cpu_powi_backward_wrapper!(
3774    powi_backward_f32_cpu_wrapper,
3775    fuel_cpu_backend::byte_kernels::powi_backward_f32,
3776    "powi_backward_f32"
3777);
3778cpu_powi_backward_wrapper!(
3779    powi_backward_f64_cpu_wrapper,
3780    fuel_cpu_backend::byte_kernels::powi_backward_f64,
3781    "powi_backward_f64"
3782);
3783cpu_powi_backward_wrapper!(
3784    powi_backward_bf16_cpu_wrapper,
3785    fuel_cpu_backend::byte_kernels::powi_backward_bf16,
3786    "powi_backward_bf16"
3787);
3788cpu_powi_backward_wrapper!(
3789    powi_backward_f16_cpu_wrapper,
3790    fuel_cpu_backend::byte_kernels::powi_backward_f16,
3791    "powi_backward_f16"
3792);
3793
3794/// Build a CPU reduction wrapper that calls a typed `(input,
3795/// output, input_shape, dims)` reduce kernel. Verifies the
3796/// `OpParams::Reduce` variant and forwards the shape + dims to the
3797/// kernel.
3798macro_rules! cpu_reduce_wrapper {
3799    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3800        pub(crate) fn $wrapper(
3801            inputs: &[Arc<RwLock<Storage>>],
3802            outputs: &mut [Arc<RwLock<Storage>>],
3803            layouts: &[Layout],
3804            params: &OpParams,
3805        ) -> Result<()> {
3806            if inputs.len() != 1 {
3807                return Err(Error::Msg(format!(
3808                    "{} wrapper expects 1 input, got {}",
3809                    $op_name,
3810                    inputs.len(),
3811                ))
3812                .bt());
3813            }
3814            if outputs.len() != 1 {
3815                return Err(Error::Msg(format!(
3816                    "{} wrapper expects 1 output, got {}",
3817                    $op_name,
3818                    outputs.len(),
3819                ))
3820                .bt());
3821            }
3822            let dims = match params {
3823                OpParams::Reduce { dims, .. } => dims,
3824                other => {
3825                    return Err(Error::Msg(format!(
3826                        "{} wrapper expects OpParams::Reduce, got {:?}",
3827                        $op_name, other,
3828                    ))
3829                    .bt())
3830                }
3831            };
3832            let input_layout = layouts.first().ok_or_else(|| {
3833                Error::Msg(format!(
3834                    "{} wrapper: layouts empty (executor must pass input layout at [0])",
3835                    $op_name,
3836                ))
3837                .bt()
3838            })?;
3839            // The pipelined executor's auto-Contiguize pass
3840            // (stage 4 of Layout-on-Node) materializes contiguous
3841            // bytes for every kernel input before this wrapper is
3842            // called — so by the time we reach here, the input
3843            // bytes match `input_layout.shape()` in row-major
3844            // order. We pass only the shape to the typed kernel.
3845            let input_shape: &[usize] = input_layout.shape().dims();
3846            let in_guard = read_storage(&inputs[0])?;
3847            let mut out_guard = write_storage(&outputs[0])?;
3848            let in_cpu = cpu_input(&in_guard)?;
3849            let out_cpu = cpu_output(&mut out_guard)?;
3850            $kernel(in_cpu, out_cpu, input_shape, dims)
3851        }
3852    };
3853}
3854
3855cpu_reduce_wrapper!(
3856    sum_reduce_f32_cpu_wrapper,
3857    fuel_cpu_backend::byte_kernels::sum_reduce_f32,
3858    "sum_reduce"
3859);
3860cpu_reduce_wrapper!(
3861    max_reduce_f32_cpu_wrapper,
3862    fuel_cpu_backend::byte_kernels::max_reduce_f32,
3863    "max_reduce"
3864);
3865cpu_reduce_wrapper!(
3866    min_reduce_f32_cpu_wrapper,
3867    fuel_cpu_backend::byte_kernels::min_reduce_f32,
3868    "min_reduce"
3869);
3870cpu_reduce_wrapper!(
3871    mean_reduce_f32_cpu_wrapper,
3872    fuel_cpu_backend::byte_kernels::mean_reduce_f32,
3873    "mean_reduce"
3874);
3875cpu_reduce_wrapper!(
3876    sum_reduce_f64_cpu_wrapper,
3877    fuel_cpu_backend::byte_kernels::sum_reduce_f64,
3878    "sum_reduce"
3879);
3880cpu_reduce_wrapper!(
3881    max_reduce_f64_cpu_wrapper,
3882    fuel_cpu_backend::byte_kernels::max_reduce_f64,
3883    "max_reduce"
3884);
3885cpu_reduce_wrapper!(
3886    min_reduce_f64_cpu_wrapper,
3887    fuel_cpu_backend::byte_kernels::min_reduce_f64,
3888    "min_reduce"
3889);
3890cpu_reduce_wrapper!(
3891    mean_reduce_f64_cpu_wrapper,
3892    fuel_cpu_backend::byte_kernels::mean_reduce_f64,
3893    "mean_reduce"
3894);
3895
3896cpu_reduce_wrapper!(
3897    sum_reduce_bf16_cpu_wrapper,
3898    fuel_cpu_backend::byte_kernels::sum_reduce_bf16,
3899    "sum_reduce"
3900);
3901cpu_reduce_wrapper!(
3902    max_reduce_bf16_cpu_wrapper,
3903    fuel_cpu_backend::byte_kernels::max_reduce_bf16,
3904    "max_reduce"
3905);
3906cpu_reduce_wrapper!(
3907    min_reduce_bf16_cpu_wrapper,
3908    fuel_cpu_backend::byte_kernels::min_reduce_bf16,
3909    "min_reduce"
3910);
3911cpu_reduce_wrapper!(
3912    mean_reduce_bf16_cpu_wrapper,
3913    fuel_cpu_backend::byte_kernels::mean_reduce_bf16,
3914    "mean_reduce"
3915);
3916
3917cpu_reduce_wrapper!(
3918    sum_reduce_f16_cpu_wrapper,
3919    fuel_cpu_backend::byte_kernels::sum_reduce_f16,
3920    "sum_reduce"
3921);
3922cpu_reduce_wrapper!(
3923    max_reduce_f16_cpu_wrapper,
3924    fuel_cpu_backend::byte_kernels::max_reduce_f16,
3925    "max_reduce"
3926);
3927cpu_reduce_wrapper!(
3928    min_reduce_f16_cpu_wrapper,
3929    fuel_cpu_backend::byte_kernels::min_reduce_f16,
3930    "min_reduce"
3931);
3932cpu_reduce_wrapper!(
3933    mean_reduce_f16_cpu_wrapper,
3934    fuel_cpu_backend::byte_kernels::mean_reduce_f16,
3935    "mean_reduce"
3936);
3937
3938/// Generate a dispatch wrapper for `(Cast, <target>, Cpu)`. The
3939/// binding-table key is keyed on the *target* dtype (= the
3940/// Node's dtype = the output Storage's dtype); the wrapper reads
3941/// the input Storage's dtype at runtime and dispatches to the
3942/// right typed conversion kernel.
3943macro_rules! cpu_cast_wrapper {
3944    (
3945        $wrapper:ident,
3946        $target_dtype:expr,
3947        $target_name:literal,
3948        { $( $source:pat => $kernel:path ),+ $(,)? } $(,)?
3949    ) => {
3950        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
3951        // real production wrapper and the importer can bind it FROM the contract.
3952        pub(crate) fn $wrapper(
3953            inputs: &[Arc<RwLock<Storage>>],
3954            outputs: &mut [Arc<RwLock<Storage>>],
3955            _layouts: &[Layout],
3956            _params: &OpParams,
3957        ) -> Result<()> {
3958            if inputs.len() != 1 {
3959                return Err(Error::Msg(format!(
3960                    "cast→{} wrapper expects 1 input, got {}",
3961                    $target_name,
3962                    inputs.len(),
3963                ))
3964                .bt());
3965            }
3966            if outputs.len() != 1 {
3967                return Err(Error::Msg(format!(
3968                    "cast→{} wrapper expects 1 output, got {}",
3969                    $target_name,
3970                    outputs.len(),
3971                ))
3972                .bt());
3973            }
3974            let in_guard = read_storage(&inputs[0])?;
3975            let mut out_guard = write_storage(&outputs[0])?;
3976            let source_dtype = in_guard.dtype;
3977            let in_cpu = cpu_input(&in_guard)?;
3978            let out_cpu = cpu_output(&mut out_guard)?;
3979            match source_dtype {
3980                $( $source => $kernel(in_cpu, out_cpu), )+
3981                other => Err(Error::Msg(format!(
3982                    "cast→{}: source dtype {:?} not yet wired (Phase C \
3983                     extends the cast matrix as needed)",
3984                    $target_name, other,
3985                ))
3986                .bt()),
3987            }
3988        }
3989    };
3990}
3991
3992/// Dispatch wrapper for `(Conv2D, *, Cpu)`. Two or three inputs
3993/// (x, weight, optional bias). Shapes + geometry flow through
3994/// `OpParams::Conv2D`.
3995/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
3996/// production wrapper and the importer can bind it FROM the contract.
3997macro_rules! cpu_conv2d_wrapper {
3998    ($name:ident, $kernel:path) => {
3999        pub(crate) fn $name(
4000            inputs: &[Arc<RwLock<Storage>>],
4001            outputs: &mut [Arc<RwLock<Storage>>],
4002            _layouts: &[Layout],
4003            params: &OpParams,
4004        ) -> Result<()> {
4005            if inputs.len() != 2 && inputs.len() != 3 {
4006                return Err(Error::Msg(format!(
4007                    "conv2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4008                    inputs.len(),
4009                ))
4010                .bt());
4011            }
4012            if outputs.len() != 1 {
4013                return Err(Error::Msg(format!(
4014                    "conv2d wrapper expects 1 output, got {}",
4015                    outputs.len(),
4016                ))
4017                .bt());
4018            }
4019            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) = match params {
4020                OpParams::Conv2D {
4021                    x_shape,
4022                    w_shape,
4023                    out_shape,
4024                    stride,
4025                    padding,
4026                    dilation,
4027                    groups,
4028                } => (
4029                    *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4030                ),
4031                other => {
4032                    return Err(Error::Msg(format!(
4033                        "conv2d wrapper expects OpParams::Conv2D, got {other:?}",
4034                    ))
4035                    .bt())
4036                }
4037            };
4038            let x_guard = read_storage(&inputs[0])?;
4039            let w_guard = read_storage(&inputs[1])?;
4040            let bias_guard = match inputs.get(2) {
4041                Some(arc) => Some(read_storage(arc)?),
4042                None => None,
4043            };
4044            let mut out_guard = write_storage(&outputs[0])?;
4045            let x_cpu = cpu_input(&x_guard)?;
4046            let w_cpu = cpu_input(&w_guard)?;
4047            let bias_cpu = match &bias_guard {
4048                Some(g) => Some(cpu_input(g)?),
4049                None => None,
4050            };
4051            let out_cpu = cpu_output(&mut out_guard)?;
4052            $kernel(
4053                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4054                dilation, groups,
4055            )
4056        }
4057    };
4058}
4059
4060cpu_conv2d_wrapper!(
4061    conv2d_f32_cpu_wrapper,
4062    fuel_cpu_backend::byte_kernels::conv2d_f32
4063);
4064cpu_conv2d_wrapper!(
4065    conv2d_f64_cpu_wrapper,
4066    fuel_cpu_backend::byte_kernels::conv2d_f64
4067);
4068cpu_conv2d_wrapper!(
4069    conv2d_bf16_cpu_wrapper,
4070    fuel_cpu_backend::byte_kernels::conv2d_bf16
4071);
4072cpu_conv2d_wrapper!(
4073    conv2d_f16_cpu_wrapper,
4074    fuel_cpu_backend::byte_kernels::conv2d_f16
4075);
4076
4077/// Dispatch wrapper for `(Conv2DEpilogue, *, Cpu)` (row 172 item 3): the conv into
4078/// the output buffer, then the elementwise recipe rewrites it in place.
4079macro_rules! cpu_conv2d_epilogue_wrapper {
4080    ($name:ident, $conv:path, $epilogue:path) => {
4081        pub(crate) fn $name(
4082            inputs: &[Arc<RwLock<Storage>>],
4083            outputs: &mut [Arc<RwLock<Storage>>],
4084            _layouts: &[Layout],
4085            params: &OpParams,
4086        ) -> Result<()> {
4087            let OpParams::Conv2DEpilogue {
4088                x_shape,
4089                w_shape,
4090                out_shape,
4091                stride,
4092                padding,
4093                groups,
4094                has_bias,
4095                recipe,
4096                scalars,
4097            } = params
4098            else {
4099                return Err(Error::Msg(format!(
4100                    "conv2d_epilogue wrapper expects OpParams::Conv2DEpilogue, got {params:?}",
4101                ))
4102                .bt());
4103            };
4104            let conv_arity = 2 + usize::from(*has_bias);
4105            if inputs.len() < conv_arity || outputs.len() != 1 {
4106                return Err(Error::Msg(format!(
4107                    "conv2d_epilogue wrapper expects at least {conv_arity} inputs and 1 output, \
4108                     got {} and {}",
4109                    inputs.len(),
4110                    outputs.len(),
4111                ))
4112                .bt());
4113            }
4114            let expr =
4115                crate::conv_epilogue::compile_epilogue(recipe, scalars, inputs.len() - conv_arity)?;
4116            let guards = inputs
4117                .iter()
4118                .map(read_storage)
4119                .collect::<Result<Vec<_>>>()?;
4120            let cpu = guards
4121                .iter()
4122                .map(|g| cpu_input(g))
4123                .collect::<Result<Vec<_>>>()?;
4124            let mut out_guard = write_storage(&outputs[0])?;
4125            let out_cpu = cpu_output(&mut out_guard)?;
4126            $conv(
4127                cpu[0],
4128                cpu[1],
4129                has_bias.then(|| cpu[2]),
4130                out_cpu,
4131                *x_shape,
4132                *w_shape,
4133                *out_shape,
4134                *stride,
4135                *padding,
4136                (1, 1),
4137                *groups,
4138            )?;
4139            $epilogue(&expr, &cpu[conv_arity..], out_cpu)
4140        }
4141    };
4142}
4143
4144cpu_conv2d_epilogue_wrapper!(
4145    conv2d_epilogue_f32_cpu_wrapper,
4146    fuel_cpu_backend::byte_kernels::conv2d_f32,
4147    fuel_cpu_backend::epilogue::epilogue_f32
4148);
4149cpu_conv2d_epilogue_wrapper!(
4150    conv2d_epilogue_f64_cpu_wrapper,
4151    fuel_cpu_backend::byte_kernels::conv2d_f64,
4152    fuel_cpu_backend::epilogue::epilogue_f64
4153);
4154cpu_conv2d_epilogue_wrapper!(
4155    conv2d_epilogue_bf16_cpu_wrapper,
4156    fuel_cpu_backend::byte_kernels::conv2d_bf16,
4157    fuel_cpu_backend::epilogue::epilogue_bf16
4158);
4159cpu_conv2d_epilogue_wrapper!(
4160    conv2d_epilogue_f16_cpu_wrapper,
4161    fuel_cpu_backend::byte_kernels::conv2d_f16,
4162    fuel_cpu_backend::epilogue::epilogue_f16
4163);
4164
4165/// Dispatch wrapper for `(ConvTranspose2D, *, Cpu)`. Two or three
4166/// inputs (x, weight, [bias]). Geometry flows through
4167/// `OpParams::ConvTranspose2D`.
4168/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4169/// production wrapper and the importer can bind it FROM the contract.
4170macro_rules! cpu_conv_transpose2d_wrapper {
4171    ($name:ident, $kernel:path) => {
4172        pub(crate) fn $name(
4173            inputs: &[Arc<RwLock<Storage>>],
4174            outputs: &mut [Arc<RwLock<Storage>>],
4175            _layouts: &[Layout],
4176            params: &OpParams,
4177        ) -> Result<()> {
4178            if inputs.len() != 2 && inputs.len() != 3 {
4179                return Err(Error::Msg(format!(
4180                    "conv_transpose2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4181                    inputs.len(),
4182                ))
4183                .bt());
4184            }
4185            if outputs.len() != 1 {
4186                return Err(Error::Msg(format!(
4187                    "conv_transpose2d wrapper expects 1 output, got {}",
4188                    outputs.len(),
4189                ))
4190                .bt());
4191            }
4192            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) =
4193                match params {
4194                    OpParams::ConvTranspose2D {
4195                        x_shape,
4196                        w_shape,
4197                        out_shape,
4198                        stride,
4199                        padding,
4200                        output_padding: _,
4201                        dilation,
4202                        groups,
4203                    } => (
4204                        *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4205                    ),
4206                    other => return Err(Error::Msg(format!(
4207                        "conv_transpose2d wrapper expects OpParams::ConvTranspose2D, got {other:?}",
4208                    ))
4209                    .bt()),
4210                };
4211            let x_guard = read_storage(&inputs[0])?;
4212            let w_guard = read_storage(&inputs[1])?;
4213            let bias_guard = match inputs.get(2) {
4214                Some(arc) => Some(read_storage(arc)?),
4215                None => None,
4216            };
4217            let mut out_guard = write_storage(&outputs[0])?;
4218            let x_cpu = cpu_input(&x_guard)?;
4219            let w_cpu = cpu_input(&w_guard)?;
4220            let bias_cpu = match &bias_guard {
4221                Some(g) => Some(cpu_input(g)?),
4222                None => None,
4223            };
4224            let out_cpu = cpu_output(&mut out_guard)?;
4225            $kernel(
4226                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4227                dilation, groups,
4228            )
4229        }
4230    };
4231}
4232
4233cpu_conv_transpose2d_wrapper!(
4234    conv_transpose2d_f32_cpu_wrapper,
4235    fuel_cpu_backend::byte_kernels::conv_transpose2d_f32
4236);
4237cpu_conv_transpose2d_wrapper!(
4238    conv_transpose2d_f64_cpu_wrapper,
4239    fuel_cpu_backend::byte_kernels::conv_transpose2d_f64
4240);
4241cpu_conv_transpose2d_wrapper!(
4242    conv_transpose2d_bf16_cpu_wrapper,
4243    fuel_cpu_backend::byte_kernels::conv_transpose2d_bf16
4244);
4245cpu_conv_transpose2d_wrapper!(
4246    conv_transpose2d_f16_cpu_wrapper,
4247    fuel_cpu_backend::byte_kernels::conv_transpose2d_f16
4248);
4249
4250/// Dispatch wrapper for `(ReduceSumTo, *, Cpu)`. Single input → single
4251/// output; shapes flow through `OpParams::ReduceSumTo`.
4252/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4253/// production wrapper and the importer can bind it FROM the contract.
4254macro_rules! cpu_reduce_sum_to_wrapper {
4255    ($name:ident, $kernel:path) => {
4256        pub(crate) fn $name(
4257            inputs: &[Arc<RwLock<Storage>>],
4258            outputs: &mut [Arc<RwLock<Storage>>],
4259            _layouts: &[Layout],
4260            params: &OpParams,
4261        ) -> Result<()> {
4262            if inputs.len() != 1 {
4263                return Err(Error::Msg(format!(
4264                    "reduce_sum_to wrapper expects 1 input, got {}",
4265                    inputs.len(),
4266                ))
4267                .bt());
4268            }
4269            if outputs.len() != 1 {
4270                return Err(Error::Msg(format!(
4271                    "reduce_sum_to wrapper expects 1 output, got {}",
4272                    outputs.len(),
4273                ))
4274                .bt());
4275            }
4276            let (input_shape, output_shape) = match params {
4277                OpParams::ReduceSumTo {
4278                    input_shape,
4279                    output_shape,
4280                } => (input_shape.clone(), output_shape.clone()),
4281                other => {
4282                    return Err(Error::Msg(format!(
4283                        "reduce_sum_to wrapper expects OpParams::ReduceSumTo, got {other:?}",
4284                    ))
4285                    .bt())
4286                }
4287            };
4288            let in_guard = read_storage(&inputs[0])?;
4289            let mut out_guard = write_storage(&outputs[0])?;
4290            let in_cpu = cpu_input(&in_guard)?;
4291            let out_cpu = cpu_output(&mut out_guard)?;
4292            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4293        }
4294    };
4295}
4296
4297cpu_reduce_sum_to_wrapper!(
4298    reduce_sum_to_f32_cpu_wrapper,
4299    fuel_cpu_backend::byte_kernels::reduce_sum_to_f32
4300);
4301cpu_reduce_sum_to_wrapper!(
4302    reduce_sum_to_f64_cpu_wrapper,
4303    fuel_cpu_backend::byte_kernels::reduce_sum_to_f64
4304);
4305cpu_reduce_sum_to_wrapper!(
4306    reduce_sum_to_bf16_cpu_wrapper,
4307    fuel_cpu_backend::byte_kernels::reduce_sum_to_bf16
4308);
4309cpu_reduce_sum_to_wrapper!(
4310    reduce_sum_to_f16_cpu_wrapper,
4311    fuel_cpu_backend::byte_kernels::reduce_sum_to_f16
4312);
4313
4314/// Dispatch wrapper for `(ReduceMaxTo, *, Cpu)`. Single input → single
4315/// output; shapes flow through `OpParams::ReduceMaxTo`.
4316/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4317/// production wrapper and the importer can bind it FROM the contract.
4318macro_rules! cpu_reduce_max_to_wrapper {
4319    ($name:ident, $kernel:path) => {
4320        pub(crate) fn $name(
4321            inputs: &[Arc<RwLock<Storage>>],
4322            outputs: &mut [Arc<RwLock<Storage>>],
4323            _layouts: &[Layout],
4324            params: &OpParams,
4325        ) -> Result<()> {
4326            if inputs.len() != 1 {
4327                return Err(Error::Msg(format!(
4328                    "reduce_max_to wrapper expects 1 input, got {}",
4329                    inputs.len(),
4330                ))
4331                .bt());
4332            }
4333            if outputs.len() != 1 {
4334                return Err(Error::Msg(format!(
4335                    "reduce_max_to wrapper expects 1 output, got {}",
4336                    outputs.len(),
4337                ))
4338                .bt());
4339            }
4340            let (input_shape, output_shape) = match params {
4341                OpParams::ReduceMaxTo {
4342                    input_shape,
4343                    output_shape,
4344                } => (input_shape.clone(), output_shape.clone()),
4345                other => {
4346                    return Err(Error::Msg(format!(
4347                        "reduce_max_to wrapper expects OpParams::ReduceMaxTo, got {other:?}",
4348                    ))
4349                    .bt())
4350                }
4351            };
4352            let in_guard = read_storage(&inputs[0])?;
4353            let mut out_guard = write_storage(&outputs[0])?;
4354            let in_cpu = cpu_input(&in_guard)?;
4355            let out_cpu = cpu_output(&mut out_guard)?;
4356            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4357        }
4358    };
4359}
4360
4361cpu_reduce_max_to_wrapper!(
4362    reduce_max_to_f32_cpu_wrapper,
4363    fuel_cpu_backend::byte_kernels::reduce_max_to_f32
4364);
4365cpu_reduce_max_to_wrapper!(
4366    reduce_max_to_f64_cpu_wrapper,
4367    fuel_cpu_backend::byte_kernels::reduce_max_to_f64
4368);
4369cpu_reduce_max_to_wrapper!(
4370    reduce_max_to_bf16_cpu_wrapper,
4371    fuel_cpu_backend::byte_kernels::reduce_max_to_bf16
4372);
4373cpu_reduce_max_to_wrapper!(
4374    reduce_max_to_f16_cpu_wrapper,
4375    fuel_cpu_backend::byte_kernels::reduce_max_to_f16
4376);
4377
4378/// Dispatch wrapper for `(FusedLinear, *, Cpu)`. Three inputs
4379/// (lhs, rhs, bias). Reuses `OpParams::Matmul` for shape.
4380macro_rules! cpu_fused_linear_wrapper {
4381    ($wrapper:ident, $kernel:path) => {
4382        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
4383        // contract's `fused_linear_<dt>` `entry_point` symbols to these wrappers.
4384        pub(crate) fn $wrapper(
4385            inputs: &[Arc<RwLock<Storage>>],
4386            outputs: &mut [Arc<RwLock<Storage>>],
4387            _layouts: &[Layout],
4388            params: &OpParams,
4389        ) -> Result<()> {
4390            if inputs.len() != 3 {
4391                return Err(Error::Msg(format!(
4392                    "fused_linear wrapper expects 3 inputs (lhs, rhs, bias), got {}",
4393                    inputs.len(),
4394                ))
4395                .bt());
4396            }
4397            if outputs.len() != 1 {
4398                return Err(Error::Msg(format!(
4399                    "fused_linear wrapper expects 1 output, got {}",
4400                    outputs.len(),
4401                ))
4402                .bt());
4403            }
4404            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
4405                OpParams::Matmul {
4406                    lhs_batch_dims,
4407                    rhs_batch_dims,
4408                    m,
4409                    n,
4410                    k,
4411                    ..
4412                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
4413                other => {
4414                    return Err(Error::Msg(format!(
4415                        "fused_linear wrapper expects OpParams::Matmul, got {other:?}",
4416                    ))
4417                    .bt())
4418                }
4419            };
4420            let lhs_guard = read_storage(&inputs[0])?;
4421            let rhs_guard = read_storage(&inputs[1])?;
4422            let bias_guard = read_storage(&inputs[2])?;
4423            let mut out_guard = write_storage(&outputs[0])?;
4424            let lhs_cpu = cpu_input(&lhs_guard)?;
4425            let rhs_cpu = cpu_input(&rhs_guard)?;
4426            let bias_cpu = cpu_input(&bias_guard)?;
4427            let out_cpu = cpu_output(&mut out_guard)?;
4428            $kernel(
4429                lhs_cpu,
4430                rhs_cpu,
4431                bias_cpu,
4432                out_cpu,
4433                lhs_batch_dims,
4434                rhs_batch_dims,
4435                m,
4436                n,
4437                k,
4438            )
4439        }
4440    };
4441}
4442
4443cpu_fused_linear_wrapper!(
4444    fused_linear_f32_cpu_wrapper,
4445    fuel_cpu_backend::byte_kernels::fused_linear_f32
4446);
4447cpu_fused_linear_wrapper!(
4448    fused_linear_f64_cpu_wrapper,
4449    fuel_cpu_backend::byte_kernels::fused_linear_f64
4450);
4451cpu_fused_linear_wrapper!(
4452    fused_linear_bf16_cpu_wrapper,
4453    fuel_cpu_backend::byte_kernels::fused_linear_bf16
4454);
4455cpu_fused_linear_wrapper!(
4456    fused_linear_f16_cpu_wrapper,
4457    fuel_cpu_backend::byte_kernels::fused_linear_f16
4458);
4459
4460// RowScaledMatMul (row 172 item 1): same `(a, b, third, out)` + `OpParams::Matmul`
4461// shape as FusedLinear; the third input is the `[..., M, 1]` row scale.
4462cpu_fused_linear_wrapper!(
4463    row_scaled_matmul_f32_cpu_wrapper,
4464    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f32
4465);
4466cpu_fused_linear_wrapper!(
4467    row_scaled_matmul_f64_cpu_wrapper,
4468    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f64
4469);
4470cpu_fused_linear_wrapper!(
4471    row_scaled_matmul_bf16_cpu_wrapper,
4472    fuel_cpu_backend::byte_kernels::row_scaled_matmul_bf16
4473);
4474cpu_fused_linear_wrapper!(
4475    row_scaled_matmul_f16_cpu_wrapper,
4476    fuel_cpu_backend::byte_kernels::row_scaled_matmul_f16
4477);
4478
4479/// Per-dtype FusedSoftmaxCrossEntropy dispatch wrapper. Two inputs
4480/// (logits T, targets I64) → one F32 output (the FSCE declared dtype,
4481/// regardless of logits dtype — losses accumulate in f64, narrow to
4482/// f32). Translates the `Reduction` enum from the FusedOpParams
4483/// payload (which lives on the graph node) to the kernel's `u8` tag —
4484/// the kernel intentionally stays free of fuel-graph dependencies.
4485macro_rules! cpu_fused_softmax_cross_entropy_wrapper {
4486    ($wrapper:ident, $kernel:path) => {
4487        pub(crate) fn $wrapper(
4488            inputs: &[Arc<RwLock<Storage>>],
4489            outputs: &mut [Arc<RwLock<Storage>>],
4490            _layouts: &[Layout],
4491            params: &OpParams,
4492        ) -> Result<()> {
4493            if inputs.len() != 2 {
4494                return Err(Error::Msg(format!(
4495                    "fused_softmax_cross_entropy wrapper expects 2 inputs (logits, targets), got {}",
4496                    inputs.len(),
4497                ))
4498                .bt());
4499            }
4500            if outputs.len() != 1 {
4501                return Err(Error::Msg(format!(
4502                    "fused_softmax_cross_entropy wrapper expects 1 output, got {}",
4503                    outputs.len(),
4504                ))
4505                .bt());
4506            }
4507            let (n_rows, vocab, reduction, ignore_index) = match params {
4508                OpParams::FusedSoftmaxCrossEntropy {
4509                    n_rows, vocab, reduction, ignore_index,
4510                } => (*n_rows, *vocab, *reduction, *ignore_index),
4511                other => {
4512                    return Err(Error::Msg(format!(
4513                        "fused_softmax_cross_entropy wrapper expects \
4514                         OpParams::FusedSoftmaxCrossEntropy, got {other:?}",
4515                    ))
4516                    .bt());
4517                }
4518            };
4519            let reduction_tag = match reduction {
4520                fuel_graph::registry::Reduction::Mean => fuel_cpu_backend::byte_kernels::REDUCTION_MEAN,
4521                fuel_graph::registry::Reduction::Sum  => fuel_cpu_backend::byte_kernels::REDUCTION_SUM,
4522                fuel_graph::registry::Reduction::None => fuel_cpu_backend::byte_kernels::REDUCTION_NONE,
4523            };
4524            let logits_guard = read_storage(&inputs[0])?;
4525            let targets_guard = read_storage(&inputs[1])?;
4526            let mut out_guard = write_storage(&outputs[0])?;
4527            let logits_cpu = cpu_input(&logits_guard)?;
4528            let targets_cpu = cpu_input(&targets_guard)?;
4529            let out_cpu = cpu_output(&mut out_guard)?;
4530            $kernel(
4531                logits_cpu, targets_cpu, out_cpu,
4532                n_rows, vocab, reduction_tag, ignore_index,
4533            )
4534        }
4535    };
4536}
4537
4538cpu_fused_softmax_cross_entropy_wrapper!(
4539    fused_softmax_cross_entropy_f32_cpu_wrapper,
4540    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f32
4541);
4542cpu_fused_softmax_cross_entropy_wrapper!(
4543    fused_softmax_cross_entropy_f64_cpu_wrapper,
4544    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f64
4545);
4546cpu_fused_softmax_cross_entropy_wrapper!(
4547    fused_softmax_cross_entropy_bf16_cpu_wrapper,
4548    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_bf16
4549);
4550cpu_fused_softmax_cross_entropy_wrapper!(
4551    fused_softmax_cross_entropy_f16_cpu_wrapper,
4552    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f16
4553);
4554
4555/// Per-dtype CausalConv1d dispatch wrapper. Three inputs (x, weight,
4556/// bias) → one output. Geometry + `use_silu` flow through
4557/// `OpParams::CausalConv1d`. All four inputs/outputs share the same
4558/// dtype `T`; the binding-table key is `[T, T, T, T]`.
4559macro_rules! cpu_causal_conv1d_wrapper {
4560    ($wrapper:ident, $kernel:path) => {
4561        pub(crate) fn $wrapper(
4562            inputs: &[Arc<RwLock<Storage>>],
4563            outputs: &mut [Arc<RwLock<Storage>>],
4564            _layouts: &[Layout],
4565            params: &OpParams,
4566        ) -> Result<()> {
4567            if inputs.len() != 3 {
4568                return Err(Error::Msg(format!(
4569                    "causal_conv1d wrapper expects 3 inputs (x, weight, bias), got {}",
4570                    inputs.len(),
4571                ))
4572                .bt());
4573            }
4574            if outputs.len() != 1 {
4575                return Err(Error::Msg(format!(
4576                    "causal_conv1d wrapper expects 1 output, got {}",
4577                    outputs.len(),
4578                ))
4579                .bt());
4580            }
4581            let (batch, channels, seq_in, seq_out, kernel, use_silu) = match params {
4582                OpParams::CausalConv1d {
4583                    batch,
4584                    channels,
4585                    seq_in,
4586                    seq_out,
4587                    kernel,
4588                    use_silu,
4589                } => (*batch, *channels, *seq_in, *seq_out, *kernel, *use_silu),
4590                other => {
4591                    return Err(Error::Msg(format!(
4592                        "causal_conv1d wrapper expects OpParams::CausalConv1d, got {other:?}",
4593                    ))
4594                    .bt());
4595                }
4596            };
4597            let x_guard = read_storage(&inputs[0])?;
4598            let w_guard = read_storage(&inputs[1])?;
4599            let bias_guard = read_storage(&inputs[2])?;
4600            let mut out_guard = write_storage(&outputs[0])?;
4601            let x_cpu = cpu_input(&x_guard)?;
4602            let w_cpu = cpu_input(&w_guard)?;
4603            let bias_cpu = cpu_input(&bias_guard)?;
4604            let out_cpu = cpu_output(&mut out_guard)?;
4605            $kernel(
4606                x_cpu, w_cpu, bias_cpu, out_cpu, batch, channels, seq_in, seq_out, kernel, use_silu,
4607            )
4608        }
4609    };
4610}
4611
4612cpu_causal_conv1d_wrapper!(
4613    causal_conv1d_f32_cpu_wrapper,
4614    fuel_cpu_backend::byte_kernels::causal_conv1d_f32
4615);
4616cpu_causal_conv1d_wrapper!(
4617    causal_conv1d_f64_cpu_wrapper,
4618    fuel_cpu_backend::byte_kernels::causal_conv1d_f64
4619);
4620cpu_causal_conv1d_wrapper!(
4621    causal_conv1d_bf16_cpu_wrapper,
4622    fuel_cpu_backend::byte_kernels::causal_conv1d_bf16
4623);
4624cpu_causal_conv1d_wrapper!(
4625    causal_conv1d_f16_cpu_wrapper,
4626    fuel_cpu_backend::byte_kernels::causal_conv1d_f16
4627);
4628
4629/// Per-dtype SelectiveScan dispatch wrapper. Five inputs (u, delta,
4630/// a, b, c) → one output (y). Geometry + `delta_softplus` flow
4631/// through `OpParams::SelectiveScan`. All six tensors share dtype `T`;
4632/// the binding-table key is `[T; 6]`.
4633macro_rules! cpu_selective_scan_wrapper {
4634    ($wrapper:ident, $kernel:path) => {
4635        pub(crate) fn $wrapper(
4636            inputs: &[Arc<RwLock<Storage>>],
4637            outputs: &mut [Arc<RwLock<Storage>>],
4638            _layouts: &[Layout],
4639            params: &OpParams,
4640        ) -> Result<()> {
4641            if inputs.len() != 5 {
4642                return Err(Error::Msg(format!(
4643                    "selective_scan wrapper expects 5 inputs (u, delta, a, b, c), got {}",
4644                    inputs.len(),
4645                ))
4646                .bt());
4647            }
4648            if outputs.len() != 1 {
4649                return Err(Error::Msg(format!(
4650                    "selective_scan wrapper expects 1 output, got {}",
4651                    outputs.len(),
4652                ))
4653                .bt());
4654            }
4655            let (batch, seqlen, dim, dstate, delta_softplus) = match params {
4656                OpParams::SelectiveScan {
4657                    batch,
4658                    seqlen,
4659                    dim,
4660                    dstate,
4661                    delta_softplus,
4662                } => (*batch, *seqlen, *dim, *dstate, *delta_softplus),
4663                other => {
4664                    return Err(Error::Msg(format!(
4665                        "selective_scan wrapper expects OpParams::SelectiveScan, got {other:?}",
4666                    ))
4667                    .bt());
4668                }
4669            };
4670            let u_guard = read_storage(&inputs[0])?;
4671            let delta_guard = read_storage(&inputs[1])?;
4672            let a_guard = read_storage(&inputs[2])?;
4673            let b_guard = read_storage(&inputs[3])?;
4674            let c_guard = read_storage(&inputs[4])?;
4675            let mut out_guard = write_storage(&outputs[0])?;
4676            let u_cpu = cpu_input(&u_guard)?;
4677            let delta_cpu = cpu_input(&delta_guard)?;
4678            let a_cpu = cpu_input(&a_guard)?;
4679            let b_cpu = cpu_input(&b_guard)?;
4680            let c_cpu = cpu_input(&c_guard)?;
4681            let out_cpu = cpu_output(&mut out_guard)?;
4682            $kernel(
4683                u_cpu,
4684                delta_cpu,
4685                a_cpu,
4686                b_cpu,
4687                c_cpu,
4688                out_cpu,
4689                batch,
4690                seqlen,
4691                dim,
4692                dstate,
4693                delta_softplus,
4694            )
4695        }
4696    };
4697}
4698
4699/// TopKLastDim dispatch wrapper (row 172 item 2). One input `x [.., n]`, ONE
4700/// bundled output `[values ; pad to 4 ; indices]`; the kernel writes both slots.
4701macro_rules! cpu_top_k_last_dim_wrapper {
4702    ($wrapper:ident, $kernel:path) => {
4703        pub(crate) fn $wrapper(
4704            inputs: &[Arc<RwLock<Storage>>],
4705            outputs: &mut [Arc<RwLock<Storage>>],
4706            _layouts: &[Layout],
4707            params: &OpParams,
4708        ) -> Result<()> {
4709            if inputs.len() != 1 || outputs.len() != 1 {
4710                return Err(Error::Msg(format!(
4711                    "top_k_last_dim wrapper expects 1 input and 1 (bundled) output, got {} and {}",
4712                    inputs.len(),
4713                    outputs.len(),
4714                ))
4715                .bt());
4716            }
4717            let (rows, n, k) = match params {
4718                OpParams::TopKLastDim { rows, n, k } => (*rows, *n, *k),
4719                other => {
4720                    return Err(Error::Msg(format!(
4721                        "top_k_last_dim wrapper expects OpParams::TopKLastDim, got {other:?}",
4722                    ))
4723                    .bt());
4724                }
4725            };
4726            let x_guard = read_storage(&inputs[0])?;
4727            let mut out_guard = write_storage(&outputs[0])?;
4728            let x_cpu = cpu_input(&x_guard)?;
4729            let out_cpu = cpu_output(&mut out_guard)?;
4730            $kernel(x_cpu, out_cpu, rows, n, k)
4731        }
4732    };
4733}
4734
4735cpu_top_k_last_dim_wrapper!(
4736    top_k_last_dim_f32_cpu_wrapper,
4737    fuel_cpu_backend::byte_kernels::top_k_last_dim_f32
4738);
4739cpu_top_k_last_dim_wrapper!(
4740    top_k_last_dim_f64_cpu_wrapper,
4741    fuel_cpu_backend::byte_kernels::top_k_last_dim_f64
4742);
4743cpu_top_k_last_dim_wrapper!(
4744    top_k_last_dim_bf16_cpu_wrapper,
4745    fuel_cpu_backend::byte_kernels::top_k_last_dim_bf16
4746);
4747cpu_top_k_last_dim_wrapper!(
4748    top_k_last_dim_f16_cpu_wrapper,
4749    fuel_cpu_backend::byte_kernels::top_k_last_dim_f16
4750);
4751
4752/// MatMulTopK dispatch wrapper (row 172 item 2 step B). Inputs `a`, `b`; ONE
4753/// bundled output `[values ; pad to 4 ; indices]`.
4754macro_rules! cpu_matmul_top_k_wrapper {
4755    ($wrapper:ident, $kernel:path) => {
4756        pub(crate) fn $wrapper(
4757            inputs: &[Arc<RwLock<Storage>>],
4758            outputs: &mut [Arc<RwLock<Storage>>],
4759            _layouts: &[Layout],
4760            params: &OpParams,
4761        ) -> Result<()> {
4762            if inputs.len() != 2 || outputs.len() != 1 {
4763                return Err(Error::Msg(format!(
4764                    "matmul_top_k wrapper expects 2 inputs and 1 (bundled) output, got {} and {}",
4765                    inputs.len(),
4766                    outputs.len(),
4767                ))
4768                .bt());
4769            }
4770            let (batch, m, n, k, top_k) = match params {
4771                OpParams::MatMulTopK {
4772                    batch,
4773                    m,
4774                    n,
4775                    k,
4776                    top_k,
4777                } => (*batch, *m, *n, *k, *top_k),
4778                other => {
4779                    return Err(Error::Msg(format!(
4780                        "matmul_top_k wrapper expects OpParams::MatMulTopK, got {other:?}",
4781                    ))
4782                    .bt());
4783                }
4784            };
4785            let lhs_guard = read_storage(&inputs[0])?;
4786            let rhs_guard = read_storage(&inputs[1])?;
4787            let mut out_guard = write_storage(&outputs[0])?;
4788            let lhs_cpu = cpu_input(&lhs_guard)?;
4789            let rhs_cpu = cpu_input(&rhs_guard)?;
4790            let out_cpu = cpu_output(&mut out_guard)?;
4791            $kernel(lhs_cpu, rhs_cpu, out_cpu, batch, m, n, k, top_k)
4792        }
4793    };
4794}
4795
4796cpu_matmul_top_k_wrapper!(
4797    matmul_top_k_f32_cpu_wrapper,
4798    fuel_cpu_backend::byte_kernels::matmul_top_k_f32
4799);
4800cpu_matmul_top_k_wrapper!(
4801    matmul_top_k_f64_cpu_wrapper,
4802    fuel_cpu_backend::byte_kernels::matmul_top_k_f64
4803);
4804cpu_matmul_top_k_wrapper!(
4805    matmul_top_k_bf16_cpu_wrapper,
4806    fuel_cpu_backend::byte_kernels::matmul_top_k_bf16
4807);
4808cpu_matmul_top_k_wrapper!(
4809    matmul_top_k_f16_cpu_wrapper,
4810    fuel_cpu_backend::byte_kernels::matmul_top_k_f16
4811);
4812
4813cpu_selective_scan_wrapper!(
4814    selective_scan_f32_cpu_wrapper,
4815    fuel_cpu_backend::byte_kernels::selective_scan_f32
4816);
4817cpu_selective_scan_wrapper!(
4818    selective_scan_f64_cpu_wrapper,
4819    fuel_cpu_backend::byte_kernels::selective_scan_f64
4820);
4821cpu_selective_scan_wrapper!(
4822    selective_scan_bf16_cpu_wrapper,
4823    fuel_cpu_backend::byte_kernels::selective_scan_bf16
4824);
4825cpu_selective_scan_wrapper!(
4826    selective_scan_f16_cpu_wrapper,
4827    fuel_cpu_backend::byte_kernels::selective_scan_f16
4828);
4829
4830/// Per-input-dtype NonZeroIndices dispatch wrapper. One input `x`
4831/// (the value tensor) → one bundled output `[indices [capacity] U32 ;
4832/// count [1] U32]`. `capacity` flows through `OpParams::NonZeroIndices`;
4833/// the binding-table key is `[input_dtype, U32]` (input + the primary
4834/// output-slot dtype). The `count_sym` field is consumed by the executor
4835/// after the kernel runs (the SymEnv bind seam), not here.
4836macro_rules! cpu_nonzero_indices_wrapper {
4837    ($wrapper:ident, $kernel:path) => {
4838        pub(crate) fn $wrapper(
4839            inputs: &[Arc<RwLock<Storage>>],
4840            outputs: &mut [Arc<RwLock<Storage>>],
4841            _layouts: &[Layout],
4842            params: &OpParams,
4843        ) -> Result<()> {
4844            if inputs.len() != 1 {
4845                return Err(Error::Msg(format!(
4846                    "nonzero_indices wrapper expects 1 input, got {}",
4847                    inputs.len(),
4848                ))
4849                .bt());
4850            }
4851            if outputs.len() != 1 {
4852                return Err(Error::Msg(format!(
4853                    "nonzero_indices wrapper expects 1 output, got {}",
4854                    outputs.len(),
4855                ))
4856                .bt());
4857            }
4858            let capacity = match params {
4859                OpParams::NonZeroIndices { capacity, .. } => *capacity,
4860                other => {
4861                    return Err(Error::Msg(format!(
4862                        "nonzero_indices wrapper expects OpParams::NonZeroIndices, got {other:?}",
4863                    ))
4864                    .bt());
4865                }
4866            };
4867            let x_guard = read_storage(&inputs[0])?;
4868            let mut out_guard = write_storage(&outputs[0])?;
4869            let x_cpu = cpu_input(&x_guard)?;
4870            let out_cpu = cpu_output(&mut out_guard)?;
4871            $kernel(x_cpu, out_cpu, capacity)
4872        }
4873    };
4874}
4875
4876cpu_nonzero_indices_wrapper!(
4877    nonzero_indices_f32_cpu_wrapper,
4878    fuel_cpu_backend::byte_kernels::nonzero_indices_f32
4879);
4880cpu_nonzero_indices_wrapper!(
4881    nonzero_indices_u32_cpu_wrapper,
4882    fuel_cpu_backend::byte_kernels::nonzero_indices_u32
4883);
4884
4885/// Per-dtype SsdChunkScan dispatch wrapper. Five inputs (x, dt, a,
4886/// b, c) → one output (y). Geometry + `chunk_size` flow through
4887/// `OpParams::SsdChunkScan`. All six tensors share dtype `T`; the
4888/// binding-table key is `[T; 6]`.
4889macro_rules! cpu_ssd_chunk_scan_wrapper {
4890    ($wrapper:ident, $kernel:path) => {
4891        pub(crate) fn $wrapper(
4892            inputs: &[Arc<RwLock<Storage>>],
4893            outputs: &mut [Arc<RwLock<Storage>>],
4894            _layouts: &[Layout],
4895            params: &OpParams,
4896        ) -> Result<()> {
4897            if inputs.len() != 5 {
4898                return Err(Error::Msg(format!(
4899                    "ssd_chunk_scan wrapper expects 5 inputs (x, dt, a, b, c), got {}",
4900                    inputs.len(),
4901                ))
4902                .bt());
4903            }
4904            if outputs.len() != 1 {
4905                return Err(Error::Msg(format!(
4906                    "ssd_chunk_scan wrapper expects 1 output, got {}",
4907                    outputs.len(),
4908                ))
4909                .bt());
4910            }
4911            let (batch, seqlen, heads, head_dim, state_dim, chunk_size) = match params {
4912                OpParams::SsdChunkScan {
4913                    batch,
4914                    seqlen,
4915                    heads,
4916                    head_dim,
4917                    state_dim,
4918                    chunk_size,
4919                } => (*batch, *seqlen, *heads, *head_dim, *state_dim, *chunk_size),
4920                other => {
4921                    return Err(Error::Msg(format!(
4922                        "ssd_chunk_scan wrapper expects OpParams::SsdChunkScan, got {other:?}",
4923                    ))
4924                    .bt());
4925                }
4926            };
4927            let x_guard = read_storage(&inputs[0])?;
4928            let dt_guard = read_storage(&inputs[1])?;
4929            let a_guard = read_storage(&inputs[2])?;
4930            let b_guard = read_storage(&inputs[3])?;
4931            let c_guard = read_storage(&inputs[4])?;
4932            let mut out_guard = write_storage(&outputs[0])?;
4933            let x_cpu = cpu_input(&x_guard)?;
4934            let dt_cpu = cpu_input(&dt_guard)?;
4935            let a_cpu = cpu_input(&a_guard)?;
4936            let b_cpu = cpu_input(&b_guard)?;
4937            let c_cpu = cpu_input(&c_guard)?;
4938            let out_cpu = cpu_output(&mut out_guard)?;
4939            $kernel(
4940                x_cpu, dt_cpu, a_cpu, b_cpu, c_cpu, out_cpu, batch, seqlen, heads, head_dim,
4941                state_dim, chunk_size,
4942            )
4943        }
4944    };
4945}
4946
4947cpu_ssd_chunk_scan_wrapper!(
4948    ssd_chunk_scan_f32_cpu_wrapper,
4949    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f32
4950);
4951cpu_ssd_chunk_scan_wrapper!(
4952    ssd_chunk_scan_f64_cpu_wrapper,
4953    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f64
4954);
4955cpu_ssd_chunk_scan_wrapper!(
4956    ssd_chunk_scan_bf16_cpu_wrapper,
4957    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_bf16
4958);
4959cpu_ssd_chunk_scan_wrapper!(
4960    ssd_chunk_scan_f16_cpu_wrapper,
4961    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f16
4962);
4963
4964/// Per-dtype Nf4Matmul wrapper. Three inputs (activations, w_packed
4965/// U8, absmax F32) → one output of the activations' dtype.
4966/// `block_size` flows through `OpParams::Nf4Matmul`.
4967macro_rules! cpu_nf4_matmul_wrapper {
4968    ($wrapper:ident, $kernel:path) => {
4969        fn $wrapper(
4970            inputs: &[Arc<RwLock<Storage>>],
4971            outputs: &mut [Arc<RwLock<Storage>>],
4972            _layouts: &[Layout],
4973            params: &OpParams,
4974        ) -> Result<()> {
4975            if inputs.len() != 3 {
4976                return Err(Error::Msg(format!(
4977                    "nf4_matmul wrapper expects 3 inputs (activations, w_packed, absmax), got {}",
4978                    inputs.len(),
4979                ))
4980                .bt());
4981            }
4982            if outputs.len() != 1 {
4983                return Err(Error::Msg(format!(
4984                    "nf4_matmul wrapper expects 1 output, got {}",
4985                    outputs.len(),
4986                ))
4987                .bt());
4988            }
4989            let (batch, m, n, k, block_size) = match params {
4990                OpParams::Nf4Matmul {
4991                    batch,
4992                    m,
4993                    n,
4994                    k,
4995                    block_size,
4996                } => (*batch, *m, *n, *k, *block_size),
4997                other => {
4998                    return Err(Error::Msg(format!(
4999                        "nf4_matmul wrapper expects OpParams::Nf4Matmul, got {other:?}",
5000                    ))
5001                    .bt());
5002                }
5003            };
5004            let a_guard = read_storage(&inputs[0])?;
5005            let w_guard = read_storage(&inputs[1])?;
5006            let abs_guard = read_storage(&inputs[2])?;
5007            let mut out_guard = write_storage(&outputs[0])?;
5008            let a_cpu = cpu_input(&a_guard)?;
5009            let w_cpu = cpu_input(&w_guard)?;
5010            let abs_cpu = cpu_input(&abs_guard)?;
5011            let out_cpu = cpu_output(&mut out_guard)?;
5012            $kernel(a_cpu, w_cpu, abs_cpu, out_cpu, batch, m, n, k, block_size)
5013        }
5014    };
5015}
5016
5017cpu_nf4_matmul_wrapper!(
5018    nf4_matmul_f32_cpu_wrapper,
5019    fuel_cpu_backend::byte_kernels::nf4_matmul_f32
5020);
5021cpu_nf4_matmul_wrapper!(
5022    nf4_matmul_f16_cpu_wrapper,
5023    fuel_cpu_backend::byte_kernels::nf4_matmul_f16
5024);
5025cpu_nf4_matmul_wrapper!(
5026    nf4_matmul_bf16_cpu_wrapper,
5027    fuel_cpu_backend::byte_kernels::nf4_matmul_bf16
5028);
5029
5030/// Dispatch wrapper for `(FlashAttn, *, Cpu)`. Three or four inputs
5031/// (q, k, v, optional alibi_slopes). Geometry + math params flow
5032/// through `OpParams::FlashAttn`.
5033macro_rules! cpu_flash_attn_wrapper {
5034    ($wrapper:ident, $kernel:path) => {
5035        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
5036        // contract's forward-FlashAttn `entry_point` symbols to these wrappers.
5037        pub(crate) fn $wrapper(
5038            inputs: &[Arc<RwLock<Storage>>],
5039            outputs: &mut [Arc<RwLock<Storage>>],
5040            _layouts: &[Layout],
5041            params: &OpParams,
5042        ) -> Result<()> {
5043            if inputs.len() != 3 && inputs.len() != 4 {
5044                return Err(Error::Msg(format!(
5045                    "flash_attn wrapper expects 3 or 4 inputs (q, k, v, [alibi]), got {}",
5046                    inputs.len(),
5047                ))
5048                .bt());
5049            }
5050            if outputs.len() != 1 {
5051                return Err(Error::Msg(format!(
5052                    "flash_attn wrapper expects 1 output, got {}",
5053                    outputs.len(),
5054                ))
5055                .bt());
5056            }
5057            let (b, hq, hkv, sq, sk, d, k_len, scale, causal, wl, wr, softcap) = match params {
5058                OpParams::FlashAttn {
5059                    b,
5060                    hq,
5061                    hkv,
5062                    sq,
5063                    sk,
5064                    d,
5065                    k_len,
5066                    softmax_scale,
5067                    causal,
5068                    window_size_left,
5069                    window_size_right,
5070                    softcap,
5071                } => (
5072                    *b,
5073                    *hq,
5074                    *hkv,
5075                    *sq,
5076                    *sk,
5077                    *d,
5078                    *k_len,
5079                    *softmax_scale,
5080                    *causal,
5081                    *window_size_left,
5082                    *window_size_right,
5083                    *softcap,
5084                ),
5085                other => {
5086                    return Err(Error::Msg(format!(
5087                        "flash_attn wrapper expects OpParams::FlashAttn, got {other:?}",
5088                    ))
5089                    .bt())
5090                }
5091            };
5092            let q_guard = read_storage(&inputs[0])?;
5093            let k_guard = read_storage(&inputs[1])?;
5094            let v_guard = read_storage(&inputs[2])?;
5095            let alibi_guard = match inputs.get(3) {
5096                Some(arc) => Some(read_storage(arc)?),
5097                None => None,
5098            };
5099            let mut out_guard = write_storage(&outputs[0])?;
5100            let q_cpu = cpu_input(&q_guard)?;
5101            let k_cpu = cpu_input(&k_guard)?;
5102            let v_cpu = cpu_input(&v_guard)?;
5103            let alibi_cpu = match &alibi_guard {
5104                Some(g) => Some(cpu_input(g)?),
5105                None => None,
5106            };
5107            let out_cpu = cpu_output(&mut out_guard)?;
5108            $kernel(
5109                q_cpu, k_cpu, v_cpu, alibi_cpu, out_cpu, b, hq, hkv, sq, sk, d, k_len, scale,
5110                causal, wl, wr, softcap,
5111            )
5112        }
5113    };
5114}
5115
5116cpu_flash_attn_wrapper!(
5117    flash_attn_f32_cpu_wrapper,
5118    fuel_cpu_backend::byte_kernels::flash_attn_f32
5119);
5120cpu_flash_attn_wrapper!(
5121    flash_attn_f64_cpu_wrapper,
5122    fuel_cpu_backend::byte_kernels::flash_attn_f64
5123);
5124cpu_flash_attn_wrapper!(
5125    flash_attn_bf16_cpu_wrapper,
5126    fuel_cpu_backend::byte_kernels::flash_attn_bf16
5127);
5128cpu_flash_attn_wrapper!(
5129    flash_attn_f16_cpu_wrapper,
5130    fuel_cpu_backend::byte_kernels::flash_attn_f16
5131);
5132
5133/// Dispatch wrapper for `(FlashAttnBackward{Q,K,V}, *, Cpu)`. Four or
5134/// five inputs `(q, k, v, do, [alibi])`; one output (one of dQ/dK/dV).
5135/// The CPU kernel always computes all three gradients; this wrapper
5136/// only persists the requested one.
5137macro_rules! cpu_flash_attn_backward_wrapper {
5138    ($wrapper:ident, $kernel:path, $which:expr) => {
5139        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
5140        // contract's FlashAttnBackward{Q,K,V} `entry_point` symbols to these wrappers.
5141        pub(crate) fn $wrapper(
5142            inputs: &[Arc<RwLock<Storage>>],
5143            outputs: &mut [Arc<RwLock<Storage>>],
5144            _layouts: &[Layout],
5145            params: &OpParams,
5146        ) -> Result<()> {
5147            if inputs.len() != 4 && inputs.len() != 5 {
5148                return Err(Error::Msg(format!(
5149                    "flash_attn_backward wrapper expects 4 or 5 inputs (q, k, v, do, [alibi]), got {}",
5150                    inputs.len(),
5151                ))
5152                .bt());
5153            }
5154            if outputs.len() != 1 {
5155                return Err(Error::Msg(format!(
5156                    "flash_attn_backward wrapper expects 1 output, got {}",
5157                    outputs.len(),
5158                ))
5159                .bt());
5160            }
5161            let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
5162                OpParams::FlashAttn {
5163                    b, hq, hkv, sq, sk, d,
5164                    softmax_scale, causal,
5165                    window_size_left, window_size_right, softcap,
5166                    // Backward is the static (full-K) training path; the
5167                    // recompute attends the full K extent. k_len ignored.
5168                    k_len: _,
5169                } => (
5170                    *b, *hq, *hkv, *sq, *sk, *d,
5171                    *softmax_scale, *causal,
5172                    *window_size_left, *window_size_right, *softcap,
5173                ),
5174                other => {
5175                    return Err(Error::Msg(format!(
5176                        "flash_attn_backward wrapper expects OpParams::FlashAttn, got {other:?}",
5177                    ))
5178                    .bt())
5179                }
5180            };
5181            let q_guard = read_storage(&inputs[0])?;
5182            let k_guard = read_storage(&inputs[1])?;
5183            let v_guard = read_storage(&inputs[2])?;
5184            let do_guard = read_storage(&inputs[3])?;
5185            let alibi_guard = match inputs.get(4) {
5186                Some(arc) => Some(read_storage(arc)?),
5187                None => None,
5188            };
5189            let mut out_guard = write_storage(&outputs[0])?;
5190            let q_cpu = cpu_input(&q_guard)?;
5191            let k_cpu = cpu_input(&k_guard)?;
5192            let v_cpu = cpu_input(&v_guard)?;
5193            let do_cpu = cpu_input(&do_guard)?;
5194            let alibi_cpu = match &alibi_guard {
5195                Some(g) => Some(cpu_input(g)?),
5196                None => None,
5197            };
5198            let out_cpu = cpu_output(&mut out_guard)?;
5199            $kernel(
5200                q_cpu, k_cpu, v_cpu, do_cpu, alibi_cpu, out_cpu, $which,
5201                b, hq, hkv, sq, sk, d,
5202                scale, causal, wl, wr, softcap,
5203            )
5204        }
5205    };
5206}
5207
5208cpu_flash_attn_backward_wrapper!(
5209    flash_attn_backward_q_f32_cpu_wrapper,
5210    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5211    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5212);
5213cpu_flash_attn_backward_wrapper!(
5214    flash_attn_backward_k_f32_cpu_wrapper,
5215    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5216    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5217);
5218cpu_flash_attn_backward_wrapper!(
5219    flash_attn_backward_v_f32_cpu_wrapper,
5220    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
5221    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5222);
5223cpu_flash_attn_backward_wrapper!(
5224    flash_attn_backward_q_f64_cpu_wrapper,
5225    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5226    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5227);
5228cpu_flash_attn_backward_wrapper!(
5229    flash_attn_backward_k_f64_cpu_wrapper,
5230    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5231    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5232);
5233cpu_flash_attn_backward_wrapper!(
5234    flash_attn_backward_v_f64_cpu_wrapper,
5235    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
5236    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5237);
5238cpu_flash_attn_backward_wrapper!(
5239    flash_attn_backward_q_bf16_cpu_wrapper,
5240    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5241    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5242);
5243cpu_flash_attn_backward_wrapper!(
5244    flash_attn_backward_k_bf16_cpu_wrapper,
5245    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5246    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5247);
5248cpu_flash_attn_backward_wrapper!(
5249    flash_attn_backward_v_bf16_cpu_wrapper,
5250    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5251    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5252);
5253cpu_flash_attn_backward_wrapper!(
5254    flash_attn_backward_q_f16_cpu_wrapper,
5255    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5256    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5257);
5258cpu_flash_attn_backward_wrapper!(
5259    flash_attn_backward_k_f16_cpu_wrapper,
5260    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5261    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5262);
5263cpu_flash_attn_backward_wrapper!(
5264    flash_attn_backward_v_f16_cpu_wrapper,
5265    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5266    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5267);
5268
5269/// Dispatch wrapper for `(PagedAttn, *, Cpu)`. 5 or 6 inputs (q,
5270/// k_cache, v_cache, block_table, context_lens, optional alibi_slopes).
5271macro_rules! cpu_paged_attn_wrapper {
5272    ($wrapper:ident, $kernel:path) => {
5273        // `pub(crate)` so the FKC `CpuLinkRegistry` (`CPU_ATTENTION_ENTRY_POINTS`)
5274        // can resolve the paged sections' `byte_kernels::paged_attn_<dt>` symbols
5275        // to these wrappers (the attention family is contract-sourced; §3.9.1).
5276        pub(crate) fn $wrapper(
5277            inputs: &[Arc<RwLock<Storage>>],
5278            outputs: &mut [Arc<RwLock<Storage>>],
5279            _layouts: &[Layout],
5280            params: &OpParams,
5281        ) -> Result<()> {
5282            if inputs.len() != 5 && inputs.len() != 6 {
5283                return Err(Error::Msg(format!(
5284                    "paged_attn wrapper expects 5 or 6 inputs, got {}",
5285                    inputs.len(),
5286                ))
5287                .bt());
5288            }
5289            if outputs.len() != 1 {
5290                return Err(Error::Msg(format!(
5291                    "paged_attn wrapper expects 1 output, got {}",
5292                    outputs.len(),
5293                ))
5294                .bt());
5295            }
5296            let (b, hq, hkv, sq, d, block_size, max_blocks_per_seq, num_blocks, scale, softcap) =
5297                match params {
5298                    OpParams::PagedAttn {
5299                        b,
5300                        hq,
5301                        hkv,
5302                        sq,
5303                        d,
5304                        block_size,
5305                        max_blocks_per_seq,
5306                        num_blocks,
5307                        softmax_scale,
5308                        softcap,
5309                    } => (
5310                        *b,
5311                        *hq,
5312                        *hkv,
5313                        *sq,
5314                        *d,
5315                        *block_size,
5316                        *max_blocks_per_seq,
5317                        *num_blocks,
5318                        *softmax_scale,
5319                        *softcap,
5320                    ),
5321                    other => {
5322                        return Err(Error::Msg(format!(
5323                            "paged_attn wrapper expects OpParams::PagedAttn, got {other:?}",
5324                        ))
5325                        .bt())
5326                    }
5327                };
5328            let q_g = read_storage(&inputs[0])?;
5329            let kc_g = read_storage(&inputs[1])?;
5330            let vc_g = read_storage(&inputs[2])?;
5331            let bt_g = read_storage(&inputs[3])?;
5332            let cl_g = read_storage(&inputs[4])?;
5333            let alibi_g = match inputs.get(5) {
5334                Some(arc) => Some(read_storage(arc)?),
5335                None => None,
5336            };
5337            if bt_g.dtype != DType::U32 || cl_g.dtype != DType::U32 {
5338                return Err(Error::Msg(format!(
5339                    "paged_attn: block_table and context_lens must be U32, got {:?} / {:?}",
5340                    bt_g.dtype, cl_g.dtype,
5341                ))
5342                .bt());
5343            }
5344            let mut out_guard = write_storage(&outputs[0])?;
5345            let q_cpu = cpu_input(&q_g)?;
5346            let kc_cpu = cpu_input(&kc_g)?;
5347            let vc_cpu = cpu_input(&vc_g)?;
5348            let bt_cpu = cpu_input(&bt_g)?;
5349            let cl_cpu = cpu_input(&cl_g)?;
5350            let alibi_cpu = match &alibi_g {
5351                Some(g) => Some(cpu_input(g)?),
5352                None => None,
5353            };
5354            let out_cpu = cpu_output(&mut out_guard)?;
5355            $kernel(
5356                q_cpu,
5357                kc_cpu,
5358                vc_cpu,
5359                bt_cpu,
5360                cl_cpu,
5361                alibi_cpu,
5362                out_cpu,
5363                b,
5364                hq,
5365                hkv,
5366                sq,
5367                d,
5368                block_size,
5369                max_blocks_per_seq,
5370                num_blocks,
5371                scale,
5372                softcap,
5373            )
5374        }
5375    };
5376}
5377
5378cpu_paged_attn_wrapper!(
5379    paged_attn_f32_cpu_wrapper,
5380    fuel_cpu_backend::byte_kernels::paged_attn_f32
5381);
5382cpu_paged_attn_wrapper!(
5383    paged_attn_f64_cpu_wrapper,
5384    fuel_cpu_backend::byte_kernels::paged_attn_f64
5385);
5386cpu_paged_attn_wrapper!(
5387    paged_attn_bf16_cpu_wrapper,
5388    fuel_cpu_backend::byte_kernels::paged_attn_bf16
5389);
5390cpu_paged_attn_wrapper!(
5391    paged_attn_f16_cpu_wrapper,
5392    fuel_cpu_backend::byte_kernels::paged_attn_f16
5393);
5394
5395// Cast wrappers — one per TARGET dtype, each matching every other source
5396// dtype. Together they cover the full 11×10 = 110 directed pair matrix
5397// (identity pairs excluded; the optimizer elides them). Every real numeric
5398// dtype is a complete closed cast basis.
5399cpu_cast_wrapper!(
5400    cast_to_f32_cpu_wrapper,
5401    DType::F32,
5402    "f32",
5403    {
5404        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f32,
5405        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f32,
5406        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f32,
5407        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f32,
5408        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f32,
5409        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f32,
5410        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f32,
5411        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f32,
5412        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f32,
5413        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f32,
5414        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f32,
5415    },
5416);
5417cpu_cast_wrapper!(
5418    cast_to_f64_cpu_wrapper,
5419    DType::F64,
5420    "f64",
5421    {
5422        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f64,
5423        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f64,
5424        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f64,
5425        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f64,
5426        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f64,
5427        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f64,
5428        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f64,
5429        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f64,
5430        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f64,
5431        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f64,
5432        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f64,
5433    },
5434);
5435cpu_cast_wrapper!(
5436    cast_to_bf16_cpu_wrapper,
5437    DType::BF16,
5438    "bf16",
5439    {
5440        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bf16,
5441        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bf16,
5442        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bf16,
5443        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bf16,
5444        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bf16,
5445        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bf16,
5446        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bf16,
5447        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bf16,
5448        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bf16,
5449        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bf16,
5450        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_bf16,
5451    },
5452);
5453cpu_cast_wrapper!(
5454    cast_to_f16_cpu_wrapper,
5455    DType::F16,
5456    "f16",
5457    {
5458        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f16,
5459        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f16,
5460        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f16,
5461        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f16,
5462        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f16,
5463        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f16,
5464        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f16,
5465        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f16,
5466        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f16,
5467        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f16,
5468        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f16,
5469    },
5470);
5471cpu_cast_wrapper!(
5472    cast_to_f8e4m3_cpu_wrapper,
5473    DType::F8E4M3,
5474    "f8e4m3",
5475    {
5476        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f8e4m3,
5477        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f8e4m3,
5478        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f8e4m3,
5479        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f8e4m3,
5480        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f8e4m3,
5481        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f8e4m3,
5482        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f8e4m3,
5483        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f8e4m3,
5484        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f8e4m3,
5485        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f8e4m3,
5486        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f8e4m3,
5487    },
5488);
5489cpu_cast_wrapper!(
5490    cast_to_u8_cpu_wrapper,
5491    DType::U8,
5492    "u8",
5493    {
5494        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u8,
5495        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u8,
5496        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u8,
5497        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u8,
5498        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u8,
5499        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u8,
5500        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_u8,
5501        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u8,
5502        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u8,
5503        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u8,
5504        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u8,
5505    },
5506);
5507cpu_cast_wrapper!(
5508    cast_to_i8_cpu_wrapper,
5509    DType::I8,
5510    "i8",
5511    {
5512        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i8,
5513        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i8,
5514        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i8,
5515        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i8,
5516        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i8,
5517        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i8,
5518        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i8,
5519        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i8,
5520        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i8,
5521        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i8,
5522        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i8,
5523    },
5524);
5525cpu_cast_wrapper!(
5526    cast_to_u32_cpu_wrapper,
5527    DType::U32,
5528    "u32",
5529    {
5530        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u32,
5531        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u32,
5532        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u32,
5533        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u32,
5534        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u32,
5535        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_u32,
5536        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u32,
5537        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u32,
5538        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u32,
5539        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u32,
5540        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u32,
5541    },
5542);
5543cpu_cast_wrapper!(
5544    cast_to_i16_cpu_wrapper,
5545    DType::I16,
5546    "i16",
5547    {
5548        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i16,
5549        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i16,
5550        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i16,
5551        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i16,
5552        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i16,
5553        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i16,
5554        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i16,
5555        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i16,
5556        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i16,
5557        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i16,
5558        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i16,
5559    },
5560);
5561cpu_cast_wrapper!(
5562    cast_to_i32_cpu_wrapper,
5563    DType::I32,
5564    "i32",
5565    {
5566        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i32,
5567        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i32,
5568        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i32,
5569        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i32,
5570        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i32,
5571        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i32,
5572        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i32,
5573        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i32,
5574        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i32,
5575        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i32,
5576        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i32,
5577    },
5578);
5579cpu_cast_wrapper!(
5580    cast_to_i64_cpu_wrapper,
5581    DType::I64,
5582    "i64",
5583    {
5584        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i64,
5585        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i64,
5586        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i64,
5587        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i64,
5588        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i64,
5589        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i64,
5590        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i64,
5591        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i64,
5592        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i64,
5593        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i64,
5594        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i64,
5595    },
5596);
5597
5598// Cast TO Bool (GAP-168) -- the 12th target. `Bool` is byte-backed like `U8`,
5599// so this wrapper exists precisely to keep the two DISTINGUISHABLE: every arm
5600// runs a real `!= 0` conversion rather than reinterpreting the source bytes.
5601cpu_cast_wrapper!(
5602    cast_to_bool_cpu_wrapper,
5603    DType::Bool,
5604    "bool",
5605    {
5606        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bool,
5607        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bool,
5608        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bool,
5609        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_bool,
5610        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bool,
5611        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bool,
5612        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bool,
5613        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bool,
5614        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bool,
5615        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bool,
5616        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bool,
5617    },
5618);
5619
5620/// Dispatch wrapper for `(MatMul, F32, Cpu)`. Extracts the
5621/// `OpParams::Matmul { m, n, k }` and forwards to the typed
5622/// kernel. Both inputs are guaranteed contiguous f32 by the
5623/// executor's auto-Contiguize pass.
5624///
5625/// `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`,
5626/// [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) can resolve the matmul contract's
5627/// `entry_point` symbol to this exact wrapper fn-pointer.
5628pub(crate) fn matmul_f32_cpu_wrapper(
5629    inputs: &[Arc<RwLock<Storage>>],
5630    outputs: &mut [Arc<RwLock<Storage>>],
5631    _layouts: &[Layout],
5632    params: &OpParams,
5633) -> Result<()> {
5634    if inputs.len() != 2 {
5635        return Err(Error::Msg(format!(
5636            "matmul wrapper expects 2 inputs, got {}",
5637            inputs.len(),
5638        ))
5639        .bt());
5640    }
5641    if outputs.len() != 1 {
5642        return Err(Error::Msg(format!(
5643            "matmul wrapper expects 1 output, got {}",
5644            outputs.len(),
5645        ))
5646        .bt());
5647    }
5648    let (lhs_batch_dims, rhs_batch_dims, m, n, k, m_compute) = match params {
5649        OpParams::Matmul {
5650            lhs_batch_dims,
5651            rhs_batch_dims,
5652            m,
5653            n,
5654            k,
5655            m_compute,
5656        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k, m_compute),
5657        other => {
5658            return Err(Error::Msg(format!(
5659                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5660            ))
5661            .bt());
5662        }
5663    };
5664    // Data-determined-M (sparse MoE): `m` is the row capacity; compute only
5665    // `rows`. `Deferred` must have been resolved at execute before the
5666    // kernel runs (see resolve_deferred_matmul).
5667    let rows = match m_compute {
5668        MatmulM::All => m,
5669        MatmulM::Rows(c) => *c,
5670        MatmulM::Deferred(d) => {
5671            return Err(Error::Msg(format!(
5672                "matmul_f32 wrapper: unresolved data-determined row count {d:?} \
5673                 (must be resolved at execute before the kernel runs)",
5674            ))
5675            .bt());
5676        }
5677    };
5678    let lhs_guard = read_storage(&inputs[0])?;
5679    let rhs_guard = read_storage(&inputs[1])?;
5680    let mut out_guard = write_storage(&outputs[0])?;
5681    let lhs_cpu = cpu_input(&lhs_guard)?;
5682    let rhs_cpu = cpu_input(&rhs_guard)?;
5683    let out_cpu = cpu_output(&mut out_guard)?;
5684    fuel_cpu_backend::byte_kernels::matmul_f32_capacity(
5685        lhs_cpu,
5686        rhs_cpu,
5687        out_cpu,
5688        lhs_batch_dims,
5689        rhs_batch_dims,
5690        m,
5691        rows,
5692        n,
5693        k,
5694    )
5695}
5696
5697/// Build a CPU matmul wrapper for any element type. The wrapper
5698/// shape is identical across dtypes — it just forwards to a typed
5699/// kernel that has the matching `(lhs, rhs, out, lhs_batch_dims,
5700/// rhs_batch_dims, m, n, k) -> Result<()>` signature.
5701macro_rules! cpu_matmul_wrapper {
5702    ($wrapper:ident, $kernel:path, $type_name:literal) => {
5703        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
5704        // contract's `entry_point` symbols to these wrapper fn-pointers.
5705        pub(crate) fn $wrapper(
5706            inputs: &[Arc<RwLock<Storage>>],
5707            outputs: &mut [Arc<RwLock<Storage>>],
5708            _layouts: &[Layout],
5709            params: &OpParams,
5710        ) -> Result<()> {
5711            if inputs.len() != 2 {
5712                return Err(Error::Msg(format!(
5713                    "matmul wrapper expects 2 inputs, got {}",
5714                    inputs.len(),
5715                ))
5716                .bt());
5717            }
5718            if outputs.len() != 1 {
5719                return Err(Error::Msg(format!(
5720                    "matmul wrapper expects 1 output, got {}",
5721                    outputs.len(),
5722                ))
5723                .bt());
5724            }
5725            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5726                OpParams::Matmul {
5727                    lhs_batch_dims,
5728                    rhs_batch_dims,
5729                    m,
5730                    n,
5731                    k,
5732                    ..
5733                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5734                other => {
5735                    return Err(Error::Msg(format!(
5736                        "matmul wrapper expects OpParams::Matmul, got {other:?}",
5737                    ))
5738                    .bt())
5739                }
5740            };
5741            let lhs_guard = read_storage(&inputs[0])?;
5742            let rhs_guard = read_storage(&inputs[1])?;
5743            let mut out_guard = write_storage(&outputs[0])?;
5744            let lhs_cpu = cpu_input(&lhs_guard)?;
5745            let rhs_cpu = cpu_input(&rhs_guard)?;
5746            let out_cpu = cpu_output(&mut out_guard)?;
5747            let _ = $type_name;
5748            $kernel(
5749                lhs_cpu,
5750                rhs_cpu,
5751                out_cpu,
5752                lhs_batch_dims,
5753                rhs_batch_dims,
5754                m,
5755                n,
5756                k,
5757            )
5758        }
5759    };
5760}
5761
5762cpu_matmul_wrapper!(
5763    matmul_bf16_cpu_wrapper,
5764    fuel_cpu_backend::byte_kernels::matmul_bf16,
5765    "matmul_bf16"
5766);
5767cpu_matmul_wrapper!(
5768    matmul_f16_cpu_wrapper,
5769    fuel_cpu_backend::byte_kernels::matmul_f16,
5770    "matmul_f16"
5771);
5772cpu_matmul_wrapper!(
5773    matmul_f32_bf16_cpu_wrapper,
5774    fuel_cpu_backend::byte_kernels::matmul_f32_bf16,
5775    "matmul_f32_bf16"
5776);
5777cpu_matmul_wrapper!(
5778    matmul_f32_f16_cpu_wrapper,
5779    fuel_cpu_backend::byte_kernels::matmul_f32_f16,
5780    "matmul_f32_f16"
5781);
5782cpu_matmul_wrapper!(
5783    matmul_i8_cpu_wrapper,
5784    fuel_cpu_backend::byte_kernels::matmul_i8,
5785    "matmul_i8"
5786);
5787cpu_matmul_wrapper!(
5788    matmul_u8_cpu_wrapper,
5789    fuel_cpu_backend::byte_kernels::matmul_u8,
5790    "matmul_u8"
5791);
5792
5793/// f64 mirror of [`matmul_f32_cpu_wrapper`]. Same OpKind
5794/// (MatMul); the binding-table key picks this entry when the
5795/// node's dtype is F64.
5796///
5797/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul contract's
5798/// `entry_point` symbol to this exact wrapper fn-pointer.
5799pub(crate) fn matmul_f64_cpu_wrapper(
5800    inputs: &[Arc<RwLock<Storage>>],
5801    outputs: &mut [Arc<RwLock<Storage>>],
5802    _layouts: &[Layout],
5803    params: &OpParams,
5804) -> Result<()> {
5805    if inputs.len() != 2 {
5806        return Err(Error::Msg(format!(
5807            "matmul wrapper expects 2 inputs, got {}",
5808            inputs.len(),
5809        ))
5810        .bt());
5811    }
5812    if outputs.len() != 1 {
5813        return Err(Error::Msg(format!(
5814            "matmul wrapper expects 1 output, got {}",
5815            outputs.len(),
5816        ))
5817        .bt());
5818    }
5819    let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5820        OpParams::Matmul {
5821            lhs_batch_dims,
5822            rhs_batch_dims,
5823            m,
5824            n,
5825            k,
5826            ..
5827        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5828        other => {
5829            return Err(Error::Msg(format!(
5830                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5831            ))
5832            .bt());
5833        }
5834    };
5835    let lhs_guard = read_storage(&inputs[0])?;
5836    let rhs_guard = read_storage(&inputs[1])?;
5837    let mut out_guard = write_storage(&outputs[0])?;
5838    let lhs_cpu = cpu_input(&lhs_guard)?;
5839    let rhs_cpu = cpu_input(&rhs_guard)?;
5840    let out_cpu = cpu_output(&mut out_guard)?;
5841    fuel_cpu_backend::byte_kernels::matmul_f64(
5842        lhs_cpu,
5843        rhs_cpu,
5844        out_cpu,
5845        lhs_batch_dims,
5846        rhs_batch_dims,
5847        m,
5848        n,
5849        k,
5850    )
5851}
5852
5853/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cpu)` — copy from a
5854/// CPU source storage into a freshly-allocated output on any target
5855/// backend. The executor allocates the output on `target_location`
5856/// via [`crate::pipelined::WorkItemKind::Copy`] before this wrapper
5857/// runs; the wrapper switches on the output's `BackendStorage`
5858/// variant to pick the H2D path.
5859///
5860/// - CPU output → memcpy (CPU→CPU).
5861/// - CUDA output → `CudaStorageBytes::write_from_host` (H2D via
5862///   `cuMemcpyHtoD`).
5863/// - Vulkan output → `VulkanBackend::write_bytes` (H2D via staging
5864///   buffer + `vkCmdCopyBuffer`).
5865///
5866/// Bridge-retirement Phase 2 (CPU→CPU) + Phase 3b (CPU→GPU). The
5867/// wrapper-internal match on output variant is the pragmatic shape
5868/// while the binding-table key `(op, dtypes, source_backend)` doesn't
5869/// yet encode the target. A future binding-table-key extension would
5870/// split this into per-(source, target) sub-wrappers without changing
5871/// the call surface.
5872///
5873/// Replaces:
5874/// * The per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
5875///   (Phase 2 deletion).
5876/// * `fuel-tensor::pipelined_bridge::upload_host_buffer`'s per-
5877///   `DeviceLocation` match (Phase 3b deletion).
5878fn copy_from_cpu_wrapper(
5879    inputs: &[Arc<RwLock<Storage>>],
5880    outputs: &mut [Arc<RwLock<Storage>>],
5881    _layouts: &[Layout],
5882    _params: &OpParams,
5883) -> Result<()> {
5884    if inputs.len() != 1 || outputs.len() != 1 {
5885        return Err(Error::Msg(format!(
5886            "copy_from_cpu_wrapper: expected 1 input + 1 output, got {} + {}",
5887            inputs.len(),
5888            outputs.len(),
5889        ))
5890        .bt());
5891    }
5892    let in_guard = read_storage(&inputs[0])?;
5893    let src = cpu_input(&in_guard)?;
5894    let mut out_guard = write_storage(&outputs[0])?;
5895    // Truncate source bytes to the destination's byte count — the
5896    // executor allocates the output exactly `node.shape.elem_count *
5897    // dtype.size_in_bytes()` bytes. Host buffers from Op::Const slots
5898    // may be larger (shared storage across views); we copy only the
5899    // destination-sized prefix. Mirrors the deleted
5900    // `upload_host_buffer`'s `truncate_to` parameter.
5901    let n_out = out_guard.inner.len_bytes();
5902    let n_src = src.len_bytes();
5903    let n = n_src.min(n_out);
5904    let src_slice = &src.bytes()[..n];
5905    match &mut out_guard.inner {
5906        BackendStorage::Cpu(dst) => {
5907            dst.bytes_mut()[..n].copy_from_slice(src_slice);
5908        }
5909        #[cfg(feature = "cuda")]
5910        BackendStorage::Cuda(dst) => {
5911            // CUDA write_from_host requires src.len() == dst.len_bytes.
5912            // The executor sized the output to `n_out`; we truncated
5913            // src to `n` = min(n_src, n_out). When n < n_out the
5914            // remaining bytes stay uninit; for the Op::Const upload
5915            // path this matches the deleted upload_host_buffer's
5916            // behavior (truncated host bytes uploaded as-is).
5917            if n == n_out {
5918                dst.write_from_host(src_slice)?;
5919            } else {
5920                // Pad: copy src into a staging vec sized exactly n_out
5921                // with trailing zeros. Rare path (size mismatch).
5922                let mut staged = vec![0_u8; n_out];
5923                staged[..n].copy_from_slice(src_slice);
5924                dst.write_from_host(&staged)?;
5925            }
5926        }
5927        #[cfg(feature = "vulkan")]
5928        BackendStorage::Vulkan(dst) => {
5929            let backend = dst
5930                .backend()
5931                .ok_or_else(|| {
5932                    Error::Msg(
5933                        "copy_from_cpu_wrapper: Vulkan output has no attached \
5934                 backend handle. The executor's Op::Copy arm must allocate \
5935                 via VulkanBackend::alloc_bytes_handle (which attaches \
5936                 the handle)."
5937                            .to_string(),
5938                    )
5939                    .bt()
5940                })?
5941                .clone();
5942            if n == n_out {
5943                backend.write_bytes(dst, src_slice)?;
5944            } else {
5945                let mut staged = vec![0_u8; n_out];
5946                staged[..n].copy_from_slice(src_slice);
5947                backend.write_bytes(dst, &staged)?;
5948            }
5949        }
5950        #[allow(unreachable_patterns)]
5951        other => {
5952            return Err(Error::Msg(format!(
5953                "copy_from_cpu_wrapper: output backend not wired ({other:?}); \
5954                 CPU + CUDA + Vulkan covered, Metal extends when its \
5955                 byte-storage substrate is ready.",
5956            ))
5957            .bt());
5958        }
5959    }
5960    Ok(())
5961}
5962
5963/// The authored CPU elementwise-binary kernel contract, embedded into the
5964/// binary. This is the PRODUCTION `include_str!` (distinct from the identical
5965/// path used in the `fkc::register` test module); `register_cpu_binary_from_contract`
5966/// parses + lowers it and binds the family FROM THE CONTRACT.
5967const CPU_ELEMENTWISE_BINARY_CONTRACT: &str =
5968    include_str!("../kernel-contracts/cpu/elementwise-binary.fkc.md");
5969
5970/// Register the CPU elementwise-binary family (8 ops × 4 dtypes = 32
5971/// bindings) by IMPORTING its FKC kernel contract — the FIRST production
5972/// FKC consumer. FKC is unconditional core infrastructure, so this is the
5973/// ONE registration path for the family: there is no hand-written fallback
5974/// (deleting it was the point — a build that lost the importer would silently
5975/// lose the family).
5976///
5977/// The authored contract `fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`
5978/// is parsed + lowered and each `entry_point` symbol resolved through the
5979/// production [`crate::fkc::CpuLinkRegistry`] to the exact same wrapper
5980/// fn-pointers the CPU backend exposes (`add_elementwise_f32_cpu_wrapper`, …;
5981/// the very map [`crate::fkc::CPU_BINARY_ENTRY_POINTS`] holds). Relative to the
5982/// deleted hand-written registrations this is behavior-preserving: identical
5983/// kernels + caps; the binding's `kernel_source` becomes the contract's
5984/// `"portable-cpu"` tag and its precision the contract's audited claim. Cost is
5985/// preserved because this runs BEFORE the `fill_unset_cpu_cost` pass, which
5986/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind
5987/// cost fn every other CPU primitive gets.
5988///
5989/// Fused-registry decision: the elementwise-binary family declares NO fused
5990/// ops (`provider.fused` is empty), and `register_cpu_kernels` threads only a
5991/// `KernelBindingTable` — there is no paired global `FusedKernelRegistry` at
5992/// this seam (the static `crate::fused::default_kernel_registry()` is built
5993/// independently). So `register_into`'s required fused argument is a local
5994/// throwaway that provably stays empty.
5995///
5996/// Init-boundary fail-fast: a parse/lower/link failure of the embedded,
5997/// authored contract is a programmer error surfaced once here via `expect`
5998/// (mirroring the `finalize().expect(...)` convention in [`global_bindings`]).
5999/// It cannot fail for a runtime-data reason — the contract is `include_str!`'d
6000/// into the binary and the link registry is exhaustive for this family.
6001fn register_cpu_binary_from_contract(table: &mut KernelBindingTable) {
6002    let provider = crate::fkc::import_bundle_str(
6003        CPU_ELEMENTWISE_BINARY_CONTRACT,
6004        &crate::fkc::CpuLinkRegistry,
6005    )
6006    .expect(
6007        "authored CPU elementwise-binary contract must import \
6008                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6009    );
6010    debug_assert!(
6011        provider.fused.is_empty(),
6012        "elementwise-binary contract declares no fused ops",
6013    );
6014    let mut fused = crate::fused::FusedKernelRegistry::new();
6015    provider
6016        .register_into(table, &mut fused)
6017        .expect("CPU elementwise-binary contract must register into the binding table");
6018}
6019
6020/// The authored CPU affine / clamp / powi kernel contract, embedded into the
6021/// binary (the PRODUCTION `include_str!`). `register_cpu_affine_clamp_powi_from_contract`
6022/// parses + lowers it and binds the family FROM THE CONTRACT.
6023const CPU_AFFINE_CLAMP_POWI_CONTRACT: &str =
6024    include_str!("../kernel-contracts/cpu/affine-clamp-powi.fkc.md");
6025
6026/// Register the CPU out-of-place scalar-param family (affine/clamp/powi × 4
6027/// dtypes + powi_backward × 4 = 16 bindings) by IMPORTING its FKC kernel
6028/// contract — the second production FKC consumer, mirroring
6029/// [`register_cpu_binary_from_contract`]. FKC is unconditional core
6030/// infrastructure, so this is the ONE registration path for the family: the
6031/// hand-written `table.register(...)` calls it used to carry are DELETED.
6032///
6033/// Each `entry_point` symbol resolves through the production
6034/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6035/// [`crate::fkc::CPU_AFFINE_CLAMP_POWI_ENTRY_POINTS`]) to the exact same wrapper
6036/// fn-pointers the CPU backend exposes. Behavior-preserving vs. the deleted
6037/// hand-written path: identical kernels + caps (contiguous-only); the binding's
6038/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its precision
6039/// the contract's audited bit-stable claim. Cost is preserved because this runs
6040/// BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6041/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6042///
6043/// The scalar params (affine mul/add, clamp min/max, powi exp) ride in
6044/// `OpParams`, NOT the dtype-list, so the imported binding keys are `[t, t]` for
6045/// the single-input forward ops and `[t, t, t]` for the two-input
6046/// `powi_backward` — identical to the deleted `&unary(t)` / `&binary(t)` regs.
6047///
6048/// The family declares NO fused ops (the FusedOps::POWI_BACKWARD fused-registry
6049/// registration is a SEPARATE seam, untouched), so `register_into`'s required
6050/// fused argument is a local throwaway that provably stays empty.
6051fn register_cpu_affine_clamp_powi_from_contract(table: &mut KernelBindingTable) {
6052    let provider =
6053        crate::fkc::import_bundle_str(CPU_AFFINE_CLAMP_POWI_CONTRACT, &crate::fkc::CpuLinkRegistry)
6054            .expect(
6055                "authored CPU affine/clamp/powi contract must import \
6056                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6057            );
6058    debug_assert!(
6059        provider.fused.is_empty(),
6060        "affine/clamp/powi contract declares no fused ops",
6061    );
6062    let mut fused = crate::fused::FusedKernelRegistry::new();
6063    provider
6064        .register_into(table, &mut fused)
6065        .expect("CPU affine/clamp/powi contract must register into the binding table");
6066}
6067
6068/// The authored CPU elementwise-unary kernel contract, embedded into the binary
6069/// (the PRODUCTION `include_str!`). `register_cpu_unary_from_contract` parses +
6070/// lowers it and binds the family FROM THE CONTRACT.
6071const CPU_ELEMENTWISE_UNARY_CONTRACT: &str =
6072    include_str!("../kernel-contracts/cpu/elementwise-unary.fkc.md");
6073
6074/// Register the CPU elementwise-unary family (22 ops × 4 dtypes = 88 bindings)
6075/// by IMPORTING its FKC kernel contract — the third production FKC consumer,
6076/// mirroring [`register_cpu_binary_from_contract`] /
6077/// [`register_cpu_affine_clamp_powi_from_contract`]. FKC is unconditional core
6078/// infrastructure, so this is the ONE registration path for the family: the
6079/// hand-written `table.register(...)` calls it used to carry are DELETED.
6080///
6081/// This is the **first** consumer of the §3.4 multi-dtype fan-out: each per-op
6082/// section declares a BASE `entry_point` (e.g. `…::relu`) and enumerates
6083/// `dtypes: [F32, F64, BF16, F16]`; the importer fans it into one binding per
6084/// dtype, resolving `<base>_<dtype>` through the production
6085/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6086/// [`crate::fkc::CPU_UNARY_ENTRY_POINTS`]) to the exact same wrapper fn-pointers
6087/// the CPU backend exposes. Behavior-preserving vs. the deleted hand-written
6088/// path: identical kernels + caps (contiguous-only, `[t, t]` keys); the
6089/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6090/// precision the contract's bit-stable claim. Cost is preserved because this
6091/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6092/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6093///
6094/// `gelu_tanh` (`OpKind::GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
6095/// (`OpKind::GeluElementwise`, base `gelu`) stay DISTINCT — the exact-erf
6096/// GELU must never be confused with the tanh approximation under a Judge epsilon.
6097///
6098/// The family declares NO fused ops, so `register_into`'s required fused argument
6099/// is a local throwaway that provably stays empty.
6100fn register_cpu_unary_from_contract(table: &mut KernelBindingTable) {
6101    let provider =
6102        crate::fkc::import_bundle_str(CPU_ELEMENTWISE_UNARY_CONTRACT, &crate::fkc::CpuLinkRegistry)
6103            .expect(
6104                "authored CPU elementwise-unary contract must import \
6105                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6106            );
6107    debug_assert!(
6108        provider.fused.is_empty(),
6109        "elementwise-unary contract declares no fused ops",
6110    );
6111    let mut fused = crate::fused::FusedKernelRegistry::new();
6112    provider
6113        .register_into(table, &mut fused)
6114        .expect("CPU elementwise-unary contract must register into the binding table");
6115}
6116
6117/// The authored CPU compare + where kernel contract, embedded into the binary
6118/// (the PRODUCTION `include_str!`). `register_cpu_compare_where_from_contract`
6119/// parses + lowers it and binds the family FROM THE CONTRACT.
6120const CPU_COMPARE_WHERE_CONTRACT: &str =
6121    include_str!("../kernel-contracts/cpu/compare-where.fkc.md");
6122
6123/// Register the CPU compare (6 ops × 4 dtypes = 24) + where (1 op × 4 dtypes =
6124/// 4) family — 28 bindings — by IMPORTING its FKC kernel contract, the fourth
6125/// production FKC consumer (mirroring the binary / affine-clamp-powi / unary
6126/// importers). FKC is unconditional core infrastructure, so this is the ONE
6127/// registration path for the family: the hand-written `table.register(...)`
6128/// calls it used to carry are DELETED.
6129///
6130/// Two contract shapes, both resolved through the production
6131/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6132/// [`crate::fkc::CPU_COMPARE_ENTRY_POINTS`] + [`crate::fkc::CPU_WHERE_ENTRY_POINTS`]):
6133///  - the 24 per-(op,dtype) COMPARE thunks are single-dtype sections → each
6134///    resolves its declared `_u8`-suffixed symbol (`eq_f32_u8`, …) AS-IS; the
6135///    binding key is `[T, T, U8]` (output is the `fixed(U8)` mask), identical
6136///    to the deleted `&compare(t)` regs.
6137///  - the single WHERE section rides the §3.4 multi-dtype fan-out — its BASE
6138///    `entry_point` `…::where` expands to `where_{f32,f64,bf16,f16}`, one
6139///    binding per dtype, key `[U8, T, T, T]` (cond U8 + `passthrough(a)` → T),
6140///    identical to the deleted `&where_dts(t)` regs.
6141///
6142/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6143/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6144/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6145/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
6146/// which upgrades the imported entries' `unknown_cost` sentinel to the same
6147/// OpKind cost fn every CPU primitive gets. The `## compare` chassis umbrella is
6148/// `registrable: false` (§3.10) and never registers. The family declares NO
6149/// fused ops, so `register_into`'s required fused argument is a local throwaway
6150/// that provably stays empty.
6151fn register_cpu_compare_where_from_contract(table: &mut KernelBindingTable) {
6152    let provider =
6153        crate::fkc::import_bundle_str(CPU_COMPARE_WHERE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6154            .expect(
6155                "authored CPU compare/where contract must import \
6156                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6157            );
6158    debug_assert!(
6159        provider.fused.is_empty(),
6160        "compare/where contract declares no fused ops",
6161    );
6162    let mut fused = crate::fused::FusedKernelRegistry::new();
6163    provider
6164        .register_into(table, &mut fused)
6165        .expect("CPU compare/where contract must register into the binding table");
6166}
6167
6168/// The authored CPU reduce kernel contract, embedded into the binary (the
6169/// PRODUCTION `include_str!`). `register_cpu_reduce_from_contract` parses +
6170/// lowers it and binds the family FROM THE CONTRACT.
6171const CPU_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce.fkc.md");
6172
6173/// Register the CPU per-axis reduce family (Sum/Mean/Max/Min × 4 dtypes = 16
6174/// bindings) by IMPORTING its FKC kernel contract, the fifth production FKC
6175/// consumer (mirroring the binary / affine-clamp-powi / unary / compare-where
6176/// importers). FKC is unconditional core infrastructure, so this is the ONE
6177/// registration path for the family: the hand-written `table.register(...)`
6178/// calls it used to carry are DELETED.
6179///
6180/// Each of the 16 per-(op, dtype) sections (`## sum_reduce_f32`, …) is a SPECIFIC
6181/// single-dtype contract with a concrete `entry_point` (`…::sum_reduce_f32`), so
6182/// none of them fan — the importer resolves each declared symbol AS-IS through
6183/// the production [`crate::fkc::CpuLinkRegistry`] (now chaining
6184/// [`crate::fkc::CPU_REDUCE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
6185/// CPU backend exposes. The binding key is `[T, T]` (input + `passthrough(input)`
6186/// output; the reduce axes + keepdim ride in `OpParams::Reduce`, NOT the
6187/// dtype-list), identical to the deleted `&unary(t)` regs.
6188///
6189/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6190/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6191/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6192/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6193/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6194/// fn every CPU primitive gets. The `## reduce` chassis umbrella is
6195/// `registrable: false` (§3.10) and never registers (without it the chassis would
6196/// double-register `SumReduce`/`[F32]` → `DuplicateKernelRef` at init). The
6197/// f32-only `argmax_dim_f32` / `argmin_dim_f32` sections are `registrable: false`
6198/// (DEFERRED — production registers `Arg{Max,Min}Dim` for ALL input dtypes via
6199/// the hand-written `arg{max,min}_dim_u32_cpu_dispatch`, which stays untouched
6200/// below). The family declares NO fused ops, so `register_into`'s required fused
6201/// argument is a local throwaway that provably stays empty.
6202fn register_cpu_reduce_from_contract(table: &mut KernelBindingTable) {
6203    let provider = crate::fkc::import_bundle_str(CPU_REDUCE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6204        .expect(
6205            "authored CPU reduce contract must import \
6206                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6207        );
6208    debug_assert!(
6209        provider.fused.is_empty(),
6210        "reduce contract declares no fused ops",
6211    );
6212    let mut fused = crate::fused::FusedKernelRegistry::new();
6213    provider
6214        .register_into(table, &mut fused)
6215        .expect("CPU reduce contract must register into the binding table");
6216}
6217
6218/// The authored CPU reduce-to kernel contract, embedded into the binary (the
6219/// PRODUCTION `include_str!`). `register_cpu_reduce_to_from_contract` parses +
6220/// lowers it and binds the family FROM THE CONTRACT.
6221const CPU_REDUCE_TO_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce-to.fkc.md");
6222
6223/// Register the CPU broadcast-target reduce-to family (ReduceSumTo /
6224/// ReduceMaxTo × 4 dtypes = 8, key `[T, T]`; ReduceMaxToBackward × 4 dtypes = 4,
6225/// key `[T, T, T]` = 12 bindings) by IMPORTING its FKC kernel contract, the
6226/// sixth production FKC consumer (mirroring the binary / affine-clamp-powi /
6227/// unary / compare-where / reduce importers). FKC is unconditional core
6228/// infrastructure, so this is the ONE registration path for the family: the
6229/// hand-written `table.register(...)` calls it used to carry are DELETED.
6230///
6231/// Each of the 12 per-(op, dtype) sections (`## reduce_sum_to_f32`, …) is a
6232/// SPECIFIC single-dtype contract with a concrete `entry_point`
6233/// (`…::reduce_sum_to_f32`), so none of them fan — the importer resolves each
6234/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6235/// (now chaining [`crate::fkc::CPU_REDUCE_TO_ENTRY_POINTS`]) to the exact
6236/// wrapper fn-pointer the CPU backend exposes. The forward binding key is
6237/// `[T, T]` (input + `passthrough(input)` output — the target
6238/// `input_shape`/`output_shape` ride in `OpParams::ReduceSumTo` /
6239/// `OpParams::ReduceMaxTo`, NOT the dtype-list), identical to the deleted
6240/// `&unary(t)` regs; the backward key is `[T, T, T]` (x, upstream +
6241/// `passthrough(x)` output), identical to the deleted `&binary(t)` regs.
6242///
6243/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6244/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6245/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6246/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
6247/// which upgrades the imported entries' `unknown_cost` sentinel to the same
6248/// OpKind cost fn every CPU primitive gets (ReduceMaxToBackward keeps its own
6249/// `cost_reduce_max_to_backward_cpu` fill). The `## reduce_to` chassis umbrella
6250/// is `registrable: false` (§3.10) and never registers (without it the chassis
6251/// would double-register `ReduceSumTo`/`[F32]` → `DuplicateKernelRef` at init).
6252/// The family declares NO fused ops, so `register_into`'s required fused
6253/// argument is a local throwaway that provably stays empty.
6254fn register_cpu_reduce_to_from_contract(table: &mut KernelBindingTable) {
6255    let provider =
6256        crate::fkc::import_bundle_str(CPU_REDUCE_TO_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6257            "authored CPU reduce-to contract must import \
6258                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6259        );
6260    debug_assert!(
6261        provider.fused.is_empty(),
6262        "reduce-to contract declares no fused ops",
6263    );
6264    let mut fused = crate::fused::FusedKernelRegistry::new();
6265    provider
6266        .register_into(table, &mut fused)
6267        .expect("CPU reduce-to contract must register into the binding table");
6268}
6269
6270/// The authored CPU norm (forward) kernel contract, embedded into the binary
6271/// (the PRODUCTION `include_str!`). `register_cpu_norm_from_contract` parses +
6272/// lowers it and binds the family FROM THE CONTRACT.
6273const CPU_NORM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/norm.fkc.md");
6274
6275/// Register the CPU last-dim NORM (forward) family (Softmax / LogSoftmax /
6276/// RmsNorm / LayerNorm × 4 dtypes = 16 bindings, key `[T, T]`) by IMPORTING its
6277/// FKC kernel contract, the seventh production FKC consumer (mirroring the
6278/// binary / affine-clamp-powi / unary / compare-where / reduce / reduce-to
6279/// importers). FKC is unconditional core infrastructure, so this is the ONE
6280/// registration path for the family: the hand-written `table.register(...)`
6281/// calls it used to carry are DELETED.
6282///
6283/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_f32`,
6284/// `## rms_norm_last_dim_f32`, …) is a SPECIFIC single-dtype contract with a
6285/// concrete `entry_point` (`…::softmax_last_dim_f32`), so none of them fan — the
6286/// importer resolves each declared symbol AS-IS through the production
6287/// [`crate::fkc::CpuLinkRegistry`] (now chaining [`crate::fkc::CPU_NORM_ENTRY_POINTS`])
6288/// to the exact wrapper fn-pointer the CPU backend exposes. The binding key is
6289/// `[T, T]` (a SINGLE input + `passthrough(input)` output — the RMS/LayerNorm
6290/// kernels carry NO affine gamma/beta operand; they are the bare normalization,
6291/// and `outer_count` / `last_dim` / `eps` ride in
6292/// `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the dtype-list),
6293/// identical to the deleted `&unary(t)` regs.
6294///
6295/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6296/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6297/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6298/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6299/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6300/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6301/// section, so there is nothing marked `registrable: false` and no double-register
6302/// risk. The forward NORM ops are ALSO registered in the `FusedKernelRegistry`
6303/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,RMS_NORM,LAYER_NORM}_LAST_DIM`)
6304/// — that is a SEPARATE registry seam and stays untouched; this migration only
6305/// moves the `KernelBindingTable` primitive path. The BACKWARD forms live in a
6306/// separate norm-backward contract and their hand-written regs stay authoritative.
6307/// The family declares NO fused ops, so `register_into`'s required fused argument
6308/// is a local throwaway that provably stays empty.
6309fn register_cpu_norm_from_contract(table: &mut KernelBindingTable) {
6310    let provider = crate::fkc::import_bundle_str(CPU_NORM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6311        .expect(
6312            "authored CPU norm contract must import \
6313                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6314        );
6315    debug_assert!(
6316        provider.fused.is_empty(),
6317        "norm forward contract declares no fused ops",
6318    );
6319    let mut fused = crate::fused::FusedKernelRegistry::new();
6320    provider
6321        .register_into(table, &mut fused)
6322        .expect("CPU norm contract must register into the binding table");
6323}
6324
6325/// The authored CPU norm-BACKWARD kernel contract, embedded into the binary
6326/// (the PRODUCTION `include_str!`). `register_cpu_norm_backward_from_contract`
6327/// parses + lowers it and binds the family FROM THE CONTRACT.
6328const CPU_NORM_BACKWARD_CONTRACT: &str =
6329    include_str!("../kernel-contracts/cpu/norm-backward.fkc.md");
6330
6331/// Register the CPU last-dim NORM-BACKWARD family (Softmax / LogSoftmax /
6332/// RmsNorm / LayerNorm backward × 4 dtypes = 16 bindings, key `[T, T, T]`) by
6333/// IMPORTING its FKC kernel contract, the eighth production FKC consumer (the
6334/// BACKWARD sibling of `register_cpu_norm_from_contract`). FKC is unconditional
6335/// core infrastructure, so this is the ONE registration path for the family: the
6336/// hand-written `table.register(...)` calls it used to carry are DELETED.
6337///
6338/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_backward_f32`,
6339/// `## rms_norm_last_dim_backward_f32`, …) is a SPECIFIC single-dtype contract
6340/// with a concrete `entry_point` (`…::softmax_last_dim_backward_f32`), so none of
6341/// them fan — the importer resolves each declared symbol AS-IS through the
6342/// production [`crate::fkc::CpuLinkRegistry`] (now chaining
6343/// [`crate::fkc::CPU_NORM_BACKWARD_ENTRY_POINTS`]) to the exact wrapper
6344/// fn-pointer the CPU backend exposes. The binding key is `[T, T, T]` — the BARE
6345/// backward takes TWO inputs (softmax/log-softmax: forward output `y` + upstream
6346/// gradient `g`; layer/rms-norm: forward input `x` + `g`, stats recomputed from
6347/// `x` + `eps`) and writes ONE `passthrough(y|x)` output; outer_count / last_dim /
6348/// eps ride in `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the
6349/// dtype-list — identical to the deleted `&binary(t)` regs.
6350///
6351/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6352/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6353/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6354/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6355/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6356/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6357/// section, so there is nothing marked `registrable: false` and no double-register
6358/// risk. The backward NORM ops are ALSO registered in the `FusedKernelRegistry`
6359/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,LAYER_NORM,RMS_NORM}_
6360/// LAST_DIM_BACKWARD`) — that is a SEPARATE registry seam and stays untouched;
6361/// this migration only moves the `KernelBindingTable` primitive path. The family
6362/// declares NO fused ops, so `register_into`'s required fused argument is a local
6363/// throwaway that provably stays empty.
6364fn register_cpu_norm_backward_from_contract(table: &mut KernelBindingTable) {
6365    let provider =
6366        crate::fkc::import_bundle_str(CPU_NORM_BACKWARD_CONTRACT, &crate::fkc::CpuLinkRegistry)
6367            .expect(
6368                "authored CPU norm-backward contract must import \
6369                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6370            );
6371    debug_assert!(
6372        provider.fused.is_empty(),
6373        "norm backward contract declares no fused ops",
6374    );
6375    let mut fused = crate::fused::FusedKernelRegistry::new();
6376    provider
6377        .register_into(table, &mut fused)
6378        .expect("CPU norm-backward contract must register into the binding table");
6379}
6380
6381/// The authored CPU RoPE kernel contract, embedded into the binary (the
6382/// PRODUCTION `include_str!`). `register_cpu_rope_from_contract` parses +
6383/// lowers it and binds the family FROM THE CONTRACT.
6384const CPU_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/rope.fkc.md");
6385
6386/// Register the CPU RoPE family (rotary position embedding; 1 op × 4 dtypes =
6387/// 4 bindings, key `[T, T, T, T]`) by IMPORTING its FKC kernel contract, the
6388/// ninth production FKC consumer. FKC is unconditional core infrastructure, so
6389/// this is the ONE registration path for the family: the hand-written
6390/// `table.register(Rope, ...)` calls it used to carry are DELETED.
6391///
6392/// Each of the 4 per-dtype sections (`## rope_f32`, `## rope_f64`,
6393/// `## rope_bf16`, `## rope_f16`) is a SPECIFIC single-dtype contract with a
6394/// concrete `entry_point` (`…::rope_f32`), so none of them fan — the importer
6395/// resolves each declared symbol AS-IS through the production
6396/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6397/// [`crate::fkc::CPU_ROPE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
6398/// CPU backend exposes. The binding key is `[T, T, T, T]` — RoPE takes THREE
6399/// inputs (`x` + the precomputed `cos`/`sin` tables of shape `[seq, head_dim]`,
6400/// all one dtype; the tables broadcast over the `outer_count` axis by the
6401/// kernel re-indexing them per outer, NOT a stride-0 view) and writes ONE
6402/// `passthrough(x)` output; outer_count / seq / head_dim ride in
6403/// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
6404/// `rope_dts(t)` regs.
6405///
6406/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6407/// caps (contiguous-only, even `head_dim`); the binding's `kernel_source`
6408/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6409/// bit-stable claim. Cost is preserved because this runs BEFORE
6410/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6411/// sentinel to the same OpKind cost fn every CPU primitive gets. This contract
6412/// has NO `##` chassis umbrella section, so there is nothing marked
6413/// `registrable: false` and no double-register risk. RoPE is ALSO registered in
6414/// the `FusedKernelRegistry` (`register_default_fused_kernels`,
6415/// `FusedOps::ROPE`) — that is a SEPARATE registry seam and stays untouched;
6416/// this migration only moves the `KernelBindingTable` primitive path. The
6417/// family declares NO fused ops, so `register_into`'s required fused argument is
6418/// a local throwaway that provably stays empty.
6419fn register_cpu_rope_from_contract(table: &mut KernelBindingTable) {
6420    let provider = crate::fkc::import_bundle_str(CPU_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6421        .expect(
6422            "authored CPU rope contract must import \
6423                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6424        );
6425    debug_assert!(
6426        provider.fused.is_empty(),
6427        "rope contract declares no fused ops",
6428    );
6429    let mut fused = crate::fused::FusedKernelRegistry::new();
6430    provider
6431        .register_into(table, &mut fused)
6432        .expect("CPU rope contract must register into the binding table");
6433}
6434
6435/// The authored CPU SSM / Mamba kernel contract, embedded into the binary (the
6436/// PRODUCTION `include_str!`). `register_cpu_ssm_from_contract` parses + lowers
6437/// it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6438const CPU_SSM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/ssm.fkc.md");
6439
6440/// Register the ENTIRE CPU SSM / Mamba family —
6441/// FusedSoftmaxCrossEntropy (key `[T, I64, F32]`) + CausalConv1d (key
6442/// `[T, T, T, T]`) + SelectiveScan + SsdChunkScan (key `[T; 6]`), 4 ops ×
6443/// 4 dtypes = 16 bindings — by IMPORTING its FKC kernel contract, the tenth
6444/// production FKC consumer. FKC is unconditional core infrastructure, so this is
6445/// the ONE registration path for the whole family: every hand-written
6446/// `table.register(...)` call is DELETED.
6447///
6448/// Each per-(op, dtype) section (`## fused_softmax_cross_entropy_f32`,
6449/// `## selective_scan_f32`, …) is a SPECIFIC single-dtype contract with a
6450/// concrete `entry_point` (`…::selective_scan_f32`), so none of them fan — the
6451/// importer resolves each declared symbol AS-IS through the production
6452/// [`crate::fkc::CpuLinkRegistry`] (chaining [`crate::fkc::CPU_SSM_ENTRY_POINTS`])
6453/// to the exact wrapper fn-pointer the CPU backend exposes. FSCE takes TWO inputs
6454/// (logits T + I64 targets) → ONE `fixed(F32)` output; CausalConv1d takes THREE
6455/// inputs (x, weight, bias) → ONE `passthrough(x)` output; every geometry/knob
6456/// rides in `OpParams`, NOT the dtype-list — identical keys to the deleted
6457/// hand-written regs.
6458///
6459/// **The two SCAN ops (SelectiveScan / SsdChunkScan) return a `return.bundle`**
6460/// multi-output (Option C: one packed buffer `[y ; last_state]`). The importer's
6461/// key-builder (`fkc/lower.rs` `assemble_dtype_variants`) appends the bundle's
6462/// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key tail,
6463/// so a 5-input scan section keys `[T; 6]` (5 inputs + the one bundled output
6464/// slot) — byte-for-byte the deleted hand-written
6465/// `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)` regs. All four
6466/// ops are now `registrable: true` (the default), so `lower_file` imports the
6467/// whole family.
6468///
6469/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6470/// caps (contiguous-only); the binding's
6471/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6472/// precision the contract's bit-stable claim. Cost is preserved because this
6473/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6474/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6475/// The family declares NO fused ops (the "fused" in FusedSoftmaxCrossEntropy is
6476/// an intra-op softmax+NLL fusion, not a graph `FusedOpId`), so `register_into`'s
6477/// required fused argument is a local throwaway that provably stays empty.
6478fn register_cpu_ssm_from_contract(table: &mut KernelBindingTable) {
6479    let provider = crate::fkc::import_bundle_str(CPU_SSM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6480        .expect(
6481            "authored CPU ssm contract must import \
6482                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6483        );
6484    debug_assert!(
6485        provider.fused.is_empty(),
6486        "ssm contract declares no fused ops",
6487    );
6488    let mut fused = crate::fused::FusedKernelRegistry::new();
6489    provider
6490        .register_into(table, &mut fused)
6491        .expect("CPU ssm contract must register into the binding table");
6492}
6493
6494/// The authored CPU 2D-convolution kernel contract, embedded into the binary
6495/// (the PRODUCTION `include_str!`). `register_cpu_conv_from_contract` parses +
6496/// lowers it and binds the MIGRATED (with-bias) subset of the family FROM THE
6497/// CONTRACT.
6498const CPU_CONV_CONTRACT: &str = include_str!("../kernel-contracts/cpu/conv.fkc.md");
6499
6500/// Register the CPU 2D-convolution family FULLY — Conv2D + ConvTranspose2D at
6501/// BOTH the no-bias key `[T, T, T]` (x, weight + out) and the with-bias key
6502/// `[T, T, T, T]` (x, weight, bias + passthrough(x) output), 2 ops × 4 dtypes ×
6503/// 2 operand-counts = 16 bindings — by IMPORTING its FKC kernel contract, the
6504/// eleventh production FKC consumer. FKC is unconditional core infrastructure,
6505/// so this is the ONE registration path for the whole family: every hand-written
6506/// `table.register(...)` conv call is DELETED.
6507///
6508/// Each per-(op, dtype) section (`## conv2d_f32`, `## conv_transpose2d_f32`, …)
6509/// is a SPECIFIC single-dtype contract with a concrete `entry_point`
6510/// (`…::conv2d_f32`), so none of them dtype-fan — the importer resolves each
6511/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6512/// (now chaining [`crate::fkc::CPU_CONV_ENTRY_POINTS`]) to the exact wrapper
6513/// fn-pointer the CPU backend exposes. Conv2D's weight is `[Cout, Cin/groups,
6514/// Kh, Kw]`; ConvTranspose2D's is the transposed `[Cin, Cout/groups, Kh, Kw]`
6515/// and it carries an extra `output_padding` op-param — but both are the same
6516/// (x, weight, optional bias) → one-output (passthrough(x)) accept shape, and
6517/// every geometry knob rides in `OpParams::{Conv2D, ConvTranspose2D}`, NOT the
6518/// dtype-list.
6519///
6520/// **The NO-BIAS key is now CONTRACT-SOURCED.** The conv contract declares
6521/// `bias` as `optional: true`, and the FKC importer's key-builder
6522/// (`fkc/lower.rs` `assemble_dtype_variants`) now supports optional operands: an
6523/// optional LAST input fans each section into TWO keys — one OMITTING `bias`
6524/// (`[T, T, T]`) and one INCLUDING it (`[T, T, T, T]`) — BOTH resolving the SAME
6525/// `entry_point`/wrapper (the same CPU wrapper handles 2 or 3 inputs). The
6526/// former no-bias deferral (hand-written `table.register(Conv2D /
6527/// ConvTranspose2D, &[dt; 3], ...)` regs) is closed and those regs deleted.
6528///
6529/// Behavior-preserving vs. the deleted hand-written path (for both operand-count
6530/// keys): identical kernels + caps (contiguous-only NCHW); the
6531/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6532/// precision the contract's bit-stable claim. Cost is preserved because this
6533/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6534/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6535/// The family declares NO fused ops (the SEPARATE FusedKernelRegistry
6536/// `FusedOps::{CONV2D, CONV_TRANSPOSE2D}` seam is hand-written, in
6537/// `register_default_fused_kernels`, and stays untouched), so `register_into`'s
6538/// required fused argument is a local throwaway that provably stays empty.
6539fn register_cpu_conv_from_contract(table: &mut KernelBindingTable) {
6540    let provider = crate::fkc::import_bundle_str(CPU_CONV_CONTRACT, &crate::fkc::CpuLinkRegistry)
6541        .expect(
6542            "authored CPU conv contract must import \
6543                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6544        );
6545    debug_assert!(
6546        provider.fused.is_empty(),
6547        "conv contract declares no fused ops",
6548    );
6549    let mut fused = crate::fused::FusedKernelRegistry::new();
6550    provider
6551        .register_into(table, &mut fused)
6552        .expect("CPU conv contract must register into the binding table");
6553}
6554
6555/// The authored CPU **padding** kernel contract, embedded into the binary (the
6556/// PRODUCTION `include_str!`). `register_cpu_padding_from_contract` parses +
6557/// lowers it and binds the FULL family (mode-unified forward `Pad` +
6558/// `PadBackward`) FROM THE CONTRACT.
6559const CPU_PADDING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/padding.fkc.md");
6560
6561/// Register the FULL CPU padding family — mode-unified forward `Pad` × 6 dtypes
6562/// = 6 + `PadBackward` × 4 dtypes = 4 bindings (all key `[T, T]`) — by IMPORTING
6563/// its FKC kernel contract, the twelfth production FKC consumer.
6564///
6565/// - **Forward `Pad`** — the ONE mode-unified `## pad` section declares a BASE
6566///   `entry_point` (`…::pad_cpu`, a synthetic umbrella — the three real mode
6567///   byte-kernels are `pad_{const,reflect,replicate}_cpu`) + the 6 production
6568///   dtypes (`U8/U32/BF16/F16/F32/F64`), so the importer's §3.4 fan-out resolves
6569///   `pad_cpu_<dtype>` — every dtype variant mapping to the ONE mode-dispatching
6570///   `pad_cpu_wrapper` (which selects Constant/Reflect/Replicate at runtime via
6571///   `mode_tag`, incl. the reflect `before/after <= n-1` validation) through the
6572///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6573///   [`crate::fkc::CPU_PADDING_ENTRY_POINTS`]). Key `[T, T]` (input +
6574///   `passthrough(input)` output; the in_shape/out_shape/padding/mode_tag/
6575///   fill_bytes ride in `OpParams::Pad`, NOT the dtype-list) — byte-for-byte the
6576///   deleted hand-written `table.register(Pad, &unary(t), …)` regs. The three
6577///   per-mode sections (`pad_const_cpu` / `pad_reflect_cpu` / `pad_replicate_cpu`)
6578///   and the `pad_walk_cpu` helper are `registrable: false` (§3.10 describe-only
6579///   mode documentation) and never resolve.
6580/// - **`PadBackward`** — each per-dtype section (`## pad_backward_f32`, …) carries
6581///   a SPECIFIC single-dtype `entry_point` (`…::pad_backward_f32`) resolved AS-IS
6582///   (no fan), key `[T, T]` (grad_out + `passthrough(grad_out)` grad_in; the
6583///   in_shape/out_shape/padding/mode_tag ride in `OpParams::PadBackward`) —
6584///   byte-for-byte the deleted `table.register(PadBackward, &unary(t), …)` regs.
6585///   `PadBackward` is per-dtype (unlike the dtype-agnostic forward `Pad`) because
6586///   gradient accumulation is typed (bf16/f16/f32 widen the scratch accumulator
6587///   to f64).
6588///
6589/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6590/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6591/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6592/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6593/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6594/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6595/// required fused argument is a local throwaway that provably stays empty.
6596fn register_cpu_padding_from_contract(table: &mut KernelBindingTable) {
6597    let provider =
6598        crate::fkc::import_bundle_str(CPU_PADDING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6599            "authored CPU padding contract must import \
6600                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6601        );
6602    debug_assert!(
6603        provider.fused.is_empty(),
6604        "padding contract declares no fused ops",
6605    );
6606    let mut fused = crate::fused::FusedKernelRegistry::new();
6607    provider
6608        .register_into(table, &mut fused)
6609        .expect("CPU padding contract must register into the binding table");
6610}
6611
6612/// The authored CPU **shape-ops** kernel contract, embedded into the binary (the
6613/// PRODUCTION `include_str!`). `register_cpu_shape_ops_from_contract` parses +
6614/// lowers it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6615const CPU_SHAPE_OPS_CONTRACT: &str = include_str!("../kernel-contracts/cpu/shape-ops.fkc.md");
6616
6617/// Register the MIGRATED CPU shape-ops subset — Flip + Roll + Concat +
6618/// MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels,
6619/// fanned per production dtype) and the four per-dtype CumSum kernels — by
6620/// IMPORTING its FKC kernel contract, the thirteenth production FKC consumer.
6621///
6622/// - **Flip** / **Roll** (key `[T, T]`, 6 dtypes each) and **Concat** (key
6623///   `[T, T]`, 9 dtypes) and **MaskedFill** (key `[T, U8, T]`, 6 dtypes) and
6624///   **WriteSlice** / **WriteSliceRotating** (key `[T, T]`, 6 dtypes each) are
6625///   ONE dtype-agnostic wrapper each. Their sections declare a BASE `entry_point`
6626///   (`…::flip_cpu`, …) + an enumerated `dtypes` list trimmed to the wired set,
6627///   so the §3.4 fan-out resolves `<base>_<dtype>` (`flip_cpu_f32`, …) — a
6628///   fabricated per-dtype symbol that every variant maps to the SAME wrapper via
6629///   [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`]. MaskedFill's `input` is the sole
6630///   varying operand; `mask` stays the fixed U8 slot and `out: passthrough(input)`,
6631///   so the fan emits `[T, U8, T]` — byte-for-byte the deleted
6632///   `table.register(MaskedFill, &masked_dtypes(t), …)` regs. **WriteSlice /
6633///   WriteSliceRotating** model `dest` as the in-place OUTPUT slot (not a key
6634///   input) and — for the rotating op — the U32 `position` as a NON-KEY runtime
6635///   operand (both handled by the executor's dedicated `Op::WriteSlice{,Rotating}`
6636///   arms), so a source-only + `out: passthrough(source)` section keys
6637///   `[T_source, T_out]` = `[T, T]` — byte-for-byte the deleted
6638///   `table.register(WriteSlice{,Rotating}, &unary(t), …)` regs and matching
6639///   `build_lookup_dtypes`' canonicalization exactly.
6640/// - **CumSum** (key `[T, T]`, 4 dtypes) is per-dtype typed accumulation, so each
6641///   `cumsum_<dt>` section carries a SPECIFIC single-dtype `entry_point` resolved
6642///   AS-IS (no fan) to its OWN typed wrapper.
6643///
6644/// **DEFERRED (describe-only, NOT imported).** `contiguize` and `triangular` are
6645/// `registrable: false` chassis/describe-only sections (no `OpKind::Contiguize` —
6646/// it is an executor materialize pass; `triangular` is the umbrella backing the
6647/// two hand-written `Triu`/`Tril` OpKinds with distinct wrappers, not a keyable
6648/// section). Those hand-written `Triu`/`Tril` regs stay authoritative.
6649///
6650/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6651/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6652/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6653/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6654/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6655/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6656/// required fused argument is a local throwaway that provably stays empty.
6657fn register_cpu_shape_ops_from_contract(table: &mut KernelBindingTable) {
6658    let provider =
6659        crate::fkc::import_bundle_str(CPU_SHAPE_OPS_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6660            "authored CPU shape-ops contract must import \
6661                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6662        );
6663    debug_assert!(
6664        provider.fused.is_empty(),
6665        "shape-ops contract declares no fused ops",
6666    );
6667    let mut fused = crate::fused::FusedKernelRegistry::new();
6668    provider
6669        .register_into(table, &mut fused)
6670        .expect("CPU shape-ops contract must register into the binding table");
6671}
6672
6673/// The authored CPU **matmul** kernel contract, embedded into the binary (the
6674/// PRODUCTION `include_str!`). `register_cpu_matmul_from_contract` parses +
6675/// lowers it and binds the FULL portable family FROM THE CONTRACT.
6676const CPU_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/cpu/matmul.fkc.md");
6677
6678/// Register the CPU **matmul** family FULLY — bare batched `MatMul` (6 dtypes,
6679/// key `[T, T, T]`) + fused `FusedLinear` (matmul + bias-add, 4 dtypes, key
6680/// `[T, T, T, T]`) = 10 bindings — by IMPORTING its FKC kernel contract, the
6681/// fourteenth production FKC consumer. FKC is unconditional core infrastructure,
6682/// so this is the ONE registration path for the PORTABLE kernels: every
6683/// hand-written `table.register(MatMul / FusedLinear, …)` portable-CPU call is
6684/// DELETED.
6685///
6686/// Each per-(op, dtype) section (`## matmul_f32`, `## fused_linear_f32`, …) is a
6687/// SPECIFIC single-dtype contract with a concrete `entry_point`
6688/// (`…::matmul_f32`), so none of them dtype-fan — the importer resolves each
6689/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6690/// (now chaining [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) to the exact wrapper
6691/// fn-pointer the CPU backend exposes. MatMul is 2-input (lhs, rhs) →
6692/// `passthrough(lhs)` output; FusedLinear is 3-input (a, b, bias) →
6693/// `passthrough(a)` output with `bias` a REQUIRED 1-D `[N]` operand (NOT
6694/// `optional`, so a single 4-slot key per dtype — no optional {absent, present}
6695/// fan). Both reuse `OpParams::Matmul` for shape, so every batch-geometry knob
6696/// (lhs_batch_dims/rhs_batch_dims/m/n/k) rides in `OpParams`, NOT the dtype-list.
6697/// The float variants (F32/F64/BF16/F16) accumulate in f32/native; the integer
6698/// MatMul variants (I8/U8) accumulate in i32 and SATURATE on store.
6699///
6700/// **Alternatives at the same key.** The binding table supports MULTIPLE ranked
6701/// kernels per `(op, dtypes, backend)` key. This importer registers ONLY the
6702/// portable (`kernel_source: "portable-cpu"`) kernels the contract covers; the
6703/// MKL / AOCL BLAS siblings live in SEPARATE external backend crates
6704/// (`fuel-mkl-cpu-backend` / `fuel-aocl-cpu-backend`), register through the
6705/// exported dispatch helpers with their own `"mkl"`/`"aocl"` `kernel_source`
6706/// tags as ranked alternatives at these SAME keys, and are out of scope here
6707/// (untouched — never registered in this crate's default build).
6708///
6709/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6710/// caps (contiguous-only, GQA-divisible batch); the binding's `kernel_source`
6711/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6712/// bit-stable claim. Cost is preserved because this runs BEFORE
6713/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6714/// sentinel to the same OpKind cost fn every CPU primitive gets. The family
6715/// declares NO fused ops (the SEPARATE `FusedKernelRegistry`
6716/// `FusedOps::FUSED_LINEAR` seam is hand-written, in
6717/// `register_default_fused_kernels`, and stays untouched — "fused" in
6718/// `FusedLinear` names an intra-op matmul+bias fusion, NOT a graph `FusedOpId`),
6719/// so `register_into`'s required fused argument is a local throwaway that
6720/// provably stays empty. The quant `QMatMul` / `Nf4Matmul` OpKinds have their
6721/// own contracts and stay hand-written.
6722fn register_cpu_matmul_from_contract(table: &mut KernelBindingTable) {
6723    let provider = crate::fkc::import_bundle_str(CPU_MATMUL_CONTRACT, &crate::fkc::CpuLinkRegistry)
6724        .expect(
6725            "authored CPU matmul contract must import \
6726                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6727        );
6728    debug_assert!(
6729        provider.fused.is_empty(),
6730        "matmul contract declares no fused ops",
6731    );
6732    let mut fused = crate::fused::FusedKernelRegistry::new();
6733    provider
6734        .register_into(table, &mut fused)
6735        .expect("CPU matmul contract must register into the binding table");
6736}
6737
6738/// The authored CPU **attention** kernel contract, embedded into the binary (the
6739/// PRODUCTION `include_str!`). `register_cpu_attention_from_contract` parses +
6740/// lowers it and binds the MIGRATED (`KernelBindingTable`) subset FROM THE
6741/// CONTRACT.
6742const CPU_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/cpu/attention.fkc.md");
6743
6744/// Register the CPU **attention** family's `KernelBindingTable` path FROM its FKC
6745/// kernel contract, the fifteenth production FKC consumer: forward `FlashAttn`
6746/// (4 dtypes) + `FlashAttnBackward{Q,K,V}` (3 selectors × 4 dtypes), each
6747/// `alibi_slopes`-optional section fanning into BOTH the no-alibi and with-alibi
6748/// keys = 4 × 4 × 2 = 32 bindings. FKC is unconditional core infrastructure, so
6749/// this is the ONE registration path for the migrated subset: the hand-written
6750/// `table.register(FlashAttn / FlashAttnBackward{Q,K,V}, …)` regs (both alibi
6751/// keys) are DELETED.
6752///
6753/// Each per-(op, dtype) section (`## flash_attn_f32`,
6754/// `## flash_attn_backward_q_f32`, …) declares a SPECIFIC single-dtype
6755/// `entry_point`, so none of them dtype-fan — the importer resolves each declared
6756/// symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`] (now
6757/// chaining [`crate::fkc::CPU_ATTENTION_ENTRY_POINTS`]) to the exact wrapper
6758/// fn-pointer. Because the contract marks `alibi_slopes` as `optional: true` (the
6759/// LAST input), the importer's key-builder (`fkc/lower.rs`
6760/// `assemble_dtype_variants`) fans each section into BOTH the no-alibi key
6761/// (`[q,k,v,out]` forward / `[q,k,v,do,out]` backward) and the with-alibi key
6762/// (`+alibi`) — both resolving the SAME `entry_point`/wrapper (the CPU wrapper
6763/// handles the presence/absence of the alibi operand). Forward FlashAttn AND the
6764/// three backward selectors share the single `OpParams::FlashAttn` carrier (there
6765/// is NO dedicated backward `OpParams` variant), so every softmax/mask geometry
6766/// knob rides in `OpParams`, NOT the dtype-list.
6767///
6768/// **PagedAttn is REGISTRABLE (`registrable: true`) and contract-sourced too.**
6769/// Its paged KV pool carries an `fdx.gather: paged_blocks` operand (§3.9.1), but
6770/// that block is import METADATA describing what an FDX view of the pool will
6771/// someday carry (FDX §6.9: "Description only: no cost, no decision"), NOT a
6772/// registration dependency: the as-built ABI passes `block_table` /
6773/// `context_lens` as ordinary U32 graph inputs + the geometry in
6774/// `OpParams::PagedAttn`, and the kernel reads them directly. So the importer
6775/// validates the gather block for COHERENCE (kind / requires_ext /
6776/// symbolic_extent / real block_table+context_lens roles) and registers the four
6777/// paged sections onto the `KernelBindingTable` at `(OpKind::PagedAttn,
6778/// [T,T,T,U32,U32,T](+[T]), Cpu)` — the optional-operand fan builds both alibi
6779/// keys, byte-for-byte the deleted hand-written `paged_attn_{no,with}_alibi`
6780/// regs. What remains [consumer-ahead] is only the FDX VIEW/materialize seam
6781/// (`view_with_gather` + `Capability::DlpackExtGather`), which has no consumer
6782/// yet. (The SEPARATE `FusedKernelRegistry` `PAGED_ATTN` seam stays hand-written,
6783/// exactly like `FLASH_ATTN`.)
6784///
6785/// Behavior-preserving vs. the deleted hand-written path (both alibi keys):
6786/// identical kernels + caps (contiguous-only); the binding's `kernel_source`
6787/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6788/// bit-stable claim. Cost is preserved because this runs BEFORE
6789/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6790/// sentinel to the same OpKind cost fn every CPU primitive gets (the CPU cost
6791/// dispatcher has `FlashAttn`/`PagedAttn` arms; the backward selectors keep
6792/// `unknown_cost`, exactly as under the deleted hand-written regs — they are not
6793/// on the cost-coverage lint's enumerated set). The family declares NO fused ops
6794/// (all sections are `op_kind:`, incl. the now-registrable PagedAttn), so
6795/// `register_into`'s required fused argument is a local throwaway that provably
6796/// stays empty. The
6797/// SEPARATE `FusedKernelRegistry` FLASH_ATTN* / PAGED_ATTN seam
6798/// (`register_default_fused_kernels`) is hand-written and stays untouched.
6799fn register_cpu_attention_from_contract(table: &mut KernelBindingTable) {
6800    let provider =
6801        crate::fkc::import_bundle_str(CPU_ATTENTION_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6802            "authored CPU attention contract must import \
6803                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6804        );
6805    debug_assert!(
6806        provider.fused.is_empty(),
6807        "attention contract declares no fused ops (all op_kind, incl. PagedAttn)",
6808    );
6809    let mut fused = crate::fused::FusedKernelRegistry::new();
6810    provider
6811        .register_into(table, &mut fused)
6812        .expect("CPU attention contract must register into the binding table");
6813}
6814
6815/// The authored CPU **in-place scalar-param** kernel contract, embedded into the
6816/// binary (the PRODUCTION `include_str!`). `register_cpu_inplace_from_contract`
6817/// parses + lowers it and binds the WHOLE family FROM THE CONTRACT.
6818const CPU_INPLACE_CONTRACT: &str =
6819    include_str!("../kernel-contracts/cpu/inplace-unary-affine.fkc.md");
6820
6821/// Register the CPU **in-place scalar-param** family's `KernelBindingTable` path
6822/// FROM its FKC kernel contract, the sixteenth production FKC consumer: 21
6823/// in-place unary ops (`<Op>Inplace`, each per-op section fanning `[F32,F64,
6824/// BF16,F16]` = 84 bindings) + `InplaceAffine` / `ClampInplace` / `PowIInplace`
6825/// (per-dtype single sections, 4 each = 12) = 96 bindings. FKC is unconditional
6826/// core infrastructure, so this is the ONE registration path for the whole
6827/// family: the hand-written `table.register(<Op>Inplace / InplaceAffine /
6828/// ClampInplace / PowIInplace, &unary(dt), …)` regs are DELETED.
6829///
6830/// Each per-op unary section (`## relu_inplace`, …) declares a BASE `entry_point`
6831/// (`…::relu_inplace`) + enumerates `dtypes: [F32,F64,BF16,F16]`, so the
6832/// importer's §3.4 multi-dtype fan-out resolves `<base>_<dtype>`
6833/// (`relu_inplace_f32`) through the production [`crate::fkc::CpuLinkRegistry`]
6834/// (now chaining [`crate::fkc::CPU_INPLACE_ENTRY_POINTS`]) to the exact wrapper
6835/// fn-pointer. The affine / clamp / powi sections are per-dtype SINGLE sections,
6836/// so they do NOT fan — their specific `<op>_inplace_<dt>` symbol resolves AS-IS
6837/// (the affine rows carry the three-way naming skew: symbol `affine_inplace_<dt>`
6838/// → wrapper `inplace_affine_<dt>_cpu_wrapper`, words swapped). Every binding
6839/// keys `[T, T]` (the single `out` operand + its `passthrough(out)` mirror; the
6840/// executor's `WorkItemKind::InplaceKernel` arm passes the target as
6841/// `outputs[0]`), byte-for-byte the deleted `&unary(dt)` regs. Scalar params
6842/// (affine `mul`/`add`, clamp `min`/`max`, powi `exp`) ride in
6843/// `OpParams::{Affine, Clamp, PowI}`, NOT the dtype-list.
6844///
6845/// The `## unary_inplace` chassis umbrella is `registrable: false` (§3.10
6846/// describe-only) — it binds no OpKind (each named op pins its own distinct
6847/// `<Op>Inplace`), so it never lowers/resolves and is excluded from
6848/// registration.
6849///
6850/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6851/// caps (contiguous-only, empty caps); the binding's `kernel_source` becomes the
6852/// contract's `"portable-cpu"` tag and its precision the contract's bit-stable
6853/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`: the
6854/// in-place OpKinds are NOT on the CPU cost-coverage lint's enumerated set and
6855/// have no arm in `default_cost_for_op_kind`, so they keep the `unknown_cost`
6856/// sentinel exactly as under the deleted hand-written regs. The family declares
6857/// NO fused ops (all sections are `op_kind:` or the describe-only umbrella), so
6858/// `register_into`'s required fused argument is a local throwaway that provably
6859/// stays empty.
6860fn register_cpu_inplace_from_contract(table: &mut KernelBindingTable) {
6861    let provider =
6862        crate::fkc::import_bundle_str(CPU_INPLACE_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6863            "authored CPU in-place contract must import \
6864                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6865        );
6866    debug_assert!(
6867        provider.fused.is_empty(),
6868        "in-place contract declares no fused ops (all op_kind or describe-only umbrella)",
6869    );
6870    let mut fused = crate::fused::FusedKernelRegistry::new();
6871    provider
6872        .register_into(table, &mut fused)
6873        .expect("CPU in-place contract must register into the binding table");
6874}
6875
6876/// The authored CPU **cast** kernel contract, embedded into the binary (the
6877/// PRODUCTION `include_str!`). `register_cpu_cast_from_contract` parses + lowers
6878/// it and binds the FULL directed-pair matrix FROM THE CONTRACT.
6879const CPU_CAST_CONTRACT: &str = include_str!("../kernel-contracts/cpu/cast.fkc.md");
6880
6881/// Register the CPU **cast** family FULLY — the COMPLETE directed-pair matrix,
6882/// every ordered pair of the 11 real numeric dtypes
6883/// {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with identity excluded =
6884/// 11 × 10 = 110 bindings (all key `[SRC, DST]`) — by IMPORTING its FKC kernel
6885/// contract.
6886///
6887/// Each per-pair section (`## cast_f64_to_f32`, …) declares a SPECIFIC
6888/// single-dtype `src` input + a `fixed(DST)` output, so none of them dtype-fan —
6889/// the importer's key-builder emits `[SRC, DST]` (the src input dtype + the
6890/// `fixed(DST)` output dtype, byte-for-byte the deleted hand-written
6891/// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the section's
6892/// SPECIFIC `cast_<src>_to_<dst>` byte-kernel `entry_point` AS-IS through the
6893/// production [`crate::fkc::CpuLinkRegistry`] (chaining
6894/// [`crate::fkc::CPU_CAST_ENTRY_POINTS`]). Because the binding lookup is keyed on
6895/// the TARGET dtype, all 10 of a target's source pairs bind the SAME per-target
6896/// `cast_to_<dst>_cpu_wrapper` (which `match`es on the source dtype internally) —
6897/// 10 distinct real byte-kernel entry_points → 1 wrapper (the synthetic-umbrella
6898/// precedent). This is the SOLE registration path for the whole family; every
6899/// hand-written `table.register(Cast, …)` reg is DELETED. Identity pairs
6900/// (`[T, T]`) are never registered — the optimizer elides identity `Cast` before
6901/// dispatch, and the per-target wrappers carry no identity arm.
6902///
6903/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6904/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6905/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6906/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6907/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6908/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6909/// required fused argument is a local throwaway that provably stays empty.
6910fn register_cpu_cast_from_contract(table: &mut KernelBindingTable) {
6911    let provider = crate::fkc::import_bundle_str(CPU_CAST_CONTRACT, &crate::fkc::CpuLinkRegistry)
6912        .expect(
6913            "authored CPU cast contract must import \
6914                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6915        );
6916    debug_assert!(
6917        provider.fused.is_empty(),
6918        "cast contract declares no fused ops",
6919    );
6920    let mut fused = crate::fused::FusedKernelRegistry::new();
6921    provider
6922        .register_into(table, &mut fused)
6923        .expect("CPU cast contract must register into the binding table");
6924}
6925
6926/// The authored CPU **indexing / gather / scatter** kernel contract, embedded
6927/// into the binary (the PRODUCTION `include_str!`).
6928/// `register_cpu_indexing_from_contract` parses + lowers it and binds the FULL
6929/// family (IndexSelect + Gather + IndexAdd + ScatterAdd) FROM THE CONTRACT.
6930const CPU_INDEXING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/indexing.fkc.md");
6931
6932/// Register the FULL CPU indexing family — IndexSelect (9 dtypes, key
6933/// `[T, U32, T]`) + Gather (9 dtypes, key `[T, U32, T]`) + IndexAdd (4 dtypes,
6934/// key `[T, U32, T, T]`) + ScatterAdd (4 dtypes, key `[T, U32, T, T]`) = 26
6935/// bindings — by IMPORTING its FKC kernel contract, the eighteenth production
6936/// FKC consumer.
6937///
6938/// - **IndexSelect** / **Gather** — the ONE section each declares a BASE
6939///   `entry_point` (`…::index_select_cpu` / `…::gather_cpu`, a dtype-agnostic
6940///   byte copy) + an enumerated `dtypes` list, so the importer's §3.4 fan-out
6941///   resolves `<base>_<dtype>` — every dtype variant mapping to the ONE
6942///   dtype-agnostic `index_select_cpu_wrapper` / `gather_cpu_wrapper` through the
6943///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6944///   [`crate::fkc::cpu_link::CPU_INDEXING_ENTRY_POINTS`]). The `indices` operand
6945///   is the FIXED U32 slot and `out: passthrough(source)`, so the fan emits key
6946///   `[T, U32, T]` — byte-for-byte the deleted hand-written
6947///   `table.register(IndexSelect/Gather, &index_select(dt)/&gather_dts(dt), …)`
6948///   regs. The contract's dtype list was trimmed to production's 9 wired dtypes
6949///   (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is describable (byte-agnostic) but
6950///   NOT wired in production, so it is dropped from the contract.
6951/// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
6952///   native, bf16/f16 widen to an f32 accumulator; out seeded from `base` then
6953///   `+= src`), so each `index_add_<dt>` / `scatter_add_<dt>` section carries a
6954///   SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan), key
6955///   `[T, U32, T, T]` (`base`, U32 `indices`, `src`, `passthrough(base)` output)
6956///   — byte-for-byte the deleted `table.register(IndexAdd/ScatterAdd, …)` regs.
6957///
6958/// The `indices` slot being a FIXED single-dtype (U32) in every section means
6959/// there is NO independent index-dtype axis and no multi-axis
6960/// `FanoutDtypeMismatch` deferral — the whole family migrates (unlike the metal
6961/// indexing situation).
6962///
6963/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6964/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6965/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6966/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6967/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6968/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6969/// required fused argument is a local throwaway that provably stays empty.
6970fn register_cpu_indexing_from_contract(table: &mut KernelBindingTable) {
6971    let provider =
6972        crate::fkc::import_bundle_str(CPU_INDEXING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6973            "authored CPU indexing contract must import \
6974                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6975        );
6976    debug_assert!(
6977        provider.fused.is_empty(),
6978        "indexing contract declares no fused ops",
6979    );
6980    let mut fused = crate::fused::FusedKernelRegistry::new();
6981    provider
6982        .register_into(table, &mut fused)
6983        .expect("CPU indexing contract must register into the binding table");
6984}
6985
6986/// Register CPU dispatch wrappers in the binding table. Call once
6987/// at process startup or on first table creation. The CPU backend
6988/// is the universal fallback; its bindings cover every standard
6989/// (op, dtype) combination after Phase C migration. Today's set
6990/// covers the elementwise binary + unary `f32` families.
6991pub fn register_cpu_kernels(table: &mut KernelBindingTable) {
6992    use OpKind::*;
6993    let cpu = BackendId::Cpu;
6994    let f32_dt = DType::F32;
6995    let f64_dt = DType::F64;
6996    let bf16_dt = DType::BF16;
6997    let f16_dt = DType::F16;
6998    let u32_dt = DType::U32;
6999
7000    // Per-operand dtype-list shape helpers. The list captures all
7001    // operands the kernel sees — inputs in order, then outputs.
7002    // Variadic Concat uses the `unary` shape as a canonical
7003    // shorthand for "uniform-dtype across N inputs + output."
7004    let unary = |t: DType| [t, t]; // (in, out)
7005    // (MatMul's (lhs, rhs, out) key shape is now built by the FKC importer from
7006    // fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
7007    // register_cpu_matmul_from_contract; the hand-written `binary` closure was
7008    // removed with its regs.)
7009    let u8_dt = DType::U8;
7010    // (Rope's (x, cos, sin, out) key shape is now built by the FKC importer
7011    // from fuel-dispatch/kernel-contracts/cpu/rope.fkc.md — see
7012    // register_cpu_rope_from_contract; the hand-written `rope_dts` closure was
7013    // removed with its regs.)
7014    // (Conv2D/ConvTranspose2D are now FULLY built by the FKC importer from
7015    // fuel-dispatch/kernel-contracts/cpu/conv.fkc.md — see register_cpu_conv_from_contract.
7016    // The contract marks `bias` as `optional: true`, so the importer's key-builder
7017    // now emits BOTH the no-bias (x, w, out) and with-bias (x, w, bias, out) keys
7018    // per (op, dtype); the hand-written `conv2d_with_bias` / `conv2d_no_bias`
7019    // closures + their regs were all removed.)
7020    // (FusedLinear's (lhs, rhs, bias, out) key shape is now built by the FKC
7021    // importer from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
7022    // register_cpu_matmul_from_contract; the hand-written `fused_linear` closure
7023    // was removed with its regs.)
7024    // FlashAttn / FlashAttnBackward{Q,K,V} / PagedAttn key-shape closures were
7025    // DELETED with the migration to FKC-contract registration (the importer's
7026    // optional-operand fan builds both alibi keys from the contract).
7027    // (IndexSelect/Gather's (data, indices, out) = [T, U32, T] and IndexAdd/
7028    // ScatterAdd's (base, indices, src, out) = [T, U32, T, T] key shapes are now
7029    // built by the FKC importer from fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md —
7030    // see register_cpu_indexing_from_contract; the hand-written `index_select` /
7031    // `gather_dts` / `index_add_dts` / `scatter_add` closures were removed with
7032    // their regs.)
7033
7034    // Elementwise binary family (8 ops × 4 dtypes = 32 bindings:
7035    // Add/Sub/Mul/Div/Maximum/Minimum/Pow/Rem × F32/F64/BF16/F16).
7036    //
7037    // This family is the FIRST production FKC-contract consumer: it is
7038    // IMPORTED from its kernel contract
7039    // (fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md), resolving every
7040    // `entry_point` symbol through the production `CpuLinkRegistry` to the
7041    // exact same wrapper fn-pointers the CPU backend exposes. The hand-written
7042    // `table.register(...)` calls this family used to carry are DELETED — FKC
7043    // is unconditional core infrastructure, so this is the sole registration
7044    // path (no build config, no fallback). Placed here — BEFORE the
7045    // `fill_unset_cpu_*` passes — so the imported entries pick up the same CPU
7046    // cost fill every other CPU primitive gets.
7047    register_cpu_binary_from_contract(table);
7048
7049    // Out-of-place scalar-param family (affine/clamp/powi × 4 dtypes +
7050    // powi_backward × 4 = 16 bindings). Second production FKC-contract
7051    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md
7052    // via the same `CpuLinkRegistry`. The hand-written `table.register(...)`
7053    // calls (Affine / ClampElementwise / PowIElementwise / PowIElementwiseBackward)
7054    // are DELETED — this is the sole registration path. Placed BEFORE the
7055    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7056    // fill. (The in-place InplaceAffine/ClampInplace/PowIInplace family and the
7057    // FusedOps::POWI_BACKWARD fused-registry seam are separate and untouched.)
7058    register_cpu_affine_clamp_powi_from_contract(table);
7059
7060    // Elementwise unary (22 ops × 4 dtypes = 88 bindings: relu/neg/sqr/sqrt/
7061    // recip/abs/tanh/exp/log/sin/cos/sigmoid/silu/step/gelu_tanh/floor/ceil/round/
7062    // sign/erf/gelu/rsqrt × F32/F64/BF16/F16). Third production FKC-contract
7063    // consumer and the FIRST user of the §3.4 multi-dtype fan-out: IMPORTED from
7064    // fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md via the same
7065    // `CpuLinkRegistry`. Each per-op section declares a BASE entry_point that the
7066    // importer expands to `<base>_<dtype>`. The hand-written `table.register(...)`
7067    // calls (the F32/F64/BF16/F16 unary blocks + the rounding/sign/erf/gelu/
7068    // rsqrt block) are DELETED — this is the sole registration path. Placed
7069    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7070    // cost fill. gelu_tanh (GeluTanhElementwise) and gelu (GeluElementwise)
7071    // stay DISTINCT.
7072    register_cpu_unary_from_contract(table);
7073
7074    // Compare (6 ops × 4 dtypes = 24, key [T, T, U8]) + where (1 op × 4 dtypes
7075    // = 4, key [U8, T, T, T]) = 28 bindings. Fourth production FKC-contract
7076    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md via
7077    // the same `CpuLinkRegistry`. The 24 compare thunks resolve their declared
7078    // `_u8`-suffixed symbols AS-IS; the single `where_kernel` section rides the
7079    // §3.4 multi-dtype fan-out (BASE `…::where` → `where_{f32,f64,bf16,f16}`)
7080    // and the `passthrough(a)` output rule. The hand-written `table.register(...)`
7081    // calls (the compare block + the `where_dts` block) are DELETED — this is the
7082    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7083    // imported entries pick up the CPU cost fill.
7084    register_cpu_compare_where_from_contract(table);
7085
7086    // Per-axis reduce (Sum/Mean/Max/Min × 4 dtypes = 16 bindings, key [T, T]).
7087    // Fifth production FKC-contract consumer: IMPORTED from
7088    // fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md via the same `CpuLinkRegistry`.
7089    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7090    // (`sum_reduce_f32`, …) resolved AS-IS (no fan-out). The hand-written
7091    // `table.register(...)` calls (the F32/F64 + BF16/F16 reduce blocks) are
7092    // DELETED — this is the sole registration path. Placed BEFORE the
7093    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7094    // fill. The `## reduce` chassis is `registrable: false` (§3.10) and the
7095    // f32-only argmax/argmin sections are deferred (registrable: false); the
7096    // hand-written Arg{Max,Min}Dim regs below stay authoritative.
7097    register_cpu_reduce_from_contract(table);
7098
7099    // Broadcast-target reduce-to (ReduceSumTo / ReduceMaxTo × 4 dtypes, key
7100    // [T, T]; ReduceMaxToBackward × 4 dtypes, key [T, T, T] = 12 bindings).
7101    // Sixth production FKC-contract consumer: IMPORTED from
7102    // fuel-dispatch/kernel-contracts/cpu/reduce-to.fkc.md via the same `CpuLinkRegistry`.
7103    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7104    // (`reduce_sum_to_f32`, …) resolved AS-IS (no fan-out). The hand-written
7105    // `table.register(...)` calls (the ReduceSumTo/ReduceMaxTo forward block +
7106    // the ReduceMaxToBackward block) are DELETED — this is the sole registration
7107    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
7108    // pick up the CPU cost fill. The `## reduce_to` chassis is
7109    // `registrable: false` (§3.10) and never registers.
7110    register_cpu_reduce_to_from_contract(table);
7111
7112    // Last-dim NORM forward (Softmax / LogSoftmax / RmsNorm / LayerNorm × 4
7113    // dtypes = 16 bindings, key [T, T]). Seventh production FKC-contract
7114    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm.fkc.md via the same
7115    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7116    // single-dtype entry_point (`softmax_last_dim_f32`, `rms_norm_last_dim_f32`,
7117    // …) resolved AS-IS (no fan-out). The RMS/LayerNorm kernels are the BARE
7118    // normalization (no affine gamma/beta operand); outer_count/last_dim/eps ride
7119    // in OpParams, so the key stays [T, T]. The hand-written `table.register(...)`
7120    // calls (the LogSoftmaxLastDim block above + the SoftmaxLastDim / RmsNormLastDim
7121    // / LayerNormLastDim block below) are DELETED — this is the sole registration
7122    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
7123    // pick up the CPU cost fill. The norm ops' SEPARATE FusedKernelRegistry seam
7124    // (register_default_fused_kernels) and the norm-BACKWARD hand-written regs stay
7125    // untouched.
7126    register_cpu_norm_from_contract(table);
7127
7128    // Last-dim NORM BACKWARD (Softmax / LogSoftmax / RmsNorm / LayerNorm backward
7129    // × 4 dtypes = 16 bindings, key [T, T, T]). Eighth production FKC-contract
7130    // consumer and the BACKWARD sibling of the norm-forward importer above:
7131    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm-backward.fkc.md via the same
7132    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7133    // single-dtype entry_point (`softmax_last_dim_backward_f32`,
7134    // `rms_norm_last_dim_backward_f32`, …) resolved AS-IS (no fan-out). The BARE
7135    // backward takes TWO inputs (y/x + upstream gradient g) → ONE passthrough
7136    // output, so the key is [T, T, T]; outer_count/last_dim/eps ride in OpParams.
7137    // The hand-written `table.register(...)` calls (the LogSoftmaxLastDimBackward
7138    // block + the SoftmaxLastDimBackward / LayerNormLastDimBackward /
7139    // RmsNormLastDimBackward block below) are DELETED — this is the sole
7140    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7141    // imported entries pick up the CPU cost fill. The norm-backward ops' SEPARATE
7142    // FusedKernelRegistry seam (register_default_fused_kernels) stays untouched.
7143    register_cpu_norm_backward_from_contract(table);
7144
7145    // RoPE (rotary position embedding; 1 op × 4 dtypes = 4 bindings, key
7146    // [T, T, T, T]). Ninth production FKC-contract consumer: IMPORTED from
7147    // fuel-dispatch/kernel-contracts/cpu/rope.fkc.md via the same `CpuLinkRegistry`.
7148    // Each per-dtype section carries a SPECIFIC single-dtype entry_point
7149    // (`rope_f32`, …) resolved AS-IS (no fan-out). RoPE takes THREE inputs
7150    // (x + the precomputed cos/sin tables, all one dtype) → ONE passthrough(x)
7151    // output, so the key is [T, T, T, T]; outer_count/seq/head_dim ride in
7152    // OpParams::Rope. The hand-written `table.register(Rope, ...)` calls (the
7153    // rope_dts block below) are DELETED — this is the sole registration path.
7154    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick
7155    // up the CPU cost fill. RoPE's SEPARATE FusedKernelRegistry seam
7156    // (register_default_fused_kernels, FusedOps::ROPE) stays untouched.
7157    register_cpu_rope_from_contract(table);
7158
7159    // CPU SSM / Mamba family — the FULL family: FusedSoftmaxCrossEntropy
7160    // (key [T, I64, F32]) + CausalConv1d (key [T, T, T, T]) + SelectiveScan +
7161    // SsdChunkScan (key [T; 6]), 4 ops × 4 dtypes = 16 bindings. Tenth
7162    // production FKC-contract consumer: IMPORTED from
7163    // fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md via the same `CpuLinkRegistry`. Each
7164    // per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
7165    // (`fused_softmax_cross_entropy_f32`, `selective_scan_f32`, …) resolved AS-IS
7166    // (no fan-out). The two SCAN ops return a `return.bundle` multi-output
7167    // (Option C, one buffer [y ; last_state]); the importer now appends the
7168    // bundle's primary-slot dtype to the key tail, so they key [T; 6]
7169    // byte-for-byte the deleted hand-written regs. Every hand-written
7170    // `table.register(...)` call for the whole family is DELETED — this is its
7171    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7172    // imported entries pick up the CPU cost fill.
7173    register_cpu_ssm_from_contract(table);
7174
7175    // NonZeroIndices — the keystone primitive for data-dependent dynamic
7176    // shapes (SSM decode / MoE sparsity / MLA KV compression). One input
7177    // `x` → one bundled output `[indices [capacity] U32 ; count [1] U32]`;
7178    // the binding key is `[input_dtype, U32]` (input + primary output-slot
7179    // dtype). Registered DIRECTLY (not yet FKC-contract-sourced): the
7180    // op's U32 output slot is a *constant* dtype, not a `passthrough` of a
7181    // T input, which the current contract key-builder does not express —
7182    // so this bring-up primitive registers by hand and is a candidate to
7183    // migrate once a data-dependent-ops contract family grows. Placed
7184    // BEFORE the `fill_unset_cpu_*` passes so the entries pick up the CPU
7185    // precision + cost fill (UNAUDITED → PRIMITIVE_DETERMINISTIC_CPU,
7186    // unknown_cost → the OpKind cost fn).
7187    table.register(
7188        NonZeroIndices,
7189        &[f32_dt, u32_dt],
7190        cpu,
7191        nonzero_indices_f32_cpu_wrapper,
7192    );
7193    table.register(
7194        NonZeroIndices,
7195        &[u32_dt, u32_dt],
7196        cpu,
7197        nonzero_indices_u32_cpu_wrapper,
7198    );
7199
7200    // CPU 2D-convolution family — FULLY contract-sourced: Conv2D +
7201    // ConvTranspose2D at BOTH the no-bias key [T, T, T] (x, weight, out) AND the
7202    // with-bias key [T, T, T, T] (x, weight, bias + passthrough(x) output), 2 ops
7203    // × 4 dtypes × 2 operand-counts = 16 bindings. Eleventh production
7204    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/conv.fkc.md
7205    // via the same `CpuLinkRegistry`. Each per-(op,dtype) section carries a
7206    // SPECIFIC single-dtype entry_point (`conv2d_f32`, `conv_transpose2d_f32`, …)
7207    // resolved AS-IS (no dtype fan-out); every geometry knob rides in
7208    // OpParams::{Conv2D, ConvTranspose2D}. The contract marks `bias` as
7209    // `optional: true`, so the importer's optional-operand key-builder fans each
7210    // section into both the no-bias and with-bias keys (same wrapper handles 2 or
7211    // 3 inputs) — ALL hand-written conv `table.register(...)` calls are DELETED,
7212    // this is the sole registration path for the whole family. Placed BEFORE the
7213    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost fill.
7214    // The conv ops' SEPARATE FusedKernelRegistry seam
7215    // (register_default_fused_kernels, FusedOps::{CONV2D, CONV_TRANSPOSE2D}) stays
7216    // untouched.
7217    register_cpu_conv_from_contract(table);
7218
7219    // CPU padding family (FULL) — mode-unified forward Pad × 6 dtypes = 6 +
7220    // PadBackward × 4 dtypes = 4 bindings (all key [T, T]). Twelfth production
7221    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/padding.fkc.md
7222    // via the same `CpuLinkRegistry`. The ONE mode-unified `## pad` forward section
7223    // declares a BASE entry_point (`pad_cpu`) + the 6 wired dtypes (U8/U32/BF16/
7224    // F16/F32/F64), so the fan resolves `pad_cpu_<dtype>` (all → the one
7225    // mode-dispatching `pad_cpu_wrapper`, which selects Constant/Reflect/Replicate
7226    // at runtime via mode_tag); each per-dtype backward section carries a SPECIFIC
7227    // single-dtype entry_point (`pad_backward_f32`, …) resolved AS-IS (no fan).
7228    // in_shape/out_shape/padding/mode_tag/fill_bytes ride in OpParams::{Pad,
7229    // PadBackward}. The three per-mode forward sections + the pad_walk_cpu helper
7230    // are `registrable: false` describe-only. ALL hand-written forward + backward
7231    // `table.register(Pad/PadBackward, …)` regs are DELETED — this is their sole
7232    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
7233    // imported entries pick up the CPU cost fill.
7234    register_cpu_padding_from_contract(table);
7235
7236    // CPU shape-ops family (migratable subset) — Flip + Roll + Concat +
7237    // MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels
7238    // fanned per production dtype: Flip/Roll/MaskedFill/WriteSlice/
7239    // WriteSliceRotating 6 dtypes, Concat 9) + the four per-dtype CumSum kernels.
7240    // Thirteenth production FKC-contract consumer: IMPORTED from
7241    // fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md via the same `CpuLinkRegistry`.
7242    // Flip/Roll/Concat/MaskedFill/WriteSlice/WriteSliceRotating sections declare a
7243    // BASE entry_point + a dtypes list trimmed to the wired set, so the fan
7244    // resolves `<base>_<dtype>` (all → the one dtype-agnostic wrapper); CumSum's
7245    // per-dtype sections resolve their SPECIFIC `cumsum_<dt>` symbol AS-IS. Keys:
7246    // Flip/Roll/Concat/CumSum/WriteSlice/WriteSliceRotating [T, T], MaskedFill
7247    // [T, U8, T]. WriteSlice/WriteSliceRotating model `dest` as the in-place
7248    // OUTPUT slot (and rotating's `position` as a non-key runtime operand), so the
7249    // imported key matches build_lookup_dtypes' canonicalized [T_src, T_out]. The
7250    // migrated hand-written regs are DELETED — this is their sole registration
7251    // path. DEFERRED (hand-written kept): Triu/Tril (the contract carries only the
7252    // `triangular` describe-only chassis) + Contiguize (no OpKind — an executor
7253    // materialize pass). Placed BEFORE the `fill_unset_cpu_*` passes so the
7254    // imported entries pick up the CPU cost fill.
7255    register_cpu_shape_ops_from_contract(table);
7256
7257    // CPU matmul family — FULLY contract-sourced (PORTABLE kernels): bare
7258    // batched MatMul (6 dtypes F32/F64/BF16/F16/I8/U8, key [T, T, T]) + fused
7259    // FusedLinear (matmul + bias-add, 4 dtypes F32/F64/BF16/F16, key
7260    // [T, T, T, T]) = 10 bindings. Fourteenth production FKC-contract consumer:
7261    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md via the same
7262    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7263    // single-dtype entry_point (`matmul_f32`, `fused_linear_f32`, …) resolved
7264    // AS-IS (no fan-out); the batch geometry (lhs_batch_dims/rhs_batch_dims/
7265    // m/n/k) rides in OpParams::Matmul (FusedLinear reuses it). Integer MatMul
7266    // (I8/U8) accumulates in i32 and saturates on store. Every hand-written
7267    // portable `table.register(MatMul / FusedLinear, …)` call is DELETED — this
7268    // is the sole registration path for the portable family. Placed BEFORE the
7269    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7270    // fill. ALTERNATIVES-AT-KEY: the MKL/AOCL BLAS siblings register at these
7271    // SAME keys from SEPARATE external crates with their own `"mkl"`/`"aocl"`
7272    // kernel_source tags — SEPARATE and untouched (not registered in this build).
7273    // The SEPARATE FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7274    // (register_default_fused_kernels) is hand-written and stays untouched; the
7275    // quant QMatMul/Nf4Matmul OpKinds have their own contracts and stay
7276    // hand-written below.
7277    register_cpu_matmul_from_contract(table);
7278
7279    // The CPU ATTENTION family's KernelBindingTable path — forward FlashAttn (4
7280    // dtypes) + FlashAttnBackward{Q,K,V} (3 selectors × 4 dtypes) + PagedAttn (4
7281    // dtypes), each alibi-optional section fanning into BOTH the no-alibi and
7282    // with-alibi keys = 40 bindings — is now registered FROM
7283    // fuel-dispatch/kernel-contracts/cpu/attention.fkc.md by
7284    // register_cpu_attention_from_contract. The contract marks `alibi_slopes`
7285    // as `optional: true`, so the importer's key-builder fans each (op, dtype)
7286    // section into both operand-count keys; FKC is the SOLE path for the migrated
7287    // family. All hand-written FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn
7288    // regs (both alibi keys) were DELETED. PagedAttn's fdx.gather pool is import
7289    // METADATA (§3.9.1: it dispatches via ordinary U32 block_table/context_lens
7290    // operands + OpParams::PagedAttn), so it registers here too; only the FDX VIEW
7291    // seam stays [consumer-ahead]. The SEPARATE FusedKernelRegistry
7292    // FLASH_ATTN*/PAGED_ATTN seam (register_default_fused_kernels) is untouched.
7293    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up
7294    // the CPU cost fill.
7295    register_cpu_attention_from_contract(table);
7296
7297    // The CPU IN-PLACE scalar-param family's KernelBindingTable path — 21 in-place
7298    // unary ops (each per-op section fanning [F32,F64,BF16,F16] = 84) +
7299    // InplaceAffine / ClampInplace / PowIInplace (per-dtype single sections, 4 each
7300    // = 12) = 96 bindings, all keyed [T, T] — is now registered FROM
7301    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7302    // register_cpu_inplace_from_contract. FKC is the SOLE path for the whole
7303    // family; all hand-written <Op>Inplace / InplaceAffine / ClampInplace /
7304    // PowIInplace regs were DELETED. The `unary_inplace` chassis section is
7305    // describe-only (registrable: false). Placed BEFORE the `fill_unset_cpu_*`
7306    // passes; the in-place OpKinds keep the `unknown_cost` sentinel (no arm in
7307    // default_cost_for_op_kind, not on the cost-coverage lint set) — identical to
7308    // the deleted hand-written regs.
7309    register_cpu_inplace_from_contract(table);
7310
7311    // (bf16 + f16 reductions are now registered from the reduce contract above,
7312    // alongside the f32/f64 variants — accumulate in f32 for stability.)
7313
7314    // Cast — the COMPLETE directed-pair matrix: every ordered pair of the 11
7315    // real numeric dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with
7316    // identity excluded = 11 × 10 = 110 bindings (all key `[SRC, DST]`) — is now
7317    // registered FROM fuel-dispatch/kernel-contracts/cpu/cast.fkc.md by
7318    // register_cpu_cast_from_contract. Each per-pair section declares a
7319    // single-dtype `src` input + a `fixed(DST)` output (no dtype fan), so the
7320    // importer keys `[SRC, DST]` and resolves the SPECIFIC `cast_<src>_to_<dst>`
7321    // byte-kernel entry_point AS-IS; because the lookup is keyed on the TARGET
7322    // dtype, all 10 of a target's source pairs bind the SAME per-target
7323    // `cast_to_<dst>_cpu_wrapper` (10 real entry_points → 1 wrapper). FKC is the
7324    // SOLE path for the whole family; all hand-written `table.register(Cast, …)`
7325    // regs were DELETED. Identity pairs are never registered — the optimizer
7326    // elides identity Cast before dispatch. The MX dummy dtypes
7327    // (F6E2M3,F6E3M2,F4,F8E8M0) have no Rust scalar type and are excluded. Placed
7328    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7329    // cost/precision fill.
7330    register_cpu_cast_from_contract(table);
7331
7332    // CPU indexing / gather / scatter family — IndexSelect + Gather
7333    // (dtype-agnostic byte copies fanned per dtype: 9 dtypes each, key
7334    // [T, U32, T], the fabricated `<base>_<dt>` symbol resolving to the ONE
7335    // wrapper) + IndexAdd + ScatterAdd (per-dtype typed accumulation: 4 dtypes
7336    // each, key [T, U32, T, T], `<op>_<dt>` resolved AS-IS). Eighteenth
7337    // production FKC consumer: IMPORTED from
7338    // fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md via the same `CpuLinkRegistry`.
7339    // The `indices` slot is a FIXED U32 operand in every section (no independent
7340    // index-dtype axis), so there is no multi-axis fan-out deferral — the whole
7341    // family migrates. The contract's index_select/gather dtype list is trimmed
7342    // to production's 9 wired dtypes (I8 describable but NOT wired). ALL
7343    // hand-written `table.register(IndexSelect/Gather/IndexAdd/ScatterAdd, …)`
7344    // regs are DELETED — this is their sole registration path. Placed BEFORE the
7345    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7346    // cost/precision fill.
7347    register_cpu_indexing_from_contract(table);
7348
7349    // Conv2D / ConvTranspose2D — BOTH the no-bias key [T, T, T] (x, weight, out)
7350    // AND the with-bias key [T, T, T, T] (x, weight, bias, out) are now registered
7351    // FROM the conv FKC contract (`register_cpu_conv_from_contract`, above). The
7352    // contract marks `bias` as `optional: true`, so the importer's key-builder
7353    // fans each (op, dtype) section into both operand-count keys — FKC is the SOLE
7354    // path for the whole conv family (16 bindings). All hand-written conv regs were
7355    // DELETED (the no-bias deferral is closed).
7356
7357    // ReduceSumTo / ReduceMaxTo (× 4 dtypes, key [T, T]) are now registered
7358    // FROM the reduce-to FKC contract (`register_cpu_reduce_to_from_contract`,
7359    // above) — the hand-written regs were DELETED (FKC is the sole path). The
7360    // ReduceMaxToBackward regs (key [T, T, T]) below were likewise deleted.
7361
7362    // FusedLinear (3 inputs lhs, rhs, bias → out; key [T, T, T, T]) is now
7363    // registered FROM the matmul FKC contract
7364    // (`register_cpu_matmul_from_contract`, above) — the hand-written regs were
7365    // DELETED (FKC is the sole path for the portable family). The SEPARATE
7366    // FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7367    // (`register_default_fused_kernels`) is hand-written and stays untouched.
7368
7369    // FlashAttn (forward) + FlashAttnBackward{Q,K,V} + PagedAttn — both the
7370    // no-alibi and with-alibi keys per dtype — are now registered FROM the
7371    // attention FKC contract (`register_cpu_attention_from_contract`, near the top
7372    // of this fn). The contract marks `alibi_slopes` as `optional: true`, so the
7373    // importer's key-builder fans each (op, dtype) section into both operand-count
7374    // keys — FKC is the SOLE path for the migrated attention family (40 bindings:
7375    // FlashAttn 8 + FlashAttnBackward{Q,K,V} 24 + PagedAttn 8). All hand-written
7376    // FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn regs (both alibi keys) were
7377    // DELETED. PagedAttn's `fdx.gather: paged_blocks` pool is import METADATA
7378    // (§3.9.1): block_table/context_lens ride as ordinary U32 operands +
7379    // OpParams::PagedAttn, so registration does not depend on the FDX gather VIEW
7380    // (that stays [consumer-ahead]).
7381
7382    // (Affine F32 is now registered from the affine-clamp-powi contract above.)
7383
7384    // The in-place scalar-param family — InplaceAffine / ClampInplace /
7385    // PowIInplace (each key [T, T], scalars in OpParams::{Affine, Clamp, PowI}) —
7386    // is now registered FROM fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md
7387    // by register_cpu_inplace_from_contract near the top of this fn (alongside the
7388    // 21 in-place unary ops). The affine sections' op_kind was corrected from the
7389    // out-of-place `Affine` to `InplaceAffine`; all hand-written in-place scalar
7390    // regs were DELETED with the migration.
7391
7392    // The ENTIRE CPU SSM / Mamba family — FusedSoftmaxCrossEntropy (key
7393    // [T, I64, F32]), CausalConv1d (key [T, T, T, T]), and the two SCAN ops
7394    // SelectiveScan / SsdChunkScan (key [T; 6] — 5 inputs + the ONE bundled
7395    // output slot) — is now registered from fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md
7396    // by register_cpu_ssm_from_contract near the top of this fn. The scans'
7397    // `return.bundle` multi-output is now key-buildable by the importer (it
7398    // appends the bundle's primary-slot dtype to the key tail), so their
7399    // hand-written `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)`
7400    // loops that used to live here were DELETED with the migration.
7401
7402    // Nf4Matmul: 3 inputs (activations T, w_packed U8, absmax F32) + 1
7403    // output T, where T ∈ {F32, F16, BF16}. The binding-table key
7404    // shape is [T, U8, F32, T].
7405    table.register(
7406        Nf4Matmul,
7407        &[DType::F32, DType::U8, DType::F32, DType::F32],
7408        cpu,
7409        nf4_matmul_f32_cpu_wrapper,
7410    );
7411    table.register(
7412        Nf4Matmul,
7413        &[DType::F16, DType::U8, DType::F32, DType::F16],
7414        cpu,
7415        nf4_matmul_f16_cpu_wrapper,
7416    );
7417    table.register(
7418        Nf4Matmul,
7419        &[DType::BF16, DType::U8, DType::F32, DType::BF16],
7420        cpu,
7421        nf4_matmul_bf16_cpu_wrapper,
7422    );
7423
7424    // The 21 in-place unary activations (Relu/Silu/GeluTanh/Tanh/Sigmoid/Neg/Abs/
7425    // Sqr/Sqrt/Rsqrt/Recip/Exp/Log/Sin/Cos/Sign/Floor/Ceil/Round/Erf/Gelu ×
7426    // F32/F64/BF16/F16 = 84 bindings, each key [T, T]) are now registered FROM
7427    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7428    // register_cpu_inplace_from_contract near the top of this fn: each per-op
7429    // section declares a BASE entry_point `<op>_inplace` + enumerates
7430    // [F32,F64,BF16,F16], so the importer's §3.4 dtype fan resolves
7431    // `<op>_inplace_<dt>` to the exact wrapper. All hand-written in-place unary
7432    // regs (the 5-op starter set + the 16-op expansion loop) were DELETED with
7433    // the migration; the shared `unary_inplace` chassis section is describe-only.
7434
7435    // (ClampElementwise / PowIElementwise F32 are now registered from the
7436    // affine-clamp-powi contract above.)
7437
7438    // Comparison (6 ops × 4 dtypes, key [T, T, U8]) + ternary select `where`
7439    // (4 dtypes, key [U8, T, T, T]) are now registered FROM the compare-where
7440    // FKC contract via register_cpu_compare_where_from_contract (near the top of
7441    // this fn) — the hand-written regs (and the `compare` / `where_dts`
7442    // dtype-list closures) are DELETED.
7443
7444    // Rounding / sign / transcendental unary ops (floor/ceil/round/sign/erf/
7445    // gelu/rsqrt × F32/F64/BF16/F16) are registered from the elementwise-unary
7446    // FKC contract via register_cpu_unary_from_contract (near the top of this fn).
7447
7448    // (Flip / Roll × 6 dtypes [T, T] and CumSum × 4 dtypes [T, T] are now
7449    // registered FROM the shape-ops FKC contract via
7450    // register_cpu_shape_ops_from_contract near the top of this fn — Flip/Roll are
7451    // one dtype-agnostic wrapper fanned per dtype; CumSum's per-dtype typed
7452    // sections resolve AS-IS. The hand-written regs were DELETED — FKC is the sole
7453    // path.)
7454
7455    // (WriteSlice + WriteSliceRotating × 6 dtypes, key [T, T], are now registered
7456    // FROM the shape-ops FKC contract via register_cpu_shape_ops_from_contract
7457    // near the top of this fn — one dtype-agnostic wrapper each, fanned per dtype.
7458    // Both model `dest` as the in-place OUTPUT slot (and rotating's `position` as a
7459    // non-key runtime operand), so the imported key matches build_lookup_dtypes'
7460    // canonicalized `[T_src, T_out]`. The hand-written regs were DELETED — FKC is
7461    // the sole path.)
7462
7463    // Triu / Tril share one byte-level kernel (dtype-agnostic).
7464    table.register(Triu, &unary(f32_dt), cpu, triu_cpu_wrapper);
7465    table.register(Triu, &unary(f64_dt), cpu, triu_cpu_wrapper);
7466    table.register(Triu, &unary(bf16_dt), cpu, triu_cpu_wrapper);
7467    table.register(Triu, &unary(f16_dt), cpu, triu_cpu_wrapper);
7468    table.register(Triu, &unary(u32_dt), cpu, triu_cpu_wrapper);
7469    table.register(Triu, &unary(u8_dt), cpu, triu_cpu_wrapper);
7470    table.register(Tril, &unary(f32_dt), cpu, tril_cpu_wrapper);
7471    table.register(Tril, &unary(f64_dt), cpu, tril_cpu_wrapper);
7472    table.register(Tril, &unary(bf16_dt), cpu, tril_cpu_wrapper);
7473    table.register(Tril, &unary(f16_dt), cpu, tril_cpu_wrapper);
7474    table.register(Tril, &unary(u32_dt), cpu, tril_cpu_wrapper);
7475    table.register(Tril, &unary(u8_dt), cpu, tril_cpu_wrapper);
7476
7477    // (LogSoftmaxLastDim × 4 dtypes is now registered FROM the norm FKC contract
7478    // via register_cpu_norm_from_contract near the top of this fn, alongside
7479    // Softmax / RmsNorm / LayerNorm forward.)
7480
7481    // (SoftmaxLastDimBackward / LogSoftmaxLastDimBackward / LayerNormLastDimBackward
7482    // / RmsNormLastDimBackward × 4 dtypes = 16 bindings, key [T, T, T]) are now
7483    // registered FROM the norm-backward FKC contract via
7484    // register_cpu_norm_backward_from_contract near the top of this fn — the BARE
7485    // backward (two inputs y/x + upstream gradient g → one passthrough output;
7486    // outer_count/last_dim/eps in OpParams). Their SEPARATE FusedKernelRegistry
7487    // seam (register_default_fused_kernels) stays untouched.
7488    // ReduceMaxToBackward (× 4 dtypes, key [T, T, T]) is now registered FROM the
7489    // reduce-to FKC contract (`register_cpu_reduce_to_from_contract`); the
7490    // hand-written regs were DELETED (FKC is the sole path).
7491
7492    // (MaskedFill × 6 dtypes, key [T, U8, T] — x dtype, mask U8, output == x — is
7493    // now registered FROM the shape-ops FKC contract via
7494    // register_cpu_shape_ops_from_contract near the top of this fn: `input` is the
7495    // sole varying operand that drives the fan, `mask` is the fixed U8 slot, and
7496    // `out: passthrough(input)`. The hand-written regs + the `masked_dtypes`
7497    // closure were DELETED — FKC is the sole path.)
7498
7499    // (Pad forward (Constant/Reflect/Replicate) × 6 dtypes — key [T, T], one
7500    // dtype-agnostic `pad_cpu_wrapper` dispatching all three modes at runtime via
7501    // `mode_tag` — is now registered FROM the padding FKC contract via
7502    // register_cpu_padding_from_contract near the top of this fn. The contract's
7503    // ONE mode-unified `## pad` section fans its 6 wired dtypes (U8/U32/BF16/F16/
7504    // F32/F64), ALL resolving `pad_cpu_wrapper`; the three per-mode sections +
7505    // the pad_walk_cpu helper are `registrable: false` describe-only. The
7506    // hand-written regs were DELETED — FKC is the sole path for the forward half.)
7507
7508    // (PadBackward × 4 dtypes — key [T, T], typed accumulation — is likewise
7509    // registered FROM the padding FKC contract via
7510    // register_cpu_padding_from_contract near the top of this fn; the
7511    // hand-written regs were DELETED — FKC is the sole path for the backward
7512    // half.)
7513
7514    // (Elementwise unary BF16 + F16 — like F32/F64 — are registered from the
7515    // elementwise-unary FKC contract via register_cpu_unary_from_contract near
7516    // the top of this fn; the importer fans each per-op section over all four
7517    // dtypes. The binary bf16/f16 ops likewise come from the elementwise-binary
7518    // contract.)
7519
7520    // (Concat — a variadic uniform-dtype op (N inputs, all the same dtype, plus
7521    // output) — is now registered FROM the shape-ops FKC contract via
7522    // register_cpu_shape_ops_from_contract near the top of this fn: the importer
7523    // treats the variadic list as ONE representative input, so the fan builds the
7524    // canonical `[T, T]` shorthand key per supported dtype (9 dtypes; the lookup
7525    // site collapses the actual N+1 dtype list to this same shorthand). The
7526    // hand-written loop was DELETED — FKC is the sole path.)
7527
7528    // (SoftmaxLastDim / RmsNormLastDim / LayerNormLastDim × 4 dtypes are now
7529    // registered FROM the norm FKC contract via register_cpu_norm_from_contract
7530    // near the top of this fn — key [T, T], bare normalization, no affine operand.
7531    // Their SEPARATE FusedKernelRegistry seam and the norm-backward regs stay
7532    // hand-written.)
7533
7534    // (IndexSelect / Gather × 9 dtypes (key [T, U32, T]) are now registered FROM
7535    // the indexing FKC contract via register_cpu_indexing_from_contract above —
7536    // one dtype-agnostic wrapper each, fanned per dtype from a BASE entry_point.
7537    // The hand-written loop was DELETED — FKC is the sole path.)
7538
7539    // (Rope × 4 dtypes is now registered FROM the rope FKC contract via
7540    // register_cpu_rope_from_contract near the top of this fn — key
7541    // [T, T, T, T] (x, cos, sin + passthrough output), geometry in
7542    // OpParams::Rope. Its SEPARATE FusedKernelRegistry seam
7543    // (register_default_fused_kernels, FusedOps::ROPE) stays hand-written.)
7544
7545    // QMatMul: F32 activations, U32 weight blocks, F32 output.
7546    table.register(
7547        QMatMul,
7548        &[f32_dt, u32_dt, f32_dt],
7549        cpu,
7550        qmatmul_f32_cpu_wrapper,
7551    );
7552
7553    // (IndexAdd / ScatterAdd × 4 dtypes (key [T, U32, T, T]) are now registered
7554    // FROM the indexing FKC contract via register_cpu_indexing_from_contract
7555    // above — each per-dtype `<op>_<dt>` entry_point resolved AS-IS to its OWN
7556    // typed wrapper. The hand-written regs were DELETED — FKC is the sole path.)
7557
7558    // ArgMax/ArgMin: input dtype varies, output is U32. The dispatch
7559    // wrapper still does its internal input-dtype match (preserves
7560    // current behavior). Register `[input_dt, U32]` once per input
7561    // dtype the dispatcher handles so the binding table can also
7562    // route directly when we collapse the wrapper later.
7563    for dt in [f32_dt, f64_dt, bf16_dt, f16_dt] {
7564        table.register(ArgMaxDim, &[dt, u32_dt], cpu, argmax_dim_u32_cpu_dispatch);
7565        table.register(ArgMinDim, &[dt, u32_dt], cpu, argmin_dim_u32_cpu_dispatch);
7566    }
7567
7568    // (Affine F64/BF16/F16 are now registered from the affine-clamp-powi
7569    // contract above.)
7570
7571    // Op::Copy — D2H / SameDevice byte-level transfer. The CPU
7572    // registration here is the CPU→CPU memcpy noop; per-source-
7573    // backend registrations live in their dispatch crates
7574    // (`register_cuda_kernels`, `vulkan_dispatch::register_vulkan_kernels`).
7575    // Bridge-retirement Phase 2 (post-9c): every realize root that
7576    // isn't on CPU gets an `Op::Copy { target: Cpu }` spliced in
7577    // before realize; the kernel dispatch resolves on the *source*
7578    // backend's BackendId. CPU→CPU is registered for uniformity (the
7579    // splice doesn't fire when device == Cpu, but kernels registered
7580    // here let direct executor tests round-trip through OpKind::Copy
7581    // on the universal fallback).
7582    let copy_dtypes = [
7583        f32_dt,
7584        f64_dt,
7585        bf16_dt,
7586        f16_dt,
7587        u32_dt,
7588        u8_dt,
7589        DType::I16,
7590        DType::I32,
7591        DType::I64,
7592        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7593        // Op::Copy to materialize a result to host.
7594        DType::Bool,
7595    ];
7596    for dt in copy_dtypes {
7597        table.register(Copy, &[dt, dt], cpu, copy_from_cpu_wrapper);
7598    }
7599    // (ClampElementwise / PowIElementwise F64/BF16/F16 and the two-input
7600    // PowIElementwiseBackward × 4 dtypes are now registered from the
7601    // affine-clamp-powi contract above. The FusedOps::POWI_BACKWARD
7602    // fused-registry seam remains separate and untouched.)
7603
7604    // Phase 7.6 step 7b — populate `PrecisionGuarantee` for every
7605    // CPU primitive registration. Every `table.register(...)` call
7606    // above defaulted to `PrecisionGuarantee::UNAUDITED`; this fill
7607    // pass upgrades them to `PRIMITIVE_DETERMINISTIC_CPU` (bit-stable
7608    // per hardware, deterministic iteration order, F32 accumulator
7609    // for half-precision). Sites that need a weaker claim should
7610    // call `table.register_with_precision(...)` explicitly *before*
7611    // this point — those won't be overwritten because the fill only
7612    // touches UNAUDITED entries.
7613    //
7614    // The architecture-target shape is precision-per-call-site,
7615    // but the 335+ CPU primitive registrations all share the same
7616    // deterministic property; bulk-applying the claim here keeps
7617    // the call sites concise while still ensuring every entry
7618    // carries an explicit, non-UNAUDITED PrecisionGuarantee that the
7619    // step-7b coverage lint can enforce.
7620    table.fill_unset_cpu_precision(crate::fused::PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU);
7621
7622    // Phase 7.6 step 8 — populate cost functions for every CPU
7623    // primitive registration. Every `table.register(...)` call
7624    // above defaulted to `unknown_cost`; this fill pass dispatches
7625    // each entry to its OpKind-appropriate cost-family function
7626    // (per `crate::cost::default_cost_for_op_kind`). Sites that
7627    // need a non-default cost claim should call
7628    // `table.register_full(...)` with their own `CostFn` *before*
7629    // this point — those won't be overwritten because the fill
7630    // only touches entries still bound to `unknown_cost`.
7631    //
7632    // Architecturally this is the same shape as the precision fill
7633    // above: bulk-apply the family-default at the end so the 335
7634    // CPU registration call sites stay concise, while the lint
7635    // (`precision_guarantee_lint_bit_stable_cpu_coverage_primitives`
7636    // companion: `cost_lint_per_op_kind_cpu_coverage`) enforces
7637    // that every OpKind ends up with a non-default cost function.
7638    table.fill_unset_cpu_cost(crate::cost::default_cost_for_op_kind);
7639}
7640
7641// =============================================================================
7642// Phase 7.5 — CUDA dispatch wrappers + registration
7643// =============================================================================
7644//
7645// First CUDA op through the unified binding table. Mirrors the CPU
7646// extractor + wrapper pattern but operates on `CudaStorageBytes`.
7647// Only `(AddElementwise, F32, Cuda)` is registered today; this is the
7648// "smallest possible first commit" that proves the CUDA migration
7649// pattern. Subsequent commits fan out to the rest of the op surface
7650// using the same wrapper-macro shape.
7651
7652/// Helper: extract `&CudaStorageBytes` from `&Storage`. Returns
7653/// Err if the variant isn't `BackendStorage::Cuda`.
7654#[cfg(feature = "cuda")]
7655pub fn cuda_input(s: &Storage) -> Result<&fuel_cuda_backend::CudaStorageBytes> {
7656    match &s.inner {
7657        BackendStorage::Cuda(c) => Ok(c),
7658        #[allow(unreachable_patterns)]
7659        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA input".to_string()).bt()),
7660    }
7661}
7662
7663/// Helper: extract `&mut CudaStorageBytes` from `&mut Storage`.
7664#[cfg(feature = "cuda")]
7665pub fn cuda_output(s: &mut Storage) -> Result<&mut fuel_cuda_backend::CudaStorageBytes> {
7666    match &mut s.inner {
7667        BackendStorage::Cuda(c) => Ok(c),
7668        #[allow(unreachable_patterns)]
7669        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA output".to_string()).bt()),
7670    }
7671}
7672
7673/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cuda)` — copy FROM a
7674/// CUDA source storage. The key is the SOURCE backend; the
7675/// destination is whatever the executor pre-allocated the output as
7676/// (see [`crate::pipelined::WorkItemKind::Copy`]), so the wrapper
7677/// routes on the output's variant:
7678///
7679/// - **CPU output** → D2H via `CudaStorageBytes::to_cpu_bytes`
7680///   (the realize-root path; the original sole behavior).
7681/// - **CUDA output** → device-to-device via
7682///   `CudaStorageBytes::slot_copy_to_new` (one `memcpy_dtod`).
7683///   Same-device copies are emitted by `insert_safety_copies` for
7684///   destructive ops on GPU-placed tensors and by the residency
7685///   machinery — before this routing existed, any such Copy errored
7686///   with "cpu kernel wrapper called with non-CPU output"
7687///   (residency_eviction_live caught it).
7688///
7689/// Dtype-agnostic at the byte level — one wrapper covers every dtype
7690/// registered at this key.
7691///
7692/// Phase 2 of the bridge-retirement trajectory (post-9c). Replaces
7693/// the CUDA branch of `BackendStorage::read_to_cpu_bytes` (deleted
7694/// alongside).
7695#[cfg(feature = "cuda")]
7696fn copy_from_cuda_wrapper(
7697    inputs: &[Arc<RwLock<Storage>>],
7698    outputs: &mut [Arc<RwLock<Storage>>],
7699    _layouts: &[Layout],
7700    _params: &OpParams,
7701) -> Result<()> {
7702    if inputs.len() != 1 || outputs.len() != 1 {
7703        return Err(Error::Msg(format!(
7704            "copy_from_cuda_wrapper: expected 1 input + 1 output, got {} + {}",
7705            inputs.len(),
7706            outputs.len(),
7707        ))
7708        .bt());
7709    }
7710    let in_guard = read_storage(&inputs[0])?;
7711    // The key is the SOURCE backend: keep the typed error for a non-CUDA input.
7712    cuda_input(&in_guard)?;
7713    let mut out_guard = write_storage(&outputs[0])?;
7714    // The per-pair transfer (CPU output: finer D2H, no whole-device synchronize, the executor waited the
7715    // producer's CompletionHandle; CUDA output: write-into, no allocation, capture-safe) lives in
7716    // `BackendStorage::copy_from` (ROADMAP row 137, seam S3 step 2).
7717    out_guard.inner.copy_from(&in_guard.inner)
7718}
7719
7720/// Phase 7.5 CUDA registration — now `Op::Copy` D2H only.
7721///
7722/// **Scope (post-alpha.67, 2026-06-10):** every compute kernel has
7723/// migrated to `register_baracuda_cuda_kernels` — baracuda is the
7724/// single CUDA kernel home. The final migrations (answering
7725/// `docs/baracuda-ask-fp-gemm-reduce-to-2026-06-10.md`):
7726///
7727/// - **MatMul** (f32/f64/f16/bf16) → Phase 74 `gemm_dense` facade;
7728///   the local cuBLAS f32 path and CUTLASS bf16/f16 byte paths
7729///   retired with `byte_kernels`.
7730/// - **ReduceSumTo / ReduceMaxTo** (4 dtypes) → baracuda's
7731///   `reduce_{sum,max}_to_*` (sys symbols shipped since alpha.46).
7732/// - **CausalConv1d** → registration moved (was always
7733///   baracuda-backed via the Fuel-prepad bridge).
7734///
7735/// What stays: **Op::Copy** — D2H byte-buffer transfer, a
7736/// Fuel-specific cross-device path that lives at this layer rather
7737/// than in any kernel crate.
7738#[cfg(feature = "cuda")]
7739pub fn register_cuda_kernels(table: &mut KernelBindingTable) {
7740    use OpKind::*;
7741    let cuda = BackendId::Cuda;
7742
7743    // Op::Copy D2H — register at `(OpKind::Copy, [dt, dt], Cuda)` for
7744    // every dtype the byte-storage substrate supports. Source-backend
7745    // key (= Cuda); the wrapper produces a CPU output, copying through
7746    // `CudaStorageBytes::to_cpu_bytes`. Bridge-retirement Phase 2.
7747    let copy_dtypes = [
7748        DType::F32,
7749        DType::BF16,
7750        DType::F16,
7751        DType::U32,
7752        DType::F64,
7753        DType::U8,
7754        DType::I16,
7755        DType::I32,
7756        DType::I64,
7757        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7758        // `Op::Copy { target: Cpu }` to materialize a device result to host, so
7759        // WITHOUT this every realized CUDA comparison fails to dispatch. This is a
7760        // byte-level transfer via `to_cpu_bytes`, so no new kernel is required —
7761        // only the registration. Mirrors the CPU list above, which already has it.
7762        DType::Bool,
7763    ];
7764    for dt in copy_dtypes {
7765        table.register(Copy, &[dt, dt], cuda, copy_from_cuda_wrapper);
7766    }
7767}
7768
7769// =============================================================================
7770// Phase 7.5 B5+ — process-wide singleton (CapabilityRegistry + KernelBindingTable)
7771// =============================================================================
7772
7773/// Process-wide [`CapabilityRegistry`]. Initialized on first access
7774/// via [`global_registry`]; the CPU backend is auto-registered
7775/// always (universal fallback). Other backends register themselves
7776/// during their initialization or app startup.
7777///
7778/// Tests that need a private registry should construct one
7779/// directly with `CapabilityRegistry::new()` rather than touch the
7780/// global.
7781static GLOBAL_REGISTRY: OnceLock<RwLock<CapabilityRegistry>> = OnceLock::new();
7782
7783/// Process-wide topology generation counter. Bumped whenever the
7784/// set of registered backends / loaded kernels changes — so a
7785/// [`crate::topology::SystemTopology`] snapshot built at
7786/// generation N self-invalidates the next time a consumer asks for
7787/// a fresh view and the counter is N+1 or greater. See the
7788/// system-topology session prompt for the contract.
7789///
7790/// The two existing global-registry mutation sites
7791/// ([`register_backend_capabilities`] and [`extend_global_bindings`])
7792/// bump this counter unconditionally. Tests and a future device-loss
7793/// detector hook in via [`bump_topology_generation`].
7794static TOPOLOGY_GENERATION: AtomicU64 = AtomicU64::new(0);
7795
7796/// Read the current topology generation. Used by SystemTopology's
7797/// `current()` to decide whether its cached snapshot is still valid.
7798pub fn topology_generation() -> u64 {
7799    TOPOLOGY_GENERATION.load(Ordering::Acquire)
7800}
7801
7802/// Bump the topology generation counter. Every component that can
7803/// change the visible set of backends or devices should call this
7804/// after the mutation lands so consumers see a self-healing
7805/// `SystemTopology::current()` next call. Cheap (one atomic add);
7806/// `Release` ordering pairs with the `Acquire` load in
7807/// `topology_generation`.
7808pub fn bump_topology_generation() {
7809    // Test builds only: a test that needs the generation to hold still (it
7810    // optimizes a graph and then realizes it, and the executor returns
7811    // `Error::TopologyChanged` if the generation moved in between) holds
7812    // `TOPOLOGY_TEST_GATE` for writing; every bump waits on it for reading.
7813    // Without this, any other test in the same binary that registers a
7814    // kernel or backend can bump mid-way (ROADMAP row 165).
7815    #[cfg(test)]
7816    let _gate = TOPOLOGY_TEST_GATE
7817        .read()
7818        .unwrap_or_else(|poisoned| poisoned.into_inner());
7819    TOPOLOGY_GENERATION.fetch_add(1, Ordering::Release);
7820}
7821
7822/// Test-only gate; see [`bump_topology_generation`]. A holder must not call
7823/// anything that bumps the generation while it holds the write guard (that
7824/// would wait on itself): initialise the lazily built globals first.
7825#[cfg(test)]
7826pub(crate) static TOPOLOGY_TEST_GATE: RwLock<()> = RwLock::new(());
7827
7828// =============================================================================
7829// Step E Phase C / B1 — per-device in-flight async-op counter (the load signal)
7830// =============================================================================
7831
7832/// Process-wide per-[`DeviceLocation`] in-flight async-op counter — the
7833/// "queue depth / slot utilization" load signal `06-runtime` names. The
7834/// same idiom as [`TOPOLOGY_GENERATION`]: a lazily-initialized
7835/// process-wide table the executor mutates and a runtime selector reads.
7836///
7837/// **What it counts.** The number of GPU operations the executor has
7838/// SUBMITTED but not yet observed completed, per device. It is a
7839/// *fuel-internal* count derived from the A4b async-completion handle
7840/// lifecycle ([`compiled::execute_compiled`]'s CUDA event +
7841/// `pipelined`'s eager-submitted Vulkan batches), NOT a driver query
7842/// (`cuStreamQuery` is a busy/idle bool, not a depth). One `+1` per
7843/// async submit ([`inflight_inc`]), one `-1` per completion-handle
7844/// retirement ([`inflight_dec`], fired from the handle's `Drop`).
7845///
7846/// **Narrowed by "event only where waited" (A4b open question #4).** A CUDA
7847/// node the `pipelined` executor's `WaitSet` pre-scan elides never builds a
7848/// `CudaCompletion` at all (`produce_pending` returns `Ready` directly, no
7849/// `Event`, no `inc`/`dec`) — see `compiled::execute_compiled_with_wait_hint`.
7850/// So on `OrderSource::Default`/`Optimized` realizes this counter now tracks
7851/// only WAITED CUDA work (cross-device `Copy`/`Move` producers, plus whatever
7852/// handles are still alive when sampled) rather than literally every enqueued
7853/// op — same-device-only kernels never touch it, elided or not, on the theory
7854/// that they were never individually observable before this change either
7855/// (only swept up in the old per-node drain). `OrderSource::Streaming` — the
7856/// ONLY order source the production load-aware picker
7857/// (`ranker::DeviceLoadSelector` / `ChainedSelector`'s `load_tier` leg)
7858/// actually reads THIS counter through — never elides (falls back to
7859/// event-every-node), so the picker's own live-load signal is unaffected;
7860/// the narrowing only bites a caller reading `inflight_count` for a
7861/// *different*, concurrently-running `Default`/`Optimized` realize on the
7862/// same device, which would now under-report that realize's true same-device
7863/// backlog. No production caller does this today.
7864///
7865/// **Honesty / correctness.** This is a SCHEDULING HINT, never a
7866/// correctness gate — correctness rests entirely on the A4b waits (which for
7867/// elided nodes now come from `pipelined::sync_active_cuda_devices`'s
7868/// realize-end blanket stream sync instead of a per-node `Event`). So
7869/// the atomics are [`Ordering::Relaxed`] (no memory to synchronize) and
7870/// [`inflight_dec`] is underflow-saturating: a hint that briefly
7871/// mis-reads costs at most a sub-optimal route, never a wrong result.
7872///
7873/// **CPU.** Keyed uniformly by `DeviceLocation`, but the CPU dispatch
7874/// path is synchronous and never builds an async completion handle, so
7875/// `inflight_count(DeviceLocation::Cpu)` is always 0 — no special-case
7876/// needed. A `BackendStreams` impl reports CPU as `None` (no queue
7877/// concept) regardless (see `fuel-tensor::pipelined_bridge`).
7878static DEVICE_INFLIGHT: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU32>>> = OnceLock::new();
7879
7880fn device_inflight_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU32>> {
7881    DEVICE_INFLIGHT.get_or_init(|| RwLock::new(HashMap::new()))
7882}
7883
7884/// Increment the in-flight async-op count for `loc` — called when the
7885/// executor SUBMITS an async op (the same site that builds an A4b
7886/// completion handle). Cheap: a single relaxed `fetch_add` once the
7887/// per-device slot exists (the slot is created once, under a brief write
7888/// lock, on the first submit to a device). A poisoned lock is swallowed
7889/// (the counter is a hint; a poisoned table just stops tracking — never
7890/// a panic on a production path).
7891pub fn inflight_inc(loc: DeviceLocation) {
7892    let table = device_inflight_table();
7893    // Fast path: slot already exists — read lock + relaxed add, no map mutation.
7894    if let Ok(guard) = table.read()
7895        && let Some(slot) = guard.get(&loc)
7896    {
7897        slot.fetch_add(1, Ordering::Relaxed);
7898        return;
7899    }
7900    // Slow path: create the slot. `entry().or_insert` is idempotent under the
7901    // write lock, so a racing inc that took the same slow path is harmless —
7902    // whichever lands second sees the slot and adds to it.
7903    if let Ok(mut guard) = table.write() {
7904        guard
7905            .entry(loc)
7906            .or_insert_with(|| AtomicU32::new(0))
7907            .fetch_add(1, Ordering::Relaxed);
7908    }
7909}
7910
7911/// Decrement the in-flight async-op count for `loc` — called when an A4b
7912/// completion handle RETIRES (its `Drop`). Underflow-saturating: if the
7913/// slot is missing or already 0 this is a no-op, so an unexpected extra
7914/// dec can never wrap the count to `u32::MAX` and poison future
7915/// scheduling. (Under the balance invariant — every `inc` is matched by
7916/// exactly one `dec` via the handle's `Drop` — this saturation never
7917/// actually fires; it is pure defense.)
7918pub fn inflight_dec(loc: DeviceLocation) {
7919    let table = device_inflight_table();
7920    if let Ok(guard) = table.read()
7921        && let Some(slot) = guard.get(&loc)
7922    {
7923        // saturating: never wrap below 0.
7924        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7925            Some(v.saturating_sub(1))
7926        });
7927    }
7928}
7929
7930/// Read the current in-flight async-op count for `loc`. The signal a
7931/// load-aware selector consults (Step E Phase C / C2, via
7932/// `BackendStreams::pending_work_count`). 0 for a device that has never
7933/// submitted async work (including CPU, which never submits any).
7934pub fn inflight_count(loc: DeviceLocation) -> u32 {
7935    let table = device_inflight_table();
7936    table
7937        .read()
7938        .ok()
7939        .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7940        .unwrap_or(0)
7941}
7942
7943/// Per-device ESTIMATED BACKLOG in nanoseconds: the executor's own
7944/// submitted-but-unfinished work x each op's estimated cost (row 158 slice
7945/// 2). Sibling of [`DEVICE_INFLIGHT`] (which counts ops); this sums their
7946/// estimated time, so a route picker can tell a 1 us queue from a 1 h one.
7947///
7948/// A slot exists only for a device that has had [`backlog_add_ns`] called, and
7949/// [`backlog_estimate_ns`] returns `None` until then: a device nobody feeds
7950/// reports NO estimate (never a fabricated "0 ns idle"), so a selector falls
7951/// back to the queue-depth tier. Relaxed atomics; a scheduling hint, never a
7952/// correctness gate; [`backlog_sub_ns`] saturates at 0.
7953static DEVICE_BACKLOG_NS: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU64>>> = OnceLock::new();
7954
7955fn device_backlog_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU64>> {
7956    DEVICE_BACKLOG_NS.get_or_init(|| RwLock::new(HashMap::new()))
7957}
7958
7959/// Add `ns` of estimated work to `loc`'s backlog (call at submit, with the
7960/// op's estimated cost). Saturating; a poisoned lock stops tracking.
7961pub fn backlog_add_ns(loc: DeviceLocation, ns: u64) {
7962    let table = device_backlog_table();
7963    let add = |slot: &AtomicU64| {
7964        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7965            Some(v.saturating_add(ns))
7966        });
7967    };
7968    if let Ok(guard) = table.read()
7969        && let Some(slot) = guard.get(&loc)
7970    {
7971        add(slot);
7972        return;
7973    }
7974    if let Ok(mut guard) = table.write() {
7975        add(guard.entry(loc).or_insert_with(|| AtomicU64::new(0)));
7976    }
7977}
7978
7979/// Remove `ns` from `loc`'s backlog (call when the work it was added for
7980/// retires). Saturates at 0; a no-op for a device never fed.
7981pub fn backlog_sub_ns(loc: DeviceLocation, ns: u64) {
7982    if let Ok(guard) = device_backlog_table().read()
7983        && let Some(slot) = guard.get(&loc)
7984    {
7985        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7986            Some(v.saturating_sub(ns))
7987        });
7988    }
7989}
7990
7991/// The estimated backlog for `loc` in ns, or `None` when nothing has ever
7992/// been fed for it (no estimate; NOT idle).
7993pub fn backlog_estimate_ns(loc: DeviceLocation) -> Option<u64> {
7994    device_backlog_table()
7995        .read()
7996        .ok()
7997        .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7998}
7999
8000/// Name of the environment variable that turns the executor's backlog feed ON (any of `1`, `true`, `on`,
8001/// `yes`). The feed is OFF by default: with it on, a real Qwen3-0.6B Q4_K_M decode on Vulkan resolved ~85%
8002/// of its branches to the CPU arm and ran slower than without it (ROADMAP row 158, n = 3 alternating
8003/// pairs, direction only, one model, Vulkan only); the backlog accumulates within a realize and drains only at its end (ROADMAP row 158 CAUSE). Set the variable,
8004/// or call [`set_backlog_feed_enabled`], to measure it.
8005pub const BACKLOG_FEED_ENV: &str = "FUEL_BACKLOG_FEED";
8006
8007/// 0 = no override (read [`BACKLOG_FEED_ENV`]), 1 = forced on, 2 = forced off.
8008static BACKLOG_FEED_OVERRIDE: AtomicU32 = AtomicU32::new(0);
8009
8010/// Force the executor's backlog feed on or off for this process, overriding [`BACKLOG_FEED_ENV`]. For the
8011/// tests and probes that measure the feed.
8012pub fn set_backlog_feed_enabled(on: bool) {
8013    BACKLOG_FEED_OVERRIDE.store(if on { 1 } else { 2 }, Ordering::Relaxed);
8014}
8015
8016/// Seeded mutant for the acceptance test (`FUEL_BACKLOG_NO_RETIRE=1`): the feed never takes an estimate
8017/// back out until the realize ends, which is the cumulative behaviour that sent ~85% of a real model's
8018/// branches to the CPU arm (ROADMAP row 158). A test seam, never set in production.
8019pub(crate) fn backlog_retire_disabled() -> bool {
8020    static FROM_ENV: OnceLock<bool> = OnceLock::new();
8021    *FROM_ENV.get_or_init(|| {
8022        std::env::var("FUEL_BACKLOG_NO_RETIRE").is_ok_and(|v| {
8023            matches!(
8024                v.trim().to_ascii_lowercase().as_str(),
8025                "1" | "true" | "on" | "yes"
8026            )
8027        })
8028    })
8029}
8030
8031/// Whether the executor adds its in-flight work to the device backlog (default: no).
8032pub(crate) fn backlog_feed_enabled() -> bool {
8033    match BACKLOG_FEED_OVERRIDE.load(Ordering::Relaxed) {
8034        1 => true,
8035        2 => false,
8036        _ => {
8037            static FROM_ENV: OnceLock<bool> = OnceLock::new();
8038            *FROM_ENV.get_or_init(|| {
8039                std::env::var(BACKLOG_FEED_ENV).is_ok_and(|v| {
8040                    matches!(
8041                        v.trim().to_ascii_lowercase().as_str(),
8042                        "1" | "true" | "on" | "yes"
8043                    )
8044                })
8045            })
8046        }
8047    }
8048}
8049
8050/// What one realize added to the per-device backlog, taken back out when the realize ends (ROADMAP row
8051/// 158, the executor feed). The executor owns one for the length of a walk and calls [`Self::add`] for
8052/// each kernel it submits to a GPU, with that node's compile-time estimate
8053/// ([`crate::compiled::CompiledNode::est_ns`]); the guard's `Drop` subtracts exactly what was added, on
8054/// the `Ok` path AND when an error unwinds the realize, so the backlog cannot leak.
8055///
8056/// Granularity, stated: work is counted from submit until the END OF THE REALIZE that submitted it, not
8057/// until its fence signals. A realize ends by draining every device it used, so at its end the work has
8058/// retired; within it the figure is an upper bound on what is still queued. What it is for: a second
8059/// realize (multi-agent serving) resolving a branch while this one's work is outstanding.
8060///
8061/// A CPU location and a zero estimate add nothing: the CPU has no queue to estimate, and a device the
8062/// executor cannot price must keep reporting NO estimate ([`backlog_estimate_ns`] `None`), never idle.
8063#[derive(Default)]
8064pub struct BacklogLedger {
8065    entries: Vec<LedgerEntry>,
8066}
8067
8068/// One fed estimate: where it was added, how much, and (when the backend can say) a non-blocking probe
8069/// that turns true once the work it stands for has completed.
8070struct LedgerEntry {
8071    loc: DeviceLocation,
8072    ns: u64,
8073    done: Option<Box<dyn Fn() -> bool + Send + Sync>>,
8074}
8075
8076impl std::fmt::Debug for BacklogLedger {
8077    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8078        f.debug_struct("BacklogLedger")
8079            .field("entries", &self.entries.len())
8080            .finish()
8081    }
8082}
8083
8084impl BacklogLedger {
8085    /// An empty ledger.
8086    pub fn new() -> Self {
8087        Self::default()
8088    }
8089
8090    /// Add `ns` of estimated work to `loc`'s backlog and keep it until the ledger is dropped (the end of
8091    /// the realize). For work with no completion probe.
8092    pub fn add(&mut self, loc: DeviceLocation, ns: u64) {
8093        self.push(loc, ns, None);
8094    }
8095
8096    /// Add `ns` of estimated work to `loc`'s backlog and take it back out as soon as `done()` reports the
8097    /// work finished (checked by [`Self::retire_completed`], without blocking), or when the ledger is
8098    /// dropped, whichever comes first. `done` must not block.
8099    pub fn add_until(
8100        &mut self,
8101        loc: DeviceLocation,
8102        ns: u64,
8103        done: impl Fn() -> bool + Send + Sync + 'static,
8104    ) {
8105        self.push(loc, ns, Some(Box::new(done)));
8106    }
8107
8108    fn push(
8109        &mut self,
8110        loc: DeviceLocation,
8111        ns: u64,
8112        done: Option<Box<dyn Fn() -> bool + Send + Sync>>,
8113    ) {
8114        if ns == 0 || matches!(loc, DeviceLocation::Cpu) {
8115            return;
8116        }
8117        backlog_add_ns(loc, ns);
8118        crate::optimizer_trace::global().record_backlog_added(ns);
8119        self.entries.push(LedgerEntry { loc, ns, done });
8120    }
8121
8122    /// Take back every entry whose probe reports its work finished. Never blocks. Called as the executor
8123    /// walks, so the backlog the picker reads is the work still QUEUED, not everything submitted so far.
8124    pub fn retire_completed(&mut self) {
8125        self.entries.retain(|e| {
8126            if e.done.as_ref().is_some_and(|d| d()) {
8127                backlog_sub_ns(e.loc, e.ns);
8128                crate::optimizer_trace::global().record_backlog_retired(e.ns);
8129                false
8130            } else {
8131                true
8132            }
8133        });
8134    }
8135
8136    /// What this ledger has added to `loc` and has outstanding (added minus retired).
8137    pub fn outstanding_ns(&self, loc: DeviceLocation) -> u64 {
8138        self.entries
8139            .iter()
8140            .filter(|e| e.loc == loc)
8141            .fold(0, |acc, e| acc.saturating_add(e.ns))
8142    }
8143}
8144
8145impl Drop for BacklogLedger {
8146    fn drop(&mut self) {
8147        for e in self.entries.drain(..) {
8148            backlog_sub_ns(e.loc, e.ns);
8149            crate::optimizer_trace::global().record_backlog_retired(e.ns);
8150        }
8151    }
8152}
8153
8154/// Process-wide [`KernelBindingTable`]. Initialized on first access
8155/// with the CPU dispatch wrappers from [`register_cpu_kernels`].
8156/// Other backends extend it when they register.
8157///
8158/// **Copy-on-write (GAP-015).** The lock guards an `Arc` *pointer*, not the
8159/// table. [`global_bindings`] clones the `Arc` and drops the read guard
8160/// before returning, so no read guard ever escapes the accessor and a
8161/// caller cannot hold one across a re-entrant region. That is what makes
8162/// the deadlock unrepresentable rather than merely unlikely: std's
8163/// `RwLock` blocks new readers once a writer queues (anti-writer-
8164/// starvation), so under the old `RwLock<KernelBindingTable>` a thread
8165/// holding a read guard that requested a *second* read waited on a lock
8166/// its own guard was blocking. Writers clone-mutate-swap.
8167static GLOBAL_BINDINGS: OnceLock<RwLock<Arc<KernelBindingTable>>> = OnceLock::new();
8168
8169/// Serializes *writers* to [`GLOBAL_BINDINGS`], and it is required for
8170/// correctness, not just tidiness.
8171///
8172/// A bare clone-mutate-swap would lose updates: two writers could clone the
8173/// same base concurrently and the second swap would silently discard the
8174/// first one's registrations. Worse, it would break
8175/// [`crate::runtime_fused_kernels::adopt_runtime_fused`], whose contract
8176/// requires its check-then-bind ("is this exact `KernelRef` already bound?"
8177/// then register) to be **atomic with respect to other writers** — two
8178/// threads racing to adopt the same region+kernel would both observe "not
8179/// bound" and both register, producing the duplicate-`KernelRef` that
8180/// `finalize` rejects.
8181///
8182/// This is deliberately a separate lock from the `RwLock` above so that the
8183/// caller-supplied extender and `finalize` run *outside* the `RwLock`; the
8184/// write guard is taken only for the pointer swap. Two consequences: a
8185/// panic in `finalize` can no longer poison the read path (the second
8186/// incident on this lock — see `runtime_fused_kernels.rs`), and an extender
8187/// that happens to call [`global_bindings`] reads a snapshot instead of
8188/// self-deadlocking. Poisoning is tolerated on both locks via
8189/// `unwrap_or_else(PoisonError::into_inner)`: a panicked writer leaves the
8190/// published table untouched, so the state a later caller observes is the
8191/// last good one, not a torn one.
8192static BINDINGS_WRITER: Mutex<()> = Mutex::new(());
8193
8194/// Initialize-once accessor for the binding-table cell. Both
8195/// [`global_bindings`] and [`extend_global_bindings`] route through this so
8196/// the init body exists exactly once.
8197fn bindings_cell() -> &'static RwLock<Arc<KernelBindingTable>> {
8198    GLOBAL_BINDINGS.get_or_init(|| {
8199        lock_trace("  BINDINGS init: begin");
8200        let mut t = KernelBindingTable::new();
8201        register_cpu_kernels(&mut t);
8202        lock_trace("  BINDINGS init: cpu done, entering optional backends");
8203        register_optional_backends(&mut t);
8204        lock_trace("  BINDINGS init: optional backends done");
8205        // Single init-boundary fail-fast: a duplicate `KernelRef` in the
8206        // hand-written static tables is a programmer error, surfaced once
8207        // here after all backends register — the never-panic replacement
8208        // for the former inline registration panic (the dynamic FKC
8209        // importer will call `finalize()?`).
8210        t.finalize()
8211            .expect("KernelBindingTable: duplicate kernel registration at init");
8212        RwLock::new(Arc::new(t))
8213    })
8214}
8215
8216fn default_cpu_caps() -> BackendCapabilities {
8217    use OpKind::*;
8218    use std::collections::HashSet;
8219    let mut op_dtype_support = HashSet::new();
8220    // The CPU coverage set must stay in lockstep with
8221    // `register_cpu_kernels`: each (op, dtype) pair registered there
8222    // is advertised here so capability-driven dispatch picks it.
8223    let f32_dt = DType::F32;
8224    for op in [
8225        AddElementwise,
8226        SubElementwise,
8227        MulElementwise,
8228        DivElementwise,
8229        ReluElementwise,
8230        NegElementwise,
8231        SqrElementwise,
8232        SqrtElementwise,
8233        RecipElementwise,
8234        AbsElementwise,
8235        TanhElementwise,
8236        ExpElementwise,
8237        LogElementwise,
8238        SinElementwise,
8239        CosElementwise,
8240        SigmoidElementwise,
8241        SiluElementwise,
8242        GeluElementwise,
8243        StepElementwise,
8244        SumReduce,
8245        MaxReduce,
8246        MinReduce,
8247        MeanReduce,
8248        MatMul,
8249        Conv2D,
8250        ConvTranspose2D,
8251        ReduceSumTo,
8252        ReduceMaxTo,
8253        FusedLinear,
8254        FlashAttn,
8255        PagedAttn,
8256        Affine,
8257        ClampElementwise,
8258        PowIElementwise,
8259        MaximumElementwise,
8260        MinimumElementwise,
8261        Concat,
8262        SoftmaxLastDim,
8263        RmsNormLastDim,
8264        LayerNormLastDim,
8265        IndexSelect,
8266        Gather,
8267        Rope,
8268        IndexAdd,
8269        ScatterAdd,
8270        QMatMul,
8271        Copy,
8272    ] {
8273        op_dtype_support.insert((op, f32_dt));
8274    }
8275    // f64 elementwise families. Reductions, matmul, conv, composed
8276    // ops, indexing, and view ops will join the f64 set as their
8277    // kernels migrate.
8278    for op in [
8279        AddElementwise,
8280        SubElementwise,
8281        MulElementwise,
8282        DivElementwise,
8283        ReluElementwise,
8284        NegElementwise,
8285        SqrElementwise,
8286        SqrtElementwise,
8287        RecipElementwise,
8288        AbsElementwise,
8289        TanhElementwise,
8290        ExpElementwise,
8291        LogElementwise,
8292        SinElementwise,
8293        CosElementwise,
8294        SigmoidElementwise,
8295        SiluElementwise,
8296        GeluElementwise,
8297        StepElementwise,
8298        MaximumElementwise,
8299        MinimumElementwise,
8300        SumReduce,
8301        MaxReduce,
8302        MinReduce,
8303        MeanReduce,
8304        MatMul,
8305        Conv2D,
8306        ConvTranspose2D,
8307        ReduceSumTo,
8308        ReduceMaxTo,
8309        FusedLinear,
8310        FlashAttn,
8311        PagedAttn,
8312    ] {
8313        op_dtype_support.insert((op, DType::F64));
8314    }
8315    // bf16 and f16 elementwise families. Reductions/matmul/conv/
8316    // composed/indexing/Rope/scalar follow as kernels migrate.
8317    let half_elementwise_ops = [
8318        AddElementwise,
8319        SubElementwise,
8320        MulElementwise,
8321        DivElementwise,
8322        MaximumElementwise,
8323        MinimumElementwise,
8324        ReluElementwise,
8325        NegElementwise,
8326        SqrElementwise,
8327        SqrtElementwise,
8328        RecipElementwise,
8329        AbsElementwise,
8330        TanhElementwise,
8331        ExpElementwise,
8332        LogElementwise,
8333        SinElementwise,
8334        CosElementwise,
8335        SigmoidElementwise,
8336        SiluElementwise,
8337        GeluElementwise,
8338        StepElementwise,
8339    ];
8340    for op in half_elementwise_ops {
8341        op_dtype_support.insert((op, DType::BF16));
8342        op_dtype_support.insert((op, DType::F16));
8343    }
8344    // bf16/f16 reductions + matmul (kernels accumulate in f32).
8345    for op in [SumReduce, MaxReduce, MinReduce, MeanReduce, MatMul] {
8346        op_dtype_support.insert((op, DType::BF16));
8347        op_dtype_support.insert((op, DType::F16));
8348    }
8349    // bf16/f16 composed/fused ops (Softmax, RmsNorm, LayerNorm,
8350    // Rope, Conv2D, ConvTranspose2D, ReduceSumTo, ReduceMaxTo,
8351    // FusedLinear, FlashAttn, PagedAttn) — all use the f32-accumulator
8352    // pattern.
8353    for op in [
8354        SoftmaxLastDim,
8355        RmsNormLastDim,
8356        LayerNormLastDim,
8357        Rope,
8358        Conv2D,
8359        ConvTranspose2D,
8360        ReduceSumTo,
8361        ReduceMaxTo,
8362        FusedLinear,
8363        FlashAttn,
8364        PagedAttn,
8365    ] {
8366        op_dtype_support.insert((op, DType::BF16));
8367        op_dtype_support.insert((op, DType::F16));
8368    }
8369    // Concat / IndexSelect / Gather are dtype-agnostic at the
8370    // byte level — advertised across the universal float/int set.
8371    for dt in [
8372        DType::F64,
8373        DType::BF16,
8374        DType::F16,
8375        DType::U32,
8376        DType::U8,
8377        DType::I16,
8378        DType::I32,
8379        DType::I64,
8380    ] {
8381        op_dtype_support.insert((Concat, dt));
8382        op_dtype_support.insert((IndexSelect, dt));
8383        op_dtype_support.insert((Gather, dt));
8384    }
8385    // IndexAdd / ScatterAdd / Affine / Clamp / PowI for f64/bf16/f16.
8386    for dt in [DType::F64, DType::BF16, DType::F16] {
8387        op_dtype_support.insert((IndexAdd, dt));
8388        op_dtype_support.insert((ScatterAdd, dt));
8389        op_dtype_support.insert((Affine, dt));
8390        op_dtype_support.insert((ClampElementwise, dt));
8391        op_dtype_support.insert((PowIElementwise, dt));
8392    }
8393    // F64 composed/fused ops (Softmax, RmsNorm, LayerNorm, Rope).
8394    for op in [SoftmaxLastDim, RmsNormLastDim, LayerNormLastDim, Rope] {
8395        op_dtype_support.insert((op, DType::F64));
8396    }
8397    // Argmax/argmin always produce U32 indices.
8398    for op in [ArgMaxDim, ArgMinDim] {
8399        op_dtype_support.insert((op, DType::U32));
8400    }
8401    // Cast advertises every target dtype that has a wrapper
8402    // registered. The capability matrix says "this backend can
8403    // produce an F64 output via Cast"; the source-side coverage
8404    // is managed inside each wrapper's match arms.
8405    for target in [DType::F32, DType::F64, DType::BF16, DType::F16] {
8406        op_dtype_support.insert((Cast, target));
8407    }
8408    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8409        crate::ranker::default_backend_rates(BackendId::Cpu);
8410    BackendCapabilities {
8411        backend_id: BackendId::Cpu,
8412        device_location: DeviceLocation::Cpu,
8413        op_dtype_support,
8414        required_alignment: 64,
8415        access_granularity_bits: 8,
8416        transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
8417        storage_substrate: SubstrateClass::HostBytes,
8418        compute_throughput_flops_per_ns,
8419        mem_bandwidth_bytes_per_ns,
8420    }
8421}
8422
8423/// Default storage substrate for a backend, matching the storage type
8424/// each backend actually produces. Mirrors `topology::default_substrate_for`
8425/// (kept in lockstep; that one is private to `topology.rs`).
8426fn substrate_for_backend(backend: BackendId) -> SubstrateClass {
8427    match backend {
8428        BackendId::Cpu => SubstrateClass::HostBytes,
8429        BackendId::Cuda => SubstrateClass::CudaUntyped,
8430        BackendId::Vulkan => SubstrateClass::VulkanBuffer,
8431        BackendId::Metal => SubstrateClass::MetalBuffer,
8432        // `BackendId` is `#[non_exhaustive]`; a downstream variant
8433        // defaults to host bytes until it declares its own substrate.
8434        _ => SubstrateClass::HostBytes,
8435    }
8436}
8437
8438/// FKC cost unification — Part A.
8439///
8440/// Derive a [`BackendCapabilities`] for `backend` (at `device_location`)
8441/// from the kernel binding `table`. This is the general (any-backend)
8442/// analogue of `default_cpu_caps`: instead of a hand-maintained list,
8443/// it reads the backend's REGISTERED KERNELS out of the binding table
8444/// and advertises exactly the `(OpKind, DType)` pairs those kernels
8445/// cover.
8446///
8447/// The `(op, dtype)` derivation mirrors
8448/// [`crate::topology::SystemTopology`]'s `binding_op_coverage`: each
8449/// binding key carries per-operand dtypes (inputs then outputs); the
8450/// classic `(op, dtype)` shape takes the OUTPUT dtype — the last entry
8451/// in the key's dtype list. Single-dtype keys (most elementwise ops)
8452/// are unambiguous; multi-dtype keys (e.g. QMatMul `[F32, U32, F32]`)
8453/// still produce the consumer-relevant output-dtype entry.
8454///
8455/// **Why this fixes the placement cost model.** The placement cost
8456/// composer (`ranker::cost::compute_static_costs`) skips any candidate
8457/// whose backend has no `BackendCapabilities` in the registry —
8458/// leaving its `static_cost` at the default ZERO, so an uncapped GPU
8459/// candidate prices as free and can spuriously out-rank a real CPU
8460/// cost. Registering the caps this function derives makes
8461/// `capabilities_for(gpu)` return `Some`, so the GPU candidate's
8462/// FLOP/byte cost fn actually runs (see also
8463/// [`KernelBindingTable::fill_unset_cost_for_backend`], which ensures
8464/// those kernels carry a non-`unknown_cost` cost fn).
8465///
8466/// Alignment / granularity use conservative device defaults (256-byte
8467/// alignment for GPU buffers — covers CUDA's 256B and Vulkan's typical
8468/// storage-buffer alignment; byte-addressable). Transfer paths
8469/// advertise the universal `HostStaging` link back to the CPU so the
8470/// `TransferMatrix` can price GPU↔CPU crossings; richer paths (P2P,
8471/// shared memory) are a future refinement the backend can declare
8472/// explicitly. Never panics.
8473pub fn derive_backend_caps(
8474    backend: BackendId,
8475    device_location: DeviceLocation,
8476    table: &KernelBindingTable,
8477) -> BackendCapabilities {
8478    use std::collections::HashSet;
8479    let mut op_dtype_support: HashSet<(OpKind, DType)> = HashSet::new();
8480    for (op, dtypes, this_backend) in table.iter_keys() {
8481        if this_backend != backend {
8482            continue;
8483        }
8484        if let Some(&output_dt) = dtypes.last() {
8485            op_dtype_support.insert((op, output_dt));
8486        }
8487    }
8488    // GPU substrate + a universal host-staging path back to CPU so the
8489    // transfer matrix can price GPU↔CPU. CPU keeps its SameDevice self
8490    // edge (this function is general, but CPU has its own hand-tuned
8491    // `default_cpu_caps`; the CPU branch here is just defensive).
8492    let transfer_paths = if device_location == DeviceLocation::Cpu {
8493        vec![(DeviceLocation::Cpu, TransferPath::SameDevice)]
8494    } else {
8495        vec![(DeviceLocation::Cpu, TransferPath::HostStaging)]
8496    };
8497    let (required_alignment, access_granularity_bits) = match backend {
8498        BackendId::Cpu => (64, 8),
8499        // GPU buffer allocations: 256-byte alignment is a safe
8500        // superset (CUDA cudaMalloc is 256B-aligned; Vulkan storage
8501        // buffers meet this). Byte-addressable.
8502        _ => (256, 8),
8503    };
8504    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8505        crate::ranker::default_backend_rates(backend);
8506    BackendCapabilities {
8507        backend_id: backend,
8508        device_location,
8509        op_dtype_support,
8510        required_alignment,
8511        access_granularity_bits,
8512        transfer_paths,
8513        storage_substrate: substrate_for_backend(backend),
8514        compute_throughput_flops_per_ns,
8515        mem_bandwidth_bytes_per_ns,
8516    }
8517}
8518
8519/// FKC cost unification — Part A.
8520///
8521/// Register the [`BackendCapabilities`] for every non-CPU backend that
8522/// has kernels in `table` into the process-wide [`CapabilityRegistry`],
8523/// deriving each backend's caps from its registered kernels via
8524/// [`derive_backend_caps`]. Called once, at the same init boundary that
8525/// populates the global binding table (see [`global_bindings`]), AFTER
8526/// the kernels are registered — so the derivation sees the full kernel
8527/// set.
8528///
8529/// This is the registration half of Part A: it closes the gap where
8530/// only the CPU auto-registered caps, leaving CUDA/Vulkan candidates
8531/// priced at zero in the placement DP. CPU is skipped here because it
8532/// already auto-registers its hand-tuned [`default_cpu_caps`] via
8533/// [`global_registry`].
8534///
8535/// Idempotency: the registry appends and lookups pick the first match,
8536/// so this should run exactly once per backend. The single init
8537/// boundary in [`global_bindings`] guarantees that.
8538fn register_derived_gpu_caps(table: &KernelBindingTable) {
8539    use std::collections::HashSet;
8540    // Which non-CPU backends have at least one kernel registered?
8541    let gpu_backends: HashSet<BackendId> = table
8542        .iter_keys()
8543        .map(|(_, _, backend)| backend)
8544        .filter(|b| *b != BackendId::Cpu)
8545        .collect();
8546    for backend in gpu_backends {
8547        register_derived_caps_for(backend, table);
8548    }
8549}
8550
8551/// Derive and register the `BackendCapabilities` for ONE backend from the kernels `table` holds for it
8552/// (the per-backend step of [`register_derived_gpu_caps`]). A backend whose kernels are added to the
8553/// global table later, through [`extend_global_bindings`], calls this once from inside its extender
8554/// (ROADMAP row 137 step 6.1: `fuel-vulkan-dispatch`), because the init boundary no longer sees it.
8555/// The capability registry appends and lookups pick the first match, so call it exactly once per backend.
8556pub fn register_derived_caps_for(backend: BackendId, table: &KernelBindingTable) {
8557    // The backend's default place (GPU ordinal 0, or the CPU); one definition in `fuel-ir`.
8558    let device_location = backend.default_location();
8559    register_backend_capabilities(derive_backend_caps(backend, device_location, table));
8560}
8561
8562/// Read-lock the process-wide capability registry. CPU is auto-
8563/// registered on first access; subsequent backends register
8564/// themselves via [`register_backend_capabilities`].
8565/// TEMPORARY GAP-015 DIAGNOSTIC — env-gated (`FUEL_LOCK_TRACE=1`), off by
8566/// default, zero behavior change. Names the thread and the acquisition it is
8567/// ABOUT to attempt versus the one it completed; a thread that logs "want" and
8568/// never logs "got" IS the blocked party, which is what the deadlock's stack we
8569/// cannot capture (no debugger on this box) would otherwise have told us.
8570/// Revert once the opposing lock order is pinned.
8571#[inline]
8572pub(crate) fn lock_trace(what: &str) {
8573    if std::env::var_os("FUEL_LOCK_TRACE").is_some() {
8574        eprintln!("[locktrace] t={:?} {}", std::thread::current().id(), what);
8575    }
8576}
8577
8578pub fn global_registry() -> std::sync::RwLockReadGuard<'static, CapabilityRegistry> {
8579    lock_trace("want REGISTRY.oncelock+read");
8580    let l = GLOBAL_REGISTRY.get_or_init(|| {
8581        lock_trace("  REGISTRY init: begin");
8582        let mut r = CapabilityRegistry::new();
8583        r.register(default_cpu_caps());
8584        lock_trace("  REGISTRY init: end");
8585        RwLock::new(r)
8586    });
8587    let g = l.read().unwrap();
8588    lock_trace("got  REGISTRY.read");
8589    g
8590}
8591
8592/// Add a backend's capabilities to the process-wide registry.
8593/// Typically called by each backend's init / probe path during
8594/// app startup. Idempotent for the same `(backend_id,
8595/// device_location)` is the *caller's* responsibility — the
8596/// registry happily appends duplicates and the lookup picks the
8597/// first-registered match.
8598pub fn register_backend_capabilities(caps: BackendCapabilities) {
8599    lock_trace("want REGISTRY.oncelock+WRITE (from register_backend_capabilities)");
8600    let lock = GLOBAL_REGISTRY.get_or_init(|| {
8601        lock_trace("  REGISTRY init: begin (via register_backend_capabilities)");
8602        let mut r = CapabilityRegistry::new();
8603        r.register(default_cpu_caps());
8604        lock_trace("  REGISTRY init: end");
8605        RwLock::new(r)
8606    });
8607    lock.write().unwrap().register(caps);
8608    lock_trace("got+released REGISTRY.WRITE");
8609    bump_topology_generation();
8610}
8611
8612/// Take a **snapshot** of the process-wide kernel-binding table. CPU
8613/// dispatch wrappers are auto-registered on first access. When built with
8614/// the `cuda` feature, the CUDA PTX path + the baracuda-kernels-sys path
8615/// are also auto-registered — production callers picking up the
8616/// global table see all available backends without manual init.
8617///
8618/// Returns an owned `Arc`, **not** a lock guard (GAP-015). The read guard
8619/// is acquired and released entirely inside this function, so a caller
8620/// cannot hold one across a call that might write the table — the shape
8621/// that deadlocked. Holding the returned `Arc` indefinitely is safe and
8622/// cheap; it keeps that snapshot alive, it does not block anyone.
8623///
8624/// **Snapshot semantics are a correctness property, not just a side
8625/// effect.** A caller sees one point-in-time table for as long as it holds
8626/// the `Arc`, so a kernel adopted concurrently is invisible to a pass
8627/// already in flight. That makes an optimize pass a pure function of
8628/// `(graph, table snapshot)`. Under the old guard, a pass could observe the
8629/// table mutate mid-pass and emit a plan not reproducible from its own
8630/// inputs — which would break the `base_map_hash` recipe-identity property
8631/// that Tier-2 convergence depends on. Adoption exists to affect
8632/// *subsequent* passes, so no known path wants mid-pass visibility.
8633pub fn global_bindings() -> Arc<KernelBindingTable> {
8634    lock_trace("want BINDINGS.oncelock+snapshot");
8635    let cell = bindings_cell();
8636    let snapshot = {
8637        // Poison-tolerant: nothing that can panic runs under this guard
8638        // (it wraps an `Arc::clone` and nothing else), so a poisoned flag
8639        // here can only have come from an unrelated writer that already
8640        // left the published table intact.
8641        let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8642        Arc::clone(&guard)
8643        // guard drops HERE, before returning — this is the whole fix.
8644    };
8645    lock_trace("got  BINDINGS snapshot (guard already released)");
8646    snapshot
8647}
8648
8649/// Auto-register every cargo-feature-gated backend that built. CPU is
8650/// always present (registered above); CUDA and Vulkan paths are
8651/// conditionally added. Future Metal / etc. paths hook in here.
8652fn register_optional_backends(table: &mut KernelBindingTable) {
8653    // CUDA is NOT registered here any more (ROADMAP row 137 step 6.2): the baracuda kernels live in
8654    // `fuel-cuda-dispatch`, above this crate, and reach the global table through `extend_global_bindings`
8655    // (`fuel_cuda_dispatch::install_global`, called by `fuel-tensor`), which also runs the CUDA cost fill
8656    // and the derived-capabilities step this function used to run.
8657    // Vulkan is NOT registered here any more (ROADMAP row 137 step 6.1): its kernels live in
8658    // `fuel-vulkan-dispatch`, above this crate, and reach the global table through
8659    // `extend_global_bindings` (`fuel_vulkan_dispatch::install_global`, called by `fuel-tensor`).
8660
8661    // FKC cost unification — Part A. Now that every compiled-in
8662    // backend's kernels are registered (and their cost fns filled),
8663    // derive + register the `BackendCapabilities` for every non-CPU
8664    // backend that has kernels, so the placement cost model's
8665    // `capabilities_for(gpu)` returns `Some` and the GPU candidate's
8666    // cost fn actually runs (instead of being skipped → priced at
8667    // zero). CPU already auto-registers its hand-tuned caps via
8668    // `global_registry`. Touches the separate `GLOBAL_REGISTRY` lock,
8669    // not this table's — no re-entrancy.
8670    register_derived_gpu_caps(table);
8671
8672    let _ = table;
8673}
8674
8675/// Add a backend's dispatch wrappers to the process-wide binding
8676/// table. Each backend exposes a `register_*_kernels(table)`
8677/// function (see [`register_cpu_kernels`]); per-backend init paths
8678/// call this to plug their wrappers into the global table.
8679///
8680/// Copy-on-write (GAP-015): clones the current table, runs `register` on
8681/// the clone, then swaps the published `Arc`. Writers are serialized by
8682/// `BINDINGS_WRITER` rather than by the `RwLock`, which is what keeps
8683/// `adopt_runtime_fused`'s check-then-bind atomic while still leaving
8684/// readers unblocked — see that static's docs for why both properties are
8685/// required. Readers in flight keep the pre-swap snapshot; they see this
8686/// registration on their next call.
8687pub fn extend_global_bindings(register: impl FnOnce(&mut KernelBindingTable)) {
8688    let cell = bindings_cell();
8689    {
8690        // Writer-side serialization. Held across clone → extend → finalize
8691        // → swap so two concurrent writers cannot lose each other's
8692        // updates, and so a check-then-bind extender observes a base no
8693        // other writer is mutating.
8694        lock_trace("want BINDINGS.WRITER (extend_global_bindings)");
8695        let _writer = BINDINGS_WRITER.lock().unwrap_or_else(|e| e.into_inner());
8696        lock_trace("got  BINDINGS.WRITER -- cloning table, extender runs OFF the RwLock");
8697
8698        let mut next = {
8699            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8700            (**guard).clone()
8701        };
8702        register(&mut next);
8703        lock_trace("  extender returned");
8704        // Re-validate after the extender adds its wrappers (same
8705        // never-panic fail-fast as the init boundary). This runs OUTSIDE
8706        // the `RwLock`, so the panic it can raise no longer poisons the
8707        // read path — and because `next` is thrown away on unwind, the
8708        // published table keeps its last good value instead of a torn one.
8709        next.finalize()
8710            .expect("KernelBindingTable: duplicate kernel registration after extend");
8711
8712        // Publish. The write guard covers a pointer swap and nothing else.
8713        {
8714            let mut guard = cell.write().unwrap_or_else(|e| e.into_inner());
8715            *guard = Arc::new(next);
8716        }
8717        lock_trace("released BINDINGS.WRITE (swap only)");
8718    }
8719    bump_topology_generation();
8720}
8721
8722/// The authored linear / quant-matmul FUSED kernel bundle, embedded into the
8723/// binary (the PRODUCTION `include_str!`). `register_cpu_linear_quant_fused_from_contract`
8724/// parses + lowers it and registers the MIGRATED subset FROM THE CONTRACT.
8725const FUSED_LINEAR_QUANT_CONTRACT: &str =
8726    include_str!("../kernel-contracts/fused/linear-quant.fkc.md");
8727
8728/// Register the linear / quant-matmul FUSED family — `FUSED_LINEAR` (4 dtypes,
8729/// key `[T, T, T, T]`) + `QMATMUL` (1 impl, key `[F32, U32, F32]`) +
8730/// `INPLACE_AFFINE` (4 dtypes, key `[T, T]`) + `FUSED_SOFTMAX_CROSS_ENTROPY`
8731/// (4 dtypes, key `[T, I64, F32]`) = **13 CPU `BackendImpl`s** — into the
8732/// [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true` FKC
8733/// contract (`fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md`), resolved
8734/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8735/// [`crate::fkc::CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`]). FKC is unconditional
8736/// core infrastructure, so this is the ONE registration path for these four
8737/// fused ops — every hand-written `register_fused!(FUSED_LINEAR / QMATMUL /
8738/// INPLACE_AFFINE / FUSED_SOFTMAX_CROSS_ENTROPY, …)` call is DELETED.
8739///
8740/// The bundle's fifth section `nf4_matmul` is `registrable: false` (its
8741/// `fdx.quant.family: AFFINE_BLOCK` is consumer-ahead, §6), so it never
8742/// lowers/registers and NF4's hand-written `FusedOps::NF4_MATMUL` regs (below,
8743/// unchanged) stay authoritative. QMATMUL's contract keys its weight operand the
8744/// LOGICAL dispatch dtype `U32` (the physical GGML block byte-honesty rides the
8745/// `fdx.quant: GGML_BLOCK` block), so the fanned key is `[F32, U32, F32]` —
8746/// byte-for-byte the deleted `QM_F32` reg. FSCE's `logits` fans over
8747/// `{F32,F64,BF16,F16}` (targets I64, output always F32), matching the four
8748/// deleted `FSCE_<dt>` regs exactly.
8749///
8750/// The bundle is fused-only, so `register_into`'s required binding-table
8751/// argument is a local throwaway that provably stays empty. Behavior-preserving
8752/// vs. the deleted hand-written path: identical per-dtype kernels (bound by
8753/// pointer through the link registry), the contract's bit-stable `audited: true`
8754/// precision (same shape as the deleted `*_CPU_PRECISION` consts — no downgrade),
8755/// and the real `compute_revision` hash (hand-written stamped `UNTRACKED`). Cost
8756/// stays the Judge-bootstrapped `fused_unknown_cost` sentinel ([consumer-ahead]:
8757/// the fused cost trampoline is a follow-up slice — the same posture the primitive
8758/// FKC imports take before `fill_unset_cpu_cost`).
8759fn register_cpu_linear_quant_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8760    let provider =
8761        crate::fkc::import_bundle_str(FUSED_LINEAR_QUANT_CONTRACT, &crate::fkc::CpuLinkRegistry)
8762            .expect(
8763                "authored linear-quant fused contract must import \
8764                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8765            );
8766    debug_assert!(
8767        provider.primitives.is_empty(),
8768        "linear-quant bundle declares only fused ops",
8769    );
8770    let mut table = KernelBindingTable::new();
8771    provider
8772        .register_into(&mut table, r)
8773        .expect("linear-quant fused contract must register into the fused registry");
8774}
8775
8776/// The authored norm / softmax FUSED kernel bundle, embedded into the binary
8777/// (the PRODUCTION `include_str!`). `register_cpu_norm_softmax_fused_from_contract`
8778/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8779const FUSED_NORM_SOFTMAX_CONTRACT: &str =
8780    include_str!("../kernel-contracts/fused/norm-softmax.fkc.md");
8781
8782/// Register the norm / softmax FUSED family — all EIGHT `fused_op` sections
8783/// (`SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`, key `[T, T]`;
8784/// `SOFTMAX_LAST_DIM_BACKWARD` / `LAYER_NORM_LAST_DIM_BACKWARD` /
8785/// `RMS_NORM_LAST_DIM_BACKWARD` / `REDUCE_MAX_TO_BACKWARD` / `POWI_BACKWARD`, key
8786/// `[T, T, T]`), each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU
8787/// `BackendImpl`s** — into the [`crate::fused::FusedKernelRegistry`] by IMPORTING
8788/// its `audited: true` FKC contract (`fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md`),
8789/// resolved through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8790/// [`crate::fkc::CPU_FUSED_NORM_ENTRY_POINTS`], the seam-proven 32-row table).
8791/// FKC is unconditional core infrastructure, so this is the ONE registration
8792/// path for these eight fused ops — every hand-written `register_fused!(SOFTMAX /
8793/// RMS_NORM / LAYER_NORM_LAST_DIM (+backward) / REDUCE_MAX_TO_BACKWARD /
8794/// POWI_BACKWARD, …)` call is DELETED.
8795///
8796/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8797/// kernels (bound by pointer through the link registry), the contract's
8798/// bit-stable `audited: true` precision — the **2026-07-03 maintainer flip
8799/// (CireSnave)** that relocates the `NORM_FAMILY_CPU_PRECISION` /
8800/// `REDUCE_MAX_TO_BACKWARD_CPU_PRECISION` / `POWI_BACKWARD_CPU_PRECISION`
8801/// bit-stable claim onto the contract (same author, same guarantee — no
8802/// downgrade), and the real `compute_revision` hash (hand-written stamped
8803/// `UNTRACKED`). Cost stays the Judge-bootstrapped `fused_unknown_cost` sentinel
8804/// (the fused cost trampoline is a follow-up slice).
8805fn register_cpu_norm_softmax_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8806    let provider =
8807        crate::fkc::import_bundle_str(FUSED_NORM_SOFTMAX_CONTRACT, &crate::fkc::CpuLinkRegistry)
8808            .expect(
8809                "authored norm-softmax fused contract must import \
8810                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8811            );
8812    debug_assert!(
8813        provider.primitives.is_empty(),
8814        "norm-softmax bundle declares only fused ops",
8815    );
8816    let mut table = KernelBindingTable::new();
8817    provider
8818        .register_into(&mut table, r)
8819        .expect("norm-softmax fused contract must register into the fused registry");
8820}
8821
8822/// The authored conv / RoPE / SSM FUSED kernel bundle, embedded into the binary
8823/// (the PRODUCTION `include_str!`). `register_cpu_conv_rope_fused_from_contract`
8824/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8825const FUSED_CONV_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/fused/conv-rope.fkc.md");
8826
8827/// Register the conv / RoPE / SSM FUSED family — all SIX `fused_op` sections,
8828/// each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU `BackendImpl`s** —
8829/// into the [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true`
8830/// FKC contract (`fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md`), resolved
8831/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8832/// [`crate::fkc::CPU_FUSED_CONV_ROPE_ENTRY_POINTS`], 24 rows). FKC is
8833/// unconditional core infrastructure, so this is the ONE registration path for
8834/// these six fused ops — every hand-written `register_fused!(ROPE / CONV2D /
8835/// CONV_TRANSPOSE2D / CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` call
8836/// is DELETED.
8837///
8838/// The 24 symbol rows fan into **32 impls** (ROPE 4 + CONV2D 8 +
8839/// CONV_TRANSPOSE2D 8 + CAUSAL_CONV1D 4 + SELECTIVE_SCAN 4 + SSD_CHUNK_SCAN 4):
8840/// - CONV2D / CONV_TRANSPOSE2D mark `bias` `optional: true`, so the importer's
8841///   key-builder fans EACH per-dtype section into BOTH the no-bias key `[T, T, T]`
8842///   and the with-bias key `[T, T, T, T]` — 4 rows → 8 impls each, byte-for-byte
8843///   the deleted `CV_*_NOB` + `CV_*_BIAS` regs. **CONV_TRANSPOSE2D's contract was
8844///   WIDENED to declare the optional `bias` operand** (it previously described
8845///   only the no-bias form): production registered both tuples and the CPU
8846///   transposed-conv scatter kernel seeds the output with `bias[co]` (or `0`), so
8847///   the widening is truthful and preserves the 8-impl count the
8848///   `default_kernel_registry_step6_coverage` gate asserts.
8849/// - SELECTIVE_SCAN / SSD_CHUNK_SCAN declare a `return.bundle` multi-output
8850///   (Option C, `[y ; last_state]`), so the key-builder appends the bundle's
8851///   primary-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the 5-input
8852///   tail — each keys `[T; 6]` byte-for-byte the deleted `SS_*` / `SCS_*` regs.
8853///
8854/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8855/// kernels (bound by pointer), the contract's bit-stable `audited: true`
8856/// precision — the **2026-07-03 maintainer flip (CireSnave)** relocating the
8857/// `ROPE_CPU_PRECISION` / `CONV2D_CPU_PRECISION` / `CONV_TRANSPOSE2D_CPU_PRECISION`
8858/// / `CAUSAL_CONV1D_CPU_PRECISION` / `SELECTIVE_SCAN_CPU_PRECISION` /
8859/// `SSD_CHUNK_SCAN_CPU_PRECISION` bit-stable claims onto the contract (same
8860/// author, same guarantee — no downgrade), and the real `compute_revision` hash
8861/// (hand-written stamped `UNTRACKED`). Cost stays the Judge-bootstrapped
8862/// `fused_unknown_cost` sentinel.
8863fn register_cpu_conv_rope_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8864    let provider =
8865        crate::fkc::import_bundle_str(FUSED_CONV_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
8866            .expect(
8867                "authored conv-rope fused contract must import \
8868                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8869            );
8870    debug_assert!(
8871        provider.primitives.is_empty(),
8872        "conv-rope bundle declares only fused ops",
8873    );
8874    let mut table = KernelBindingTable::new();
8875    provider
8876        .register_into(&mut table, r)
8877        .expect("conv-rope fused contract must register into the fused registry");
8878}
8879
8880/// Phase 7.6 step 6 — register the always-built fused-op kernels into
8881/// the [`crate::fused::FusedKernelRegistry`]. Called by
8882/// [`crate::fused::default_kernel_registry`]; kept here so the
8883/// crate-private CPU dispatch wrappers stay co-located with their
8884/// registration.
8885///
8886/// Today's coverage. Three `audited: true` FKC contracts are IMPORTED at the top
8887/// (contract-sourced, replacing the deleted hand-written `register_fused!`
8888/// entries); the attention family + deferred NF4 stay hand-written:
8889/// - **linear-quant** (`register_cpu_linear_quant_fused_from_contract`) — 13
8890///   impls: `FUSED_LINEAR` (4) + `QMATMUL` (1) + `INPLACE_AFFINE` (4) +
8891///   `FUSED_SOFTMAX_CROSS_ENTROPY` (4). The 5th section `NF4_MATMUL` is
8892///   `registrable: false` (AFFINE_BLOCK consumer-ahead) → stays hand-written.
8893/// - **norm-softmax** (`register_cpu_norm_softmax_fused_from_contract`) — 32
8894///   impls: `SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`
8895///   (+ their `_BACKWARD`) + `REDUCE_MAX_TO_BACKWARD` + `POWI_BACKWARD`
8896///   (8 sections × 4 dtypes).
8897/// - **conv-rope** (`register_cpu_conv_rope_fused_from_contract`) — 32 impls:
8898///   `ROPE` (4) + `CONV2D` (8, no-bias|with-bias) + `CONV_TRANSPOSE2D` (8,
8899///   no-bias|with-bias — bias operand WIDENED into the contract) +
8900///   `CAUSAL_CONV1D` (4) + `SELECTIVE_SCAN` (4, bundle) + `SSD_CHUNK_SCAN`
8901///   (4, bundle).
8902/// - hand-written below: `FLASH_ATTN` (8) + `FLASH_ATTN_BACKWARD_{Q,K,V}` (24) +
8903///   `PAGED_ATTN` (8) + `NF4_MATMUL` (3).
8904///
8905/// Total: 120 CPU BackendImpls registered across **all 24** registered
8906/// fused ops. The architecture v1.0 §05 bit-stable coverage
8907/// commitment is now compiler-enforced for the full fused-op set
8908/// (no `KNOWN_GAPS` allowlist in the step-7 lint).
8909///
8910/// Backend crates (fuel-cuda-backend, fuel-vulkan-backend) extend by
8911/// composing against the registry from their own startup paths or via
8912/// the step-9 binding-table refactor.
8913pub fn register_default_fused_kernels(r: &mut crate::fused::FusedKernelRegistry) {
8914    // NOTE: only the attention family (FLASH_ATTN / FLASH_ATTN_BACKWARD_{Q,K,V} /
8915    // PAGED_ATTN) + the deferred NF4_MATMUL keep hand-written cost fns + precision
8916    // consts here. The norm-softmax, linear-quant, and conv-rope bundles are
8917    // IMPORTED from their `audited: true` FKC contracts (below), so their cost fns
8918    // + `*_CPU_PRECISION` consts are no longer imported into this fn.
8919    use crate::fused::{
8920        ATTN_BACKWARD_CPU_PRECISION, ATTN_CPU_PRECISION, NF4_MATMUL_CPU_PRECISION,
8921        cost_attn_backward_cpu, cost_attn_cpu, cost_nf4_matmul_cpu,
8922    };
8923    use crate::register_fused;
8924    use fuel_graph::registry::FusedOps;
8925
8926    // Dtype tuples mirror the binding-table shape.
8927    // (FusedLinear's `(lhs, rhs, bias, out)` tuples are gone — FUSED_LINEAR is
8928    // now imported from the linear-quant FKC contract. Conv2D/ConvTranspose2D
8929    // `CV_*`, Softmax/RmsNorm/LayerNorm `UNARY_*`, `ROPE_*`, the norm/reduce/powi
8930    // backward `BW_*`, and the SSM `CC1D_*`/`SS_*`/`SCS_*` tuples are ALSO gone —
8931    // CONV2D/CONV_TRANSPOSE2D/ROPE + the norm-softmax bundle + CAUSAL_CONV1D/
8932    // SELECTIVE_SCAN/SSD_CHUNK_SCAN are now imported from the norm-softmax and
8933    // conv-rope FKC contracts, below.)
8934
8935    // FlashAttn: (q, k, v, [alibi], out) — no-alibi 4-tuple,
8936    // with-alibi 5-tuple. Same wrapper handles both.
8937    const FA_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32];
8938    const FA_F32_A: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8939    const FA_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64];
8940    const FA_F64_A: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8941    const FA_BF16_NOA: &[DType] = &[DType::BF16, DType::BF16, DType::BF16, DType::BF16];
8942    const FA_BF16_A: &[DType] = &[
8943        DType::BF16,
8944        DType::BF16,
8945        DType::BF16,
8946        DType::BF16,
8947        DType::BF16,
8948    ];
8949    const FA_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16];
8950    const FA_F16_A: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8951
8952    // FlashAttnBackward{Q,K,V}: (q, k, v, do, [alibi], out) —
8953    // no-alibi 5-tuple, with-alibi 6-tuple. Mirrors the binding-table
8954    // `fa_bw_no_alibi` / `fa_bw_with_alibi` key shapes.
8955    const FAB_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8956    const FAB_F32_A: &[DType] = &[
8957        DType::F32,
8958        DType::F32,
8959        DType::F32,
8960        DType::F32,
8961        DType::F32,
8962        DType::F32,
8963    ];
8964    const FAB_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8965    const FAB_F64_A: &[DType] = &[
8966        DType::F64,
8967        DType::F64,
8968        DType::F64,
8969        DType::F64,
8970        DType::F64,
8971        DType::F64,
8972    ];
8973    const FAB_BF16_NOA: &[DType] = &[
8974        DType::BF16,
8975        DType::BF16,
8976        DType::BF16,
8977        DType::BF16,
8978        DType::BF16,
8979    ];
8980    const FAB_BF16_A: &[DType] = &[
8981        DType::BF16,
8982        DType::BF16,
8983        DType::BF16,
8984        DType::BF16,
8985        DType::BF16,
8986        DType::BF16,
8987    ];
8988    const FAB_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8989    const FAB_F16_A: &[DType] = &[
8990        DType::F16,
8991        DType::F16,
8992        DType::F16,
8993        DType::F16,
8994        DType::F16,
8995        DType::F16,
8996    ];
8997
8998    // PagedAttn: (q, kc, vc, bt:U32, cl:U32, [alibi], out).
8999    const PA_F32_NOA: &[DType] = &[
9000        DType::F32,
9001        DType::F32,
9002        DType::F32,
9003        DType::U32,
9004        DType::U32,
9005        DType::F32,
9006    ];
9007    const PA_F32_A: &[DType] = &[
9008        DType::F32,
9009        DType::F32,
9010        DType::F32,
9011        DType::U32,
9012        DType::U32,
9013        DType::F32,
9014        DType::F32,
9015    ];
9016    const PA_F64_NOA: &[DType] = &[
9017        DType::F64,
9018        DType::F64,
9019        DType::F64,
9020        DType::U32,
9021        DType::U32,
9022        DType::F64,
9023    ];
9024    const PA_F64_A: &[DType] = &[
9025        DType::F64,
9026        DType::F64,
9027        DType::F64,
9028        DType::U32,
9029        DType::U32,
9030        DType::F64,
9031        DType::F64,
9032    ];
9033    const PA_BF16_NOA: &[DType] = &[
9034        DType::BF16,
9035        DType::BF16,
9036        DType::BF16,
9037        DType::U32,
9038        DType::U32,
9039        DType::BF16,
9040    ];
9041    const PA_BF16_A: &[DType] = &[
9042        DType::BF16,
9043        DType::BF16,
9044        DType::BF16,
9045        DType::U32,
9046        DType::U32,
9047        DType::BF16,
9048        DType::BF16,
9049    ];
9050    const PA_F16_NOA: &[DType] = &[
9051        DType::F16,
9052        DType::F16,
9053        DType::F16,
9054        DType::U32,
9055        DType::U32,
9056        DType::F16,
9057    ];
9058    const PA_F16_A: &[DType] = &[
9059        DType::F16,
9060        DType::F16,
9061        DType::F16,
9062        DType::U32,
9063        DType::U32,
9064        DType::F16,
9065        DType::F16,
9066    ];
9067
9068    // (QMatMul's `(a:F32, w_q:U32, out:F32)` tuple is gone — QMATMUL is now
9069    // imported from the linear-quant FKC contract. The `[T, T, T]` backward-helper
9070    // `BW_*` tuples are gone too — SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD +
9071    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD are now imported from the norm-softmax
9072    // FKC contract.)
9073
9074    let cpu = BackendId::Cpu;
9075
9076    // FUSED_LINEAR (4) + QMATMUL (1) + INPLACE_AFFINE (4) +
9077    // FUSED_SOFTMAX_CROSS_ENTROPY (4) = 13 CPU impls are IMPORTED from the
9078    // `audited: true` linear-quant FKC contract (resolved through the production
9079    // CpuLinkRegistry). This REPLACES the deleted hand-written register_fused!
9080    // entries for those four fused ops. The bundle's fifth section, nf4_matmul,
9081    // is `registrable: false` (AFFINE_BLOCK consumer-ahead, §6), so NF4's
9082    // hand-written FusedOps::NF4_MATMUL regs below stay authoritative.
9083    register_cpu_linear_quant_fused_from_contract(r);
9084
9085    // SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM (+ backward) +
9086    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD = 32 CPU impls are IMPORTED from the
9087    // `audited: true` norm-softmax FKC contract (8 sections × 4 dtypes), resolved
9088    // through the production CpuLinkRegistry (CPU_FUSED_NORM_ENTRY_POINTS). This
9089    // REPLACES the deleted hand-written register_fused! entries for those eight
9090    // fused ops.
9091    register_cpu_norm_softmax_fused_from_contract(r);
9092
9093    // ROPE + CONV2D + CONV_TRANSPOSE2D + CAUSAL_CONV1D + SELECTIVE_SCAN +
9094    // SSD_CHUNK_SCAN = 32 CPU impls are IMPORTED from the `audited: true`
9095    // conv-rope FKC contract (6 sections; CONV2D/CONV_TRANSPOSE2D fan the optional
9096    // bias into no-bias + with-bias keys → 8 impls each; SELECTIVE_SCAN/
9097    // SSD_CHUNK_SCAN key [T;6] via the return.bundle primary slot), resolved
9098    // through the production CpuLinkRegistry (CPU_FUSED_CONV_ROPE_ENTRY_POINTS).
9099    // This REPLACES the deleted hand-written register_fused! entries for those six
9100    // fused ops.
9101    register_cpu_conv_rope_fused_from_contract(r);
9102
9103    // NOTE (CapturedRun 4b-resume, 2026-07-13): a CUDA `FusedOps::ROPE`
9104    // candidate via baracuda's `rope_apply_<dt>_run` was registered here
9105    // (commit 3be28ab1) and then REVERTED — baracuda's `rope_apply` uses the
9106    // INTERLEAVED pairing `(2k, 2k+1)` (GPT-J) while Fuel's `FusedOps::ROPE`
9107    // (`Tensor::rope_with_tables`) is ROTATE-HALF `(j, j+head_dim/2)`
9108    // (Llama/HF). They compute DIFFERENT functions, so the interleaved kernel
9109    // must NOT be a candidate for the rotate-half op (a GPU numerical test
9110    // caught the divergence: `fuel_cuda_backend::baracuda::attention::
9111    // fused_rope_tests`). CUDA rope therefore runs via the correct rotate-half
9112    // primitive decompose until baracuda ships a rotate-half table-driven
9113    // `rope_apply` variant; the staged (unwired) driver + scratch cache live
9114    // in `fuel-cuda-backend` ready for that kernel.
9115
9116    // FlashAttn × 4 dtypes × {no-alibi, with-alibi}.
9117    register_fused!(
9118        r,
9119        FusedOps::FLASH_ATTN,
9120        cpu,
9121        FA_F32_NOA,
9122        flash_attn_f32_cpu_wrapper,
9123        cost = cost_attn_cpu,
9124        precision = ATTN_CPU_PRECISION
9125    );
9126    register_fused!(
9127        r,
9128        FusedOps::FLASH_ATTN,
9129        cpu,
9130        FA_F32_A,
9131        flash_attn_f32_cpu_wrapper,
9132        cost = cost_attn_cpu,
9133        precision = ATTN_CPU_PRECISION
9134    );
9135    register_fused!(
9136        r,
9137        FusedOps::FLASH_ATTN,
9138        cpu,
9139        FA_F64_NOA,
9140        flash_attn_f64_cpu_wrapper,
9141        cost = cost_attn_cpu,
9142        precision = ATTN_CPU_PRECISION
9143    );
9144    register_fused!(
9145        r,
9146        FusedOps::FLASH_ATTN,
9147        cpu,
9148        FA_F64_A,
9149        flash_attn_f64_cpu_wrapper,
9150        cost = cost_attn_cpu,
9151        precision = ATTN_CPU_PRECISION
9152    );
9153    register_fused!(
9154        r,
9155        FusedOps::FLASH_ATTN,
9156        cpu,
9157        FA_BF16_NOA,
9158        flash_attn_bf16_cpu_wrapper,
9159        cost = cost_attn_cpu,
9160        precision = ATTN_CPU_PRECISION
9161    );
9162    register_fused!(
9163        r,
9164        FusedOps::FLASH_ATTN,
9165        cpu,
9166        FA_BF16_A,
9167        flash_attn_bf16_cpu_wrapper,
9168        cost = cost_attn_cpu,
9169        precision = ATTN_CPU_PRECISION
9170    );
9171    register_fused!(
9172        r,
9173        FusedOps::FLASH_ATTN,
9174        cpu,
9175        FA_F16_NOA,
9176        flash_attn_f16_cpu_wrapper,
9177        cost = cost_attn_cpu,
9178        precision = ATTN_CPU_PRECISION
9179    );
9180    register_fused!(
9181        r,
9182        FusedOps::FLASH_ATTN,
9183        cpu,
9184        FA_F16_A,
9185        flash_attn_f16_cpu_wrapper,
9186        cost = cost_attn_cpu,
9187        precision = ATTN_CPU_PRECISION
9188    );
9189
9190    // FlashAttnBackward{Q,K,V} × 4 dtypes × {no-alibi, with-alibi}.
9191    // Reuses the binding-table dispatch wrappers — the CPU kernel
9192    // computes all three gradients each call and the wrapper persists
9193    // the one matching the OpKind; the cost model accounts for that.
9194    register_fused!(
9195        r,
9196        FusedOps::FLASH_ATTN_BACKWARD_Q,
9197        cpu,
9198        FAB_F32_NOA,
9199        flash_attn_backward_q_f32_cpu_wrapper,
9200        cost = cost_attn_backward_cpu,
9201        precision = ATTN_BACKWARD_CPU_PRECISION
9202    );
9203    register_fused!(
9204        r,
9205        FusedOps::FLASH_ATTN_BACKWARD_Q,
9206        cpu,
9207        FAB_F32_A,
9208        flash_attn_backward_q_f32_cpu_wrapper,
9209        cost = cost_attn_backward_cpu,
9210        precision = ATTN_BACKWARD_CPU_PRECISION
9211    );
9212    register_fused!(
9213        r,
9214        FusedOps::FLASH_ATTN_BACKWARD_Q,
9215        cpu,
9216        FAB_F64_NOA,
9217        flash_attn_backward_q_f64_cpu_wrapper,
9218        cost = cost_attn_backward_cpu,
9219        precision = ATTN_BACKWARD_CPU_PRECISION
9220    );
9221    register_fused!(
9222        r,
9223        FusedOps::FLASH_ATTN_BACKWARD_Q,
9224        cpu,
9225        FAB_F64_A,
9226        flash_attn_backward_q_f64_cpu_wrapper,
9227        cost = cost_attn_backward_cpu,
9228        precision = ATTN_BACKWARD_CPU_PRECISION
9229    );
9230    register_fused!(
9231        r,
9232        FusedOps::FLASH_ATTN_BACKWARD_Q,
9233        cpu,
9234        FAB_BF16_NOA,
9235        flash_attn_backward_q_bf16_cpu_wrapper,
9236        cost = cost_attn_backward_cpu,
9237        precision = ATTN_BACKWARD_CPU_PRECISION
9238    );
9239    register_fused!(
9240        r,
9241        FusedOps::FLASH_ATTN_BACKWARD_Q,
9242        cpu,
9243        FAB_BF16_A,
9244        flash_attn_backward_q_bf16_cpu_wrapper,
9245        cost = cost_attn_backward_cpu,
9246        precision = ATTN_BACKWARD_CPU_PRECISION
9247    );
9248    register_fused!(
9249        r,
9250        FusedOps::FLASH_ATTN_BACKWARD_Q,
9251        cpu,
9252        FAB_F16_NOA,
9253        flash_attn_backward_q_f16_cpu_wrapper,
9254        cost = cost_attn_backward_cpu,
9255        precision = ATTN_BACKWARD_CPU_PRECISION
9256    );
9257    register_fused!(
9258        r,
9259        FusedOps::FLASH_ATTN_BACKWARD_Q,
9260        cpu,
9261        FAB_F16_A,
9262        flash_attn_backward_q_f16_cpu_wrapper,
9263        cost = cost_attn_backward_cpu,
9264        precision = ATTN_BACKWARD_CPU_PRECISION
9265    );
9266
9267    register_fused!(
9268        r,
9269        FusedOps::FLASH_ATTN_BACKWARD_K,
9270        cpu,
9271        FAB_F32_NOA,
9272        flash_attn_backward_k_f32_cpu_wrapper,
9273        cost = cost_attn_backward_cpu,
9274        precision = ATTN_BACKWARD_CPU_PRECISION
9275    );
9276    register_fused!(
9277        r,
9278        FusedOps::FLASH_ATTN_BACKWARD_K,
9279        cpu,
9280        FAB_F32_A,
9281        flash_attn_backward_k_f32_cpu_wrapper,
9282        cost = cost_attn_backward_cpu,
9283        precision = ATTN_BACKWARD_CPU_PRECISION
9284    );
9285    register_fused!(
9286        r,
9287        FusedOps::FLASH_ATTN_BACKWARD_K,
9288        cpu,
9289        FAB_F64_NOA,
9290        flash_attn_backward_k_f64_cpu_wrapper,
9291        cost = cost_attn_backward_cpu,
9292        precision = ATTN_BACKWARD_CPU_PRECISION
9293    );
9294    register_fused!(
9295        r,
9296        FusedOps::FLASH_ATTN_BACKWARD_K,
9297        cpu,
9298        FAB_F64_A,
9299        flash_attn_backward_k_f64_cpu_wrapper,
9300        cost = cost_attn_backward_cpu,
9301        precision = ATTN_BACKWARD_CPU_PRECISION
9302    );
9303    register_fused!(
9304        r,
9305        FusedOps::FLASH_ATTN_BACKWARD_K,
9306        cpu,
9307        FAB_BF16_NOA,
9308        flash_attn_backward_k_bf16_cpu_wrapper,
9309        cost = cost_attn_backward_cpu,
9310        precision = ATTN_BACKWARD_CPU_PRECISION
9311    );
9312    register_fused!(
9313        r,
9314        FusedOps::FLASH_ATTN_BACKWARD_K,
9315        cpu,
9316        FAB_BF16_A,
9317        flash_attn_backward_k_bf16_cpu_wrapper,
9318        cost = cost_attn_backward_cpu,
9319        precision = ATTN_BACKWARD_CPU_PRECISION
9320    );
9321    register_fused!(
9322        r,
9323        FusedOps::FLASH_ATTN_BACKWARD_K,
9324        cpu,
9325        FAB_F16_NOA,
9326        flash_attn_backward_k_f16_cpu_wrapper,
9327        cost = cost_attn_backward_cpu,
9328        precision = ATTN_BACKWARD_CPU_PRECISION
9329    );
9330    register_fused!(
9331        r,
9332        FusedOps::FLASH_ATTN_BACKWARD_K,
9333        cpu,
9334        FAB_F16_A,
9335        flash_attn_backward_k_f16_cpu_wrapper,
9336        cost = cost_attn_backward_cpu,
9337        precision = ATTN_BACKWARD_CPU_PRECISION
9338    );
9339
9340    register_fused!(
9341        r,
9342        FusedOps::FLASH_ATTN_BACKWARD_V,
9343        cpu,
9344        FAB_F32_NOA,
9345        flash_attn_backward_v_f32_cpu_wrapper,
9346        cost = cost_attn_backward_cpu,
9347        precision = ATTN_BACKWARD_CPU_PRECISION
9348    );
9349    register_fused!(
9350        r,
9351        FusedOps::FLASH_ATTN_BACKWARD_V,
9352        cpu,
9353        FAB_F32_A,
9354        flash_attn_backward_v_f32_cpu_wrapper,
9355        cost = cost_attn_backward_cpu,
9356        precision = ATTN_BACKWARD_CPU_PRECISION
9357    );
9358    register_fused!(
9359        r,
9360        FusedOps::FLASH_ATTN_BACKWARD_V,
9361        cpu,
9362        FAB_F64_NOA,
9363        flash_attn_backward_v_f64_cpu_wrapper,
9364        cost = cost_attn_backward_cpu,
9365        precision = ATTN_BACKWARD_CPU_PRECISION
9366    );
9367    register_fused!(
9368        r,
9369        FusedOps::FLASH_ATTN_BACKWARD_V,
9370        cpu,
9371        FAB_F64_A,
9372        flash_attn_backward_v_f64_cpu_wrapper,
9373        cost = cost_attn_backward_cpu,
9374        precision = ATTN_BACKWARD_CPU_PRECISION
9375    );
9376    register_fused!(
9377        r,
9378        FusedOps::FLASH_ATTN_BACKWARD_V,
9379        cpu,
9380        FAB_BF16_NOA,
9381        flash_attn_backward_v_bf16_cpu_wrapper,
9382        cost = cost_attn_backward_cpu,
9383        precision = ATTN_BACKWARD_CPU_PRECISION
9384    );
9385    register_fused!(
9386        r,
9387        FusedOps::FLASH_ATTN_BACKWARD_V,
9388        cpu,
9389        FAB_BF16_A,
9390        flash_attn_backward_v_bf16_cpu_wrapper,
9391        cost = cost_attn_backward_cpu,
9392        precision = ATTN_BACKWARD_CPU_PRECISION
9393    );
9394    register_fused!(
9395        r,
9396        FusedOps::FLASH_ATTN_BACKWARD_V,
9397        cpu,
9398        FAB_F16_NOA,
9399        flash_attn_backward_v_f16_cpu_wrapper,
9400        cost = cost_attn_backward_cpu,
9401        precision = ATTN_BACKWARD_CPU_PRECISION
9402    );
9403    register_fused!(
9404        r,
9405        FusedOps::FLASH_ATTN_BACKWARD_V,
9406        cpu,
9407        FAB_F16_A,
9408        flash_attn_backward_v_f16_cpu_wrapper,
9409        cost = cost_attn_backward_cpu,
9410        precision = ATTN_BACKWARD_CPU_PRECISION
9411    );
9412
9413    // PagedAttn × 4 dtypes × {no-alibi, with-alibi}.
9414    register_fused!(
9415        r,
9416        FusedOps::PAGED_ATTN,
9417        cpu,
9418        PA_F32_NOA,
9419        paged_attn_f32_cpu_wrapper,
9420        cost = cost_attn_cpu,
9421        precision = ATTN_CPU_PRECISION
9422    );
9423    register_fused!(
9424        r,
9425        FusedOps::PAGED_ATTN,
9426        cpu,
9427        PA_F32_A,
9428        paged_attn_f32_cpu_wrapper,
9429        cost = cost_attn_cpu,
9430        precision = ATTN_CPU_PRECISION
9431    );
9432    register_fused!(
9433        r,
9434        FusedOps::PAGED_ATTN,
9435        cpu,
9436        PA_F64_NOA,
9437        paged_attn_f64_cpu_wrapper,
9438        cost = cost_attn_cpu,
9439        precision = ATTN_CPU_PRECISION
9440    );
9441    register_fused!(
9442        r,
9443        FusedOps::PAGED_ATTN,
9444        cpu,
9445        PA_F64_A,
9446        paged_attn_f64_cpu_wrapper,
9447        cost = cost_attn_cpu,
9448        precision = ATTN_CPU_PRECISION
9449    );
9450    register_fused!(
9451        r,
9452        FusedOps::PAGED_ATTN,
9453        cpu,
9454        PA_BF16_NOA,
9455        paged_attn_bf16_cpu_wrapper,
9456        cost = cost_attn_cpu,
9457        precision = ATTN_CPU_PRECISION
9458    );
9459    register_fused!(
9460        r,
9461        FusedOps::PAGED_ATTN,
9462        cpu,
9463        PA_BF16_A,
9464        paged_attn_bf16_cpu_wrapper,
9465        cost = cost_attn_cpu,
9466        precision = ATTN_CPU_PRECISION
9467    );
9468    register_fused!(
9469        r,
9470        FusedOps::PAGED_ATTN,
9471        cpu,
9472        PA_F16_NOA,
9473        paged_attn_f16_cpu_wrapper,
9474        cost = cost_attn_cpu,
9475        precision = ATTN_CPU_PRECISION
9476    );
9477    register_fused!(
9478        r,
9479        FusedOps::PAGED_ATTN,
9480        cpu,
9481        PA_F16_A,
9482        paged_attn_f16_cpu_wrapper,
9483        cost = cost_attn_cpu,
9484        precision = ATTN_CPU_PRECISION
9485    );
9486
9487    // (QMATMUL × F32 activations × U32 weights — 1 impl — is now IMPORTED from
9488    // the linear-quant FKC contract, above. The `[T, T, T]` backward helpers
9489    // SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD + REDUCE_MAX_TO_BACKWARD +
9490    // POWI_BACKWARD are IMPORTED from the norm-softmax FKC contract, and
9491    // CAUSAL_CONV1D + SELECTIVE_SCAN + SSD_CHUNK_SCAN (with INPLACE_AFFINE +
9492    // FUSED_SOFTMAX_CROSS_ENTROPY) are IMPORTED from the conv-rope / linear-quant
9493    // FKC contracts — all above.)
9494
9495    // NF4_MATMUL — four-tuple (activations T, w_packed U8, absmax
9496    // F32, out T), 3 dtype variants (T ∈ {F32, F16, BF16}).
9497    const NF4_F32: &[DType] = &[DType::F32, DType::U8, DType::F32, DType::F32];
9498    const NF4_F16: &[DType] = &[DType::F16, DType::U8, DType::F32, DType::F16];
9499    const NF4_BF16: &[DType] = &[DType::BF16, DType::U8, DType::F32, DType::BF16];
9500    register_fused!(
9501        r,
9502        FusedOps::NF4_MATMUL,
9503        cpu,
9504        NF4_F32,
9505        nf4_matmul_f32_cpu_wrapper,
9506        cost = cost_nf4_matmul_cpu,
9507        precision = NF4_MATMUL_CPU_PRECISION
9508    );
9509    register_fused!(
9510        r,
9511        FusedOps::NF4_MATMUL,
9512        cpu,
9513        NF4_F16,
9514        nf4_matmul_f16_cpu_wrapper,
9515        cost = cost_nf4_matmul_cpu,
9516        precision = NF4_MATMUL_CPU_PRECISION
9517    );
9518    register_fused!(
9519        r,
9520        FusedOps::NF4_MATMUL,
9521        cpu,
9522        NF4_BF16,
9523        nf4_matmul_bf16_cpu_wrapper,
9524        cost = cost_nf4_matmul_cpu,
9525        precision = NF4_MATMUL_CPU_PRECISION
9526    );
9527}
9528
9529#[cfg(test)]
9530mod tests {
9531    use super::*;
9532
9533    /// BORN-RED → GREEN: the `audited: true` linear-quant FUSED bundle is
9534    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9535    ///
9536    /// `register_default_fused_kernels` now imports
9537    /// `fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md` through the production
9538    /// `CpuLinkRegistry` (chaining `CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`) INSTEAD
9539    /// of the hand-written `register_fused!(FUSED_LINEAR / QMATMUL / INPLACE_AFFINE
9540    /// / FUSED_SOFTMAX_CROSS_ENTROPY, …)` entries (deleted). Each migrated
9541    /// `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype production
9542    /// wrapper (pointer identity) AND carries the contract's REAL revision hash.
9543    ///
9544    /// **Discriminator = `revision != UNTRACKED`.** Both the deleted hand-written
9545    /// regs and the imported impls bind the SAME wrapper fn-pointer, so pointer
9546    /// identity holds in BOTH states — it is not the red discriminator. The
9547    /// hand-written `register_fused!` path stamps `KernelRevisionHash::UNTRACKED`
9548    /// (the macro default); only the FKC import path stamps the contract's real
9549    /// `compute_revision` hash. RED (before the import wired + hand-written still
9550    /// present): `lookup_by_dtypes` returns the first-registered (hand-written)
9551    /// impl → `revision == UNTRACKED` → `assert_ne!` fails. GREEN (hand-written
9552    /// deleted, import wired): the imported impl is the sole source → real
9553    /// revision → passes.
9554    ///
9555    /// Guards: the unmigrated `FLASH_ATTN` still resolves its hand-written impl
9556    /// (UNTRACKED, unchanged); the DEFERRED `NF4_MATMUL` (contract section
9557    /// `registrable: false`, `AFFINE_BLOCK` consumer-ahead) also stays
9558    /// hand-written (UNTRACKED) — proving the migration is scoped to exactly the
9559    /// four registrable sections.
9560    #[test]
9561    fn linear_quant_fused_family_migrated_to_fkc_contract() {
9562        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9563        use fuel_graph::registry::FusedOps;
9564
9565        let mut r = FusedKernelRegistry::new();
9566        register_default_fused_kernels(&mut r);
9567
9568        // --- FUSED_LINEAR: 4 dtypes, key [T, T, T, T] ---
9569        for (dt, expected) in [
9570            (
9571                DType::F32,
9572                fused_linear_f32_cpu_wrapper as *const () as usize,
9573            ),
9574            (
9575                DType::F64,
9576                fused_linear_f64_cpu_wrapper as *const () as usize,
9577            ),
9578            (
9579                DType::BF16,
9580                fused_linear_bf16_cpu_wrapper as *const () as usize,
9581            ),
9582            (
9583                DType::F16,
9584                fused_linear_f16_cpu_wrapper as *const () as usize,
9585            ),
9586        ] {
9587            let got = r
9588                .lookup_by_dtypes(FusedOps::FUSED_LINEAR, BackendId::Cpu, &[dt, dt, dt, dt])
9589                .unwrap_or_else(|| panic!("FUSED_LINEAR {dt:?} migrated impl present"));
9590            assert_eq!(
9591                got.kernel as usize, expected,
9592                "FUSED_LINEAR {dt:?} binds its exact per-dtype production wrapper",
9593            );
9594            assert_ne!(
9595                got.revision,
9596                KernelRevisionHash::UNTRACKED,
9597                "FKC-imported FUSED_LINEAR {dt:?} carries the contract's real revision \
9598                 (hand-written register_fused! stamps UNTRACKED)",
9599            );
9600        }
9601
9602        // --- QMATMUL: 1 impl, key [F32, U32, F32] (logical dispatch dtype U32) ---
9603        let qm = r
9604            .lookup_by_dtypes(
9605                FusedOps::QMATMUL,
9606                BackendId::Cpu,
9607                &[DType::F32, DType::U32, DType::F32],
9608            )
9609            .expect("QMATMUL migrated impl present at [F32, U32, F32]");
9610        assert_eq!(
9611            qm.kernel as usize,
9612            qmatmul_f32_cpu_wrapper as *const () as usize
9613        );
9614        assert_ne!(qm.revision, KernelRevisionHash::UNTRACKED);
9615
9616        // --- INPLACE_AFFINE: 4 dtypes, key [T, T] ---
9617        for (dt, expected) in [
9618            (
9619                DType::F32,
9620                inplace_affine_f32_cpu_wrapper as *const () as usize,
9621            ),
9622            (
9623                DType::F64,
9624                inplace_affine_f64_cpu_wrapper as *const () as usize,
9625            ),
9626            (
9627                DType::BF16,
9628                inplace_affine_bf16_cpu_wrapper as *const () as usize,
9629            ),
9630            (
9631                DType::F16,
9632                inplace_affine_f16_cpu_wrapper as *const () as usize,
9633            ),
9634        ] {
9635            let got = r
9636                .lookup_by_dtypes(FusedOps::INPLACE_AFFINE, BackendId::Cpu, &[dt, dt])
9637                .unwrap_or_else(|| panic!("INPLACE_AFFINE {dt:?} migrated impl present"));
9638            assert_eq!(got.kernel as usize, expected);
9639            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9640        }
9641
9642        // --- FUSED_SOFTMAX_CROSS_ENTROPY: 4 dtypes, key [T, I64, F32] ---
9643        for (dt, expected) in [
9644            (
9645                DType::F32,
9646                fused_softmax_cross_entropy_f32_cpu_wrapper as *const () as usize,
9647            ),
9648            (
9649                DType::F64,
9650                fused_softmax_cross_entropy_f64_cpu_wrapper as *const () as usize,
9651            ),
9652            (
9653                DType::BF16,
9654                fused_softmax_cross_entropy_bf16_cpu_wrapper as *const () as usize,
9655            ),
9656            (
9657                DType::F16,
9658                fused_softmax_cross_entropy_f16_cpu_wrapper as *const () as usize,
9659            ),
9660        ] {
9661            let got = r
9662                .lookup_by_dtypes(
9663                    FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
9664                    BackendId::Cpu,
9665                    &[dt, DType::I64, DType::F32],
9666                )
9667                .unwrap_or_else(|| panic!("FSCE {dt:?} migrated impl present"));
9668            assert_eq!(got.kernel as usize, expected);
9669            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9670        }
9671
9672        // --- GUARD: unmigrated FLASH_ATTN still resolves its hand-written impl ---
9673        let fa = r
9674            .lookup_by_dtypes(
9675                FusedOps::FLASH_ATTN,
9676                BackendId::Cpu,
9677                &[DType::F32, DType::F32, DType::F32, DType::F32],
9678            )
9679            .expect("FLASH_ATTN hand-written impl present");
9680        assert_eq!(
9681            fa.kernel as usize,
9682            flash_attn_f32_cpu_wrapper as *const () as usize
9683        );
9684        assert_eq!(
9685            fa.revision,
9686            KernelRevisionHash::UNTRACKED,
9687            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9688        );
9689
9690        // --- GUARD: DEFERRED NF4_MATMUL stays hand-written (registrable: false) ---
9691        let nf4 = r
9692            .lookup_by_dtypes(
9693                FusedOps::NF4_MATMUL,
9694                BackendId::Cpu,
9695                &[DType::F32, DType::U8, DType::F32, DType::F32],
9696            )
9697            .expect("NF4_MATMUL hand-written impl present (AFFINE_BLOCK deferred)");
9698        assert_eq!(
9699            nf4.kernel as usize,
9700            nf4_matmul_f32_cpu_wrapper as *const () as usize
9701        );
9702        assert_eq!(
9703            nf4.revision,
9704            KernelRevisionHash::UNTRACKED,
9705            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9706        );
9707    }
9708
9709    /// BORN-RED → GREEN: the `audited: true` norm/softmax FUSED bundle is
9710    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9711    ///
9712    /// `register_default_fused_kernels` now imports
9713    /// `fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md` through the production
9714    /// `CpuLinkRegistry` (chaining `CPU_FUSED_NORM_ENTRY_POINTS`) INSTEAD of the
9715    /// hand-written `register_fused!(SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM
9716    /// (+backward) / REDUCE_MAX_TO_BACKWARD / POWI_BACKWARD, …)` entries (deleted).
9717    /// Each migrated `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype
9718    /// production wrapper (pointer identity) AND carries the contract's REAL
9719    /// revision hash.
9720    ///
9721    /// **Discriminator = `revision != UNTRACKED`.** Both paths bind the SAME
9722    /// wrapper fn-pointer, so pointer identity holds in BOTH states — it is not
9723    /// the red discriminator. The hand-written `register_fused!` path stamps
9724    /// `KernelRevisionHash::UNTRACKED`; only the FKC import path stamps the
9725    /// contract's real `compute_revision`. RED (before wired + hand-written still
9726    /// present): `lookup_by_dtypes` returns the hand-written impl → `UNTRACKED` →
9727    /// `assert_ne!` fails. GREEN (deleted + imported): real revision → passes.
9728    ///
9729    /// Also asserts the **2026-07-03 maintainer flip rode through**: the imported
9730    /// precision is bit-stable (`bit_stable_on_same_hardware == true`), NOT the
9731    /// `UNAUDITED` an `audited: false` contract would have lowered to — the whole
9732    /// point of the flip.
9733    #[test]
9734    fn norm_softmax_fused_family_migrated_to_fkc_contract() {
9735        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9736        use fuel_graph::registry::FusedOps;
9737
9738        let mut r = FusedKernelRegistry::new();
9739        register_default_fused_kernels(&mut r);
9740
9741        // FORWARD (key [T, T]) — Softmax / RmsNorm / LayerNorm last-dim.
9742        let forward = [
9743            (
9744                FusedOps::SOFTMAX_LAST_DIM,
9745                [
9746                    softmax_last_dim_f32_cpu_wrapper as *const () as usize,
9747                    softmax_last_dim_f64_cpu_wrapper as *const () as usize,
9748                    softmax_last_dim_bf16_cpu_wrapper as *const () as usize,
9749                    softmax_last_dim_f16_cpu_wrapper as *const () as usize,
9750                ],
9751            ),
9752            (
9753                FusedOps::RMS_NORM_LAST_DIM,
9754                [
9755                    rms_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9756                    rms_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9757                    rms_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9758                    rms_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9759                ],
9760            ),
9761            (
9762                FusedOps::LAYER_NORM_LAST_DIM,
9763                [
9764                    layer_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9765                    layer_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9766                    layer_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9767                    layer_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9768                ],
9769            ),
9770        ];
9771        for (id, wrappers) in forward {
9772            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9773                .iter()
9774                .zip(wrappers)
9775            {
9776                let got = r
9777                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt])
9778                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9779                assert_eq!(
9780                    got.kernel as usize, expected,
9781                    "{id:?} {dt:?} binds its exact per-dtype production wrapper",
9782                );
9783                assert_ne!(
9784                    got.revision,
9785                    KernelRevisionHash::UNTRACKED,
9786                    "FKC-imported {id:?} {dt:?} carries the contract's real revision \
9787                     (hand-written register_fused! stamps UNTRACKED)",
9788                );
9789                assert!(
9790                    got.precision.bit_stable_on_same_hardware,
9791                    "the 2026-07-03 audited:true flip rode through as bit-stable for {id:?} {dt:?} \
9792                     (NOT the UNAUDITED an audited:false contract would have lowered to)",
9793                );
9794            }
9795        }
9796
9797        // BACKWARD (key [T, T, T]) — Softmax / Layer / Rms backward +
9798        // ReduceMaxTo / PowI backward (backward-of-primitive helpers).
9799        let backward = [
9800            (
9801                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
9802                [
9803                    softmax_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9804                    softmax_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9805                    softmax_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9806                    softmax_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9807                ],
9808            ),
9809            (
9810                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
9811                [
9812                    layer_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9813                    layer_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9814                    layer_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9815                    layer_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9816                ],
9817            ),
9818            (
9819                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
9820                [
9821                    rms_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9822                    rms_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9823                    rms_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9824                    rms_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9825                ],
9826            ),
9827            (
9828                FusedOps::REDUCE_MAX_TO_BACKWARD,
9829                [
9830                    reduce_max_to_backward_f32_cpu_wrapper as *const () as usize,
9831                    reduce_max_to_backward_f64_cpu_wrapper as *const () as usize,
9832                    reduce_max_to_backward_bf16_cpu_wrapper as *const () as usize,
9833                    reduce_max_to_backward_f16_cpu_wrapper as *const () as usize,
9834                ],
9835            ),
9836            (
9837                FusedOps::POWI_BACKWARD,
9838                [
9839                    powi_backward_f32_cpu_wrapper as *const () as usize,
9840                    powi_backward_f64_cpu_wrapper as *const () as usize,
9841                    powi_backward_bf16_cpu_wrapper as *const () as usize,
9842                    powi_backward_f16_cpu_wrapper as *const () as usize,
9843                ],
9844            ),
9845        ];
9846        for (id, wrappers) in backward {
9847            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9848                .iter()
9849                .zip(wrappers)
9850            {
9851                let got = r
9852                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt, *dt])
9853                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9854                assert_eq!(got.kernel as usize, expected);
9855                assert_ne!(
9856                    got.revision,
9857                    KernelRevisionHash::UNTRACKED,
9858                    "FKC-imported {id:?} {dt:?} carries the contract's real revision",
9859                );
9860                assert!(
9861                    got.precision.bit_stable_on_same_hardware,
9862                    "the audited:true flip rode through as bit-stable for {id:?} {dt:?}",
9863                );
9864            }
9865        }
9866
9867        // GUARD: an UNMIGRATED fused op (FLASH_ATTN) still resolves its
9868        // hand-written impl at UNTRACKED — proves the migration is scoped.
9869        let fa = r
9870            .lookup_by_dtypes(
9871                FusedOps::FLASH_ATTN,
9872                BackendId::Cpu,
9873                &[DType::F32, DType::F32, DType::F32, DType::F32],
9874            )
9875            .expect("FLASH_ATTN hand-written impl present");
9876        assert_eq!(
9877            fa.revision,
9878            KernelRevisionHash::UNTRACKED,
9879            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9880        );
9881    }
9882
9883    /// BORN-RED → GREEN: the `audited: true` conv / RoPE / SSM FUSED bundle is
9884    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9885    ///
9886    /// `register_default_fused_kernels` now imports
9887    /// `fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md` through the production
9888    /// `CpuLinkRegistry` (chaining `CPU_FUSED_CONV_ROPE_ENTRY_POINTS`) INSTEAD of
9889    /// the hand-written `register_fused!(ROPE / CONV2D / CONV_TRANSPOSE2D /
9890    /// CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` entries (deleted). Each
9891    /// migrated impl binds the EXACT per-dtype wrapper (pointer identity) AND
9892    /// carries the contract's REAL revision (hand-written stamps UNTRACKED — the
9893    /// red discriminator). Covers the two multi-key cases:
9894    /// - CONV2D / CONV_TRANSPOSE2D fan the optional bias into BOTH the no-bias
9895    ///   key `[T, T, T]` and the with-bias key `[T, T, T, T]` (8 impls each);
9896    /// - SELECTIVE_SCAN / SSD_CHUNK_SCAN key `[T; 6]` (5 inputs + the bundle's
9897    ///   primary output slot).
9898    ///
9899    /// Also asserts the **2026-07-03 maintainer flip rode through** as bit-stable
9900    /// (NOT `UNAUDITED`).
9901    #[test]
9902    fn conv_rope_fused_family_migrated_to_fkc_contract() {
9903        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9904        use fuel_graph::registry::FusedOps;
9905
9906        let mut r = FusedKernelRegistry::new();
9907        register_default_fused_kernels(&mut r);
9908
9909        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
9910
9911        // ROPE — key [T, T, T, T] (x, cos, sin + out).
9912        let rope_w = [
9913            rope_f32_cpu_wrapper as *const () as usize,
9914            rope_f64_cpu_wrapper as *const () as usize,
9915            rope_bf16_cpu_wrapper as *const () as usize,
9916            rope_f16_cpu_wrapper as *const () as usize,
9917        ];
9918        for (dt, expected) in dts.iter().zip(rope_w) {
9919            let got = r
9920                .lookup_by_dtypes(FusedOps::ROPE, BackendId::Cpu, &[*dt, *dt, *dt, *dt])
9921                .unwrap_or_else(|| panic!("ROPE {dt:?} migrated impl present"));
9922            assert_eq!(got.kernel as usize, expected);
9923            assert_ne!(
9924                got.revision,
9925                KernelRevisionHash::UNTRACKED,
9926                "ROPE {dt:?} real revision"
9927            );
9928            assert!(
9929                got.precision.bit_stable_on_same_hardware,
9930                "audited:true rode through bit-stable for ROPE {dt:?}",
9931            );
9932        }
9933
9934        // CONV2D / CONV_TRANSPOSE2D — optional bias ⇒ BOTH no-bias [T,T,T] and
9935        // with-bias [T,T,T,T] resolve the SAME per-dtype wrapper (8 impls each).
9936        let conv = [
9937            (
9938                FusedOps::CONV2D,
9939                [
9940                    conv2d_f32_cpu_wrapper as *const () as usize,
9941                    conv2d_f64_cpu_wrapper as *const () as usize,
9942                    conv2d_bf16_cpu_wrapper as *const () as usize,
9943                    conv2d_f16_cpu_wrapper as *const () as usize,
9944                ],
9945            ),
9946            (
9947                FusedOps::CONV_TRANSPOSE2D,
9948                [
9949                    conv_transpose2d_f32_cpu_wrapper as *const () as usize,
9950                    conv_transpose2d_f64_cpu_wrapper as *const () as usize,
9951                    conv_transpose2d_bf16_cpu_wrapper as *const () as usize,
9952                    conv_transpose2d_f16_cpu_wrapper as *const () as usize,
9953                ],
9954            ),
9955        ];
9956        for (id, wrappers) in conv {
9957            for (dt, expected) in dts.iter().zip(wrappers) {
9958                for key in [vec![*dt, *dt, *dt], vec![*dt, *dt, *dt, *dt]] {
9959                    let with_bias = key.len() == 4;
9960                    let got = r
9961                        .lookup_by_dtypes(id, BackendId::Cpu, &key)
9962                        .unwrap_or_else(|| {
9963                            panic!("{id:?} {dt:?} (with_bias={with_bias}) migrated impl present")
9964                        });
9965                    assert_eq!(got.kernel as usize, expected);
9966                    assert_ne!(
9967                        got.revision,
9968                        KernelRevisionHash::UNTRACKED,
9969                        "{id:?} {dt:?} (with_bias={with_bias}) real revision",
9970                    );
9971                    assert!(
9972                        got.precision.bit_stable_on_same_hardware,
9973                        "audited:true rode through bit-stable for {id:?} {dt:?} (with_bias={with_bias})",
9974                    );
9975                }
9976            }
9977        }
9978
9979        // CAUSAL_CONV1D — key [T, T, T, T] (x, weight, bias + out).
9980        let cc1d_w = [
9981            causal_conv1d_f32_cpu_wrapper as *const () as usize,
9982            causal_conv1d_f64_cpu_wrapper as *const () as usize,
9983            causal_conv1d_bf16_cpu_wrapper as *const () as usize,
9984            causal_conv1d_f16_cpu_wrapper as *const () as usize,
9985        ];
9986        for (dt, expected) in dts.iter().zip(cc1d_w) {
9987            let got = r
9988                .lookup_by_dtypes(
9989                    FusedOps::CAUSAL_CONV1D,
9990                    BackendId::Cpu,
9991                    &[*dt, *dt, *dt, *dt],
9992                )
9993                .unwrap_or_else(|| panic!("CAUSAL_CONV1D {dt:?} migrated impl present"));
9994            assert_eq!(got.kernel as usize, expected);
9995            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9996            assert!(got.precision.bit_stable_on_same_hardware);
9997        }
9998
9999        // SELECTIVE_SCAN / SSD_CHUNK_SCAN — return.bundle ⇒ key [T; 6]
10000        // (5 inputs + the bundled primary output slot).
10001        let scan = [
10002            (
10003                FusedOps::SELECTIVE_SCAN,
10004                [
10005                    selective_scan_f32_cpu_wrapper as *const () as usize,
10006                    selective_scan_f64_cpu_wrapper as *const () as usize,
10007                    selective_scan_bf16_cpu_wrapper as *const () as usize,
10008                    selective_scan_f16_cpu_wrapper as *const () as usize,
10009                ],
10010            ),
10011            (
10012                FusedOps::SSD_CHUNK_SCAN,
10013                [
10014                    ssd_chunk_scan_f32_cpu_wrapper as *const () as usize,
10015                    ssd_chunk_scan_f64_cpu_wrapper as *const () as usize,
10016                    ssd_chunk_scan_bf16_cpu_wrapper as *const () as usize,
10017                    ssd_chunk_scan_f16_cpu_wrapper as *const () as usize,
10018                ],
10019            ),
10020        ];
10021        for (id, wrappers) in scan {
10022            for (dt, expected) in dts.iter().zip(wrappers) {
10023                let got = r
10024                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt; 6])
10025                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
10026                assert_eq!(got.kernel as usize, expected);
10027                assert_ne!(
10028                    got.revision,
10029                    KernelRevisionHash::UNTRACKED,
10030                    "{id:?} {dt:?} real revision",
10031                );
10032                assert!(
10033                    got.precision.bit_stable_on_same_hardware,
10034                    "audited:true rode through bit-stable for {id:?} {dt:?}",
10035                );
10036            }
10037        }
10038
10039        // GUARD: the DEFERRED NF4_MATMUL (linear-quant `registrable: false`) stays
10040        // hand-written at UNTRACKED — proves this migration is scoped to conv-rope.
10041        let nf4 = r
10042            .lookup_by_dtypes(
10043                FusedOps::NF4_MATMUL,
10044                BackendId::Cpu,
10045                &[DType::F32, DType::U8, DType::F32, DType::F32],
10046            )
10047            .expect("NF4_MATMUL hand-written impl present");
10048        assert_eq!(
10049            nf4.revision,
10050            KernelRevisionHash::UNTRACKED,
10051            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
10052        );
10053    }
10054
10055    /// Phase 7.6 step 7b — the architecture v1.0 §05 "always-built
10056    /// backend bit-stable coverage commitment" lint, extended from
10057    /// the fused-op half (step 7a) to **primitive** ops.
10058    ///
10059    /// Every `OpKind` variant that flows through `KernelBindingTable`
10060    /// MUST have at least one CPU registration with
10061    /// `precision.bit_stable_on_same_hardware == true`. The
10062    /// architecture's correctness anchor is the always-built backend
10063    /// giving every downstream consumer a deterministic
10064    /// implementation to fall back on, so cross-backend equivalence
10065    /// tests have a fixed reference.
10066    ///
10067    /// The lint runs as a unit test so violations surface in CI
10068    /// rather than at runtime. Adding a new `OpKind` variant without
10069    /// a matching CPU registration fails this test immediately.
10070    ///
10071    /// As of step 7b (2026-05-11), every `OpKind` variant has CPU
10072    /// coverage via `register_cpu_kernels` + the
10073    /// `fill_unset_cpu_precision` pass at the end of that function.
10074    /// `KNOWN_GAPS` is empty.
10075    ///
10076    /// Note on the OpKind enumeration: there's no `strum`-style
10077    /// derive on the enum, so the test hardcodes the variant list.
10078    /// New OpKind variants must be added here AND to a matching
10079    /// CPU registration in `register_cpu_kernels`. The two-touch
10080    /// requirement is a feature — the test becomes the canonical
10081    /// "all kernels accounted for" reference.
10082    #[test]
10083    /// FKC-CLAUSE: FKC-4.8-0001 — the always-built coverage commitment. This is a
10084    /// CORPUS property (>=1 bit-stable CPU kernel per primitive op), not a
10085    /// per-contract rule, so it raises no FkcError and is invisible to the
10086    /// variant-anchored gate in tests/fkc_clause_coverage.rs.
10087    fn precision_guarantee_lint_bit_stable_cpu_coverage_primitives() {
10088        use fuel_ir::dispatch::OpKind;
10089        use fuel_ir::probe::BackendId;
10090
10091        // Allowlist for OpKind variants that *can't* have bit-stable
10092        // CPU coverage. Empty as of step 7b (every variant routes
10093        // through deterministic kernels). New entries must come with
10094        // a documented reason — and a follow-up to close the gap.
10095        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
10096
10097        // The canonical list of every OpKind variant. Mirrors the
10098        // enum definition in fuel-core-types::dispatch. Adding a
10099        // new variant requires adding it here; that's the explicit
10100        // contract for "this OpKind exists and is expected to have
10101        // CPU coverage."
10102        const ALL_OP_KINDS: &[OpKind] = &[
10103            OpKind::MatMul,
10104            OpKind::AddElementwise,
10105            OpKind::SubElementwise,
10106            OpKind::MulElementwise,
10107            OpKind::DivElementwise,
10108            OpKind::ReluElementwise,
10109            OpKind::NegElementwise,
10110            OpKind::SqrElementwise,
10111            OpKind::SqrtElementwise,
10112            OpKind::RecipElementwise,
10113            OpKind::AbsElementwise,
10114            OpKind::TanhElementwise,
10115            OpKind::ExpElementwise,
10116            OpKind::LogElementwise,
10117            OpKind::SinElementwise,
10118            OpKind::CosElementwise,
10119            OpKind::SigmoidElementwise,
10120            OpKind::SiluElementwise,
10121            OpKind::GeluTanhElementwise,
10122            OpKind::StepElementwise,
10123            OpKind::SumReduce,
10124            OpKind::MaxReduce,
10125            OpKind::MinReduce,
10126            OpKind::MeanReduce,
10127            OpKind::Cast,
10128            OpKind::Conv2D,
10129            OpKind::ConvTranspose2D,
10130            OpKind::ReduceSumTo,
10131            OpKind::ReduceMaxTo,
10132            OpKind::FusedLinear,
10133            OpKind::FlashAttn,
10134            OpKind::PagedAttn,
10135            OpKind::Affine,
10136            OpKind::ClampElementwise,
10137            OpKind::PowIElementwise,
10138            OpKind::MaximumElementwise,
10139            OpKind::MinimumElementwise,
10140            OpKind::EqualElementwise,
10141            OpKind::NotEqualElementwise,
10142            OpKind::LessElementwise,
10143            OpKind::LessEqualElementwise,
10144            OpKind::GreaterElementwise,
10145            OpKind::GreaterEqualElementwise,
10146            OpKind::Where,
10147            OpKind::FloorElementwise,
10148            OpKind::CeilElementwise,
10149            OpKind::RoundElementwise,
10150            OpKind::SignElementwise,
10151            OpKind::ErfElementwise,
10152            OpKind::GeluElementwise,
10153            OpKind::PowElementwise,
10154            OpKind::RsqrtElementwise,
10155            OpKind::RemElementwise,
10156            OpKind::Flip,
10157            OpKind::Roll,
10158            OpKind::CumSum,
10159            OpKind::Pad,
10160            OpKind::PadBackward,
10161            OpKind::Triu,
10162            OpKind::Tril,
10163            OpKind::LogSoftmaxLastDim,
10164            OpKind::LogSoftmaxLastDimBackward,
10165            OpKind::MaskedFill,
10166            OpKind::Concat,
10167            OpKind::SoftmaxLastDim,
10168            OpKind::SoftmaxLastDimBackward,
10169            OpKind::RmsNormLastDim,
10170            OpKind::RmsNormLastDimBackward,
10171            OpKind::LayerNormLastDim,
10172            OpKind::LayerNormLastDimBackward,
10173            OpKind::ReduceMaxToBackward,
10174            OpKind::IndexSelect,
10175            OpKind::Gather,
10176            OpKind::Rope,
10177            OpKind::IndexAdd,
10178            OpKind::ScatterAdd,
10179            OpKind::ArgMaxDim,
10180            OpKind::ArgMinDim,
10181            OpKind::QMatMul,
10182            OpKind::Copy,
10183            OpKind::FusedSoftmaxCrossEntropy,
10184            OpKind::CausalConv1d,
10185            OpKind::SelectiveScan,
10186            OpKind::SsdChunkScan,
10187            OpKind::Nf4Matmul,
10188        ];
10189
10190        // Populate the binding table the same way the production
10191        // path does — via register_cpu_kernels including the
10192        // fill_unset_cpu_precision pass at the end.
10193        let mut table = KernelBindingTable::new();
10194        register_cpu_kernels(&mut table);
10195
10196        // Group all CPU registrations by OpKind so we can check
10197        // coverage per variant.
10198        let mut by_op_kind: std::collections::HashMap<
10199            OpKind,
10200            Vec<crate::fused::PrecisionGuarantee>,
10201        > = std::collections::HashMap::new();
10202        for (op, _dtypes, backend, precision) in table.iter_precision() {
10203            if backend == BackendId::Cpu {
10204                by_op_kind.entry(op).or_default().push(precision);
10205            }
10206        }
10207
10208        let mut failures: Vec<String> = Vec::new();
10209        let mut covered = 0usize;
10210        let mut allowlisted = 0usize;
10211
10212        for op in ALL_OP_KINDS.iter().copied() {
10213            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
10214                allowlisted += 1;
10215                if by_op_kind.contains_key(&op) {
10216                    failures.push(format!(
10217                        "OpKind::{op:?} is on the KNOWN_GAPS allowlist but DOES \
10218                         have a CPU registration now. Reason given was: \
10219                         {reason:?}. Remove the allowlist entry to enable the \
10220                         bit-stable lint for this op.",
10221                    ));
10222                }
10223                continue;
10224            }
10225            let precisions = by_op_kind.get(&op);
10226            let has_bit_stable_cpu =
10227                precisions.is_some_and(|ps| ps.iter().any(|p| p.bit_stable_on_same_hardware));
10228            if has_bit_stable_cpu {
10229                covered += 1;
10230            } else {
10231                failures.push(format!(
10232                    "OpKind::{op:?} has no bit-stable CPU registration. \
10233                     Architecture v1.0 §05 requires the always-built backend \
10234                     (fuel-cpu-backend) to provide at least one \
10235                     `bit_stable_on_same_hardware: true` kernel per primitive \
10236                     op. Either add a CPU registration in \
10237                     register_cpu_kernels (the fill_unset_cpu_precision pass \
10238                     at the end will upgrade it to PRIMITIVE_DETERMINISTIC_CPU \
10239                     automatically), or add a line to KNOWN_GAPS above with a \
10240                     documented reason.",
10241                ));
10242            }
10243        }
10244
10245        assert!(
10246            failures.is_empty(),
10247            "Architecture v1.0 bit-stable CPU coverage lint (primitives) failed:\n{}",
10248            failures.join("\n"),
10249        );
10250        assert_eq!(
10251            allowlisted, 0,
10252            "KNOWN_GAPS allowlist is empty by design; saw {allowlisted} allowlisted",
10253        );
10254        // Sanity: ALL_OP_KINDS should match the production
10255        // registration set. If a new variant lands in the enum
10256        // without being added here, the test's value is reduced —
10257        // catch the case by asserting the count.
10258        assert!(covered > 0, "lint covered 0 OpKinds — table appears empty",);
10259        // Sanity: every OpKind we enumerated should have ≥1 dtype
10260        // registration. The fill pass should have populated
10261        // precision for each.
10262        for op in ALL_OP_KINDS {
10263            assert!(
10264                by_op_kind.contains_key(op),
10265                "OpKind::{op:?} has no CPU registration at all — either add \
10266                 one in register_cpu_kernels or document the gap in \
10267                 KNOWN_GAPS.",
10268            );
10269        }
10270    }
10271
10272    /// Phase 7.6 step 8 — the "every OpKind has a real cost
10273    /// function" coverage lint. Companion to step 7b's bit-stable
10274    /// precision lint; the architectural commitment is that every
10275    /// primitive op carries both a `PrecisionGuarantee` and a
10276    /// `CostFn` (Layer-1 cost model: FLOPs + bandwidth + launch
10277    /// overhead) by the time the binding table is consulted at
10278    /// dispatch time.
10279    ///
10280    /// The lint runs as a unit test. Violations surface in CI
10281    /// rather than at runtime — a new `OpKind` variant without a
10282    /// matching arm in
10283    /// [`crate::cost::default_cost_for_op_kind`] fails this test
10284    /// immediately because the fill pass leaves it bound to
10285    /// `unknown_cost`.
10286    ///
10287    /// `KNOWN_GAPS` is empty as of step 8 (2026-05-12). Adding a
10288    /// future variant without immediate cost coverage needs a
10289    /// documented allowlist entry AND a follow-up.
10290    #[test]
10291    fn cost_lint_per_op_kind_cpu_coverage() {
10292        use fuel_ir::dispatch::OpKind;
10293        use fuel_ir::probe::BackendId;
10294
10295        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
10296
10297        const ALL_OP_KINDS: &[OpKind] = &[
10298            OpKind::MatMul,
10299            OpKind::AddElementwise,
10300            OpKind::SubElementwise,
10301            OpKind::MulElementwise,
10302            OpKind::DivElementwise,
10303            OpKind::ReluElementwise,
10304            OpKind::NegElementwise,
10305            OpKind::SqrElementwise,
10306            OpKind::SqrtElementwise,
10307            OpKind::RecipElementwise,
10308            OpKind::AbsElementwise,
10309            OpKind::TanhElementwise,
10310            OpKind::ExpElementwise,
10311            OpKind::LogElementwise,
10312            OpKind::SinElementwise,
10313            OpKind::CosElementwise,
10314            OpKind::SigmoidElementwise,
10315            OpKind::SiluElementwise,
10316            OpKind::GeluTanhElementwise,
10317            OpKind::StepElementwise,
10318            OpKind::SumReduce,
10319            OpKind::MaxReduce,
10320            OpKind::MinReduce,
10321            OpKind::MeanReduce,
10322            OpKind::Cast,
10323            OpKind::Conv2D,
10324            OpKind::ConvTranspose2D,
10325            OpKind::ReduceSumTo,
10326            OpKind::ReduceMaxTo,
10327            OpKind::FusedLinear,
10328            OpKind::FlashAttn,
10329            OpKind::PagedAttn,
10330            OpKind::Affine,
10331            OpKind::ClampElementwise,
10332            OpKind::PowIElementwise,
10333            OpKind::MaximumElementwise,
10334            OpKind::MinimumElementwise,
10335            OpKind::EqualElementwise,
10336            OpKind::NotEqualElementwise,
10337            OpKind::LessElementwise,
10338            OpKind::LessEqualElementwise,
10339            OpKind::GreaterElementwise,
10340            OpKind::GreaterEqualElementwise,
10341            OpKind::Where,
10342            OpKind::FloorElementwise,
10343            OpKind::CeilElementwise,
10344            OpKind::RoundElementwise,
10345            OpKind::SignElementwise,
10346            OpKind::ErfElementwise,
10347            OpKind::GeluElementwise,
10348            OpKind::PowElementwise,
10349            OpKind::RsqrtElementwise,
10350            OpKind::RemElementwise,
10351            OpKind::Flip,
10352            OpKind::Roll,
10353            OpKind::CumSum,
10354            OpKind::Pad,
10355            OpKind::PadBackward,
10356            OpKind::Triu,
10357            OpKind::Tril,
10358            OpKind::LogSoftmaxLastDim,
10359            OpKind::LogSoftmaxLastDimBackward,
10360            OpKind::MaskedFill,
10361            OpKind::Concat,
10362            OpKind::SoftmaxLastDim,
10363            OpKind::SoftmaxLastDimBackward,
10364            OpKind::RmsNormLastDim,
10365            OpKind::RmsNormLastDimBackward,
10366            OpKind::LayerNormLastDim,
10367            OpKind::LayerNormLastDimBackward,
10368            OpKind::ReduceMaxToBackward,
10369            OpKind::IndexSelect,
10370            OpKind::Gather,
10371            OpKind::Rope,
10372            OpKind::IndexAdd,
10373            OpKind::ScatterAdd,
10374            OpKind::ArgMaxDim,
10375            OpKind::ArgMinDim,
10376            OpKind::QMatMul,
10377            OpKind::Copy,
10378            OpKind::FusedSoftmaxCrossEntropy,
10379            OpKind::CausalConv1d,
10380            OpKind::SelectiveScan,
10381            OpKind::SsdChunkScan,
10382            OpKind::Nf4Matmul,
10383        ];
10384
10385        let mut table = KernelBindingTable::new();
10386        register_cpu_kernels(&mut table);
10387
10388        // Group cost functions by OpKind for CPU registrations.
10389        let mut by_op_kind: std::collections::HashMap<OpKind, Vec<crate::kernel::CostFn>> =
10390            std::collections::HashMap::new();
10391        for (op, _dtypes, backend, cost) in table.iter_cost() {
10392            if backend == BackendId::Cpu {
10393                by_op_kind.entry(op).or_default().push(cost);
10394            }
10395        }
10396
10397        let unknown_sentinel = crate::kernel::unknown_cost as *const () as usize;
10398
10399        let mut failures: Vec<String> = Vec::new();
10400        for op in ALL_OP_KINDS.iter().copied() {
10401            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
10402                if let Some(costs) = by_op_kind.get(&op) {
10403                    let has_real = costs.iter().any(|c| (*c as usize) != unknown_sentinel);
10404                    if has_real {
10405                        failures.push(format!(
10406                            "OpKind::{op:?} is on the cost-lint KNOWN_GAPS \
10407                             allowlist but DOES have a non-default cost fn \
10408                             now. Reason given: {reason:?}. Remove the \
10409                             allowlist entry.",
10410                        ));
10411                    }
10412                }
10413                continue;
10414            }
10415            let costs = by_op_kind.get(&op);
10416            let has_real_cost =
10417                costs.is_some_and(|cs| cs.iter().any(|c| (*c as usize) != unknown_sentinel));
10418            if !has_real_cost {
10419                failures.push(format!(
10420                    "OpKind::{op:?} has no non-default cost fn in any CPU \
10421                     registration. Either add an arm in \
10422                     `crate::cost::default_cost_for_op_kind` (the \
10423                     fill_unset_cpu_cost pass at the end of \
10424                     register_cpu_kernels will pick it up automatically), \
10425                     register an explicit cost via `register_full(...)`, \
10426                     or add a line to KNOWN_GAPS with a documented reason.",
10427                ));
10428            }
10429        }
10430
10431        assert!(
10432            failures.is_empty(),
10433            "Phase 7.6 step 8 cost-coverage lint failed:\n{}",
10434            failures.join("\n"),
10435        );
10436        // Sanity: every OpKind we enumerated should have ≥1 CPU
10437        // registration (asserted separately by the step-7b lint,
10438        // but re-checked here for symmetry).
10439        for op in ALL_OP_KINDS {
10440            assert!(
10441                by_op_kind.contains_key(op),
10442                "OpKind::{op:?} has no CPU registration at all.",
10443            );
10444        }
10445    }
10446
10447    fn cpu_caps() -> BackendCapabilities {
10448        BackendCapabilities {
10449            backend_id: BackendId::Cpu,
10450            device_location: DeviceLocation::Cpu,
10451            op_dtype_support: [
10452                (OpKind::MatMul, DType::F32),
10453                (OpKind::MatMul, DType::F64),
10454                (OpKind::AddElementwise, DType::F32),
10455                (OpKind::AddElementwise, DType::F64),
10456            ]
10457            .into_iter()
10458            .collect(),
10459            required_alignment: 64,
10460            access_granularity_bits: 8,
10461            transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
10462            storage_substrate: SubstrateClass::HostBytes,
10463            compute_throughput_flops_per_ns: 1.0,
10464            mem_bandwidth_bytes_per_ns: 4.0,
10465        }
10466    }
10467
10468    fn cuda_caps() -> BackendCapabilities {
10469        BackendCapabilities {
10470            backend_id: BackendId::Cuda,
10471            device_location: DeviceLocation::Cuda { gpu_id: 0 },
10472            op_dtype_support: [
10473                (OpKind::MatMul, DType::F32),
10474                (OpKind::MatMul, DType::F16),
10475                (OpKind::AddElementwise, DType::F32),
10476            ]
10477            .into_iter()
10478            .collect(),
10479            required_alignment: 256,
10480            access_granularity_bits: 8,
10481            transfer_paths: vec![
10482                (DeviceLocation::Cpu, TransferPath::DeviceCopy),
10483                (DeviceLocation::Cuda { gpu_id: 0 }, TransferPath::SameDevice),
10484            ],
10485            storage_substrate: SubstrateClass::CudaUntyped,
10486            compute_throughput_flops_per_ns: 30.0,
10487            mem_bandwidth_bytes_per_ns: 40.0,
10488        }
10489    }
10490
10491    /// Smoke: empty registry has nothing.
10492    #[test]
10493    fn empty_registry() {
10494        let r = CapabilityRegistry::new();
10495        assert!(r.backends().is_empty());
10496        let result = r.find_backend_for(OpKind::MatMul, DType::F32);
10497        assert!(result.is_err());
10498    }
10499
10500    /// Find_backends returns matching backends in registration order.
10501    #[test]
10502    fn find_backends_order_preserved() {
10503        let mut r = CapabilityRegistry::new();
10504        r.register(cuda_caps()); // registered first → wins ties
10505        r.register(cpu_caps());
10506
10507        let backends = r.find_backends(OpKind::MatMul, DType::F32);
10508        assert_eq!(backends.len(), 2);
10509        assert_eq!(backends[0].backend_id, BackendId::Cuda);
10510        assert_eq!(backends[1].backend_id, BackendId::Cpu);
10511    }
10512
10513    /// Find_backend_for picks first match.
10514    #[test]
10515    fn find_backend_first_wins() {
10516        let mut r = CapabilityRegistry::new();
10517        r.register(cuda_caps());
10518        r.register(cpu_caps());
10519
10520        let chosen = r.find_backend_for(OpKind::MatMul, DType::F32).unwrap();
10521        assert_eq!(chosen.backend_id, BackendId::Cuda);
10522    }
10523
10524    /// CPU-only registry falls back when GPU dtypes aren't supported.
10525    #[test]
10526    fn cpu_handles_what_gpu_doesnt() {
10527        let mut r = CapabilityRegistry::new();
10528        r.register(cuda_caps());
10529        r.register(cpu_caps());
10530
10531        // CUDA doesn't support F64; CPU does.
10532        let chosen = r.find_backend_for(OpKind::MatMul, DType::F64).unwrap();
10533        assert_eq!(chosen.backend_id, BackendId::Cpu);
10534    }
10535
10536    /// Unsupported (op, dtype) returns NoBackendForOp with diagnostic data.
10537    #[test]
10538    fn unsupported_combo_errors_with_diagnostic() {
10539        let mut r = CapabilityRegistry::new();
10540        r.register(cpu_caps());
10541
10542        let err = match r.find_backend_for(OpKind::MatMul, DType::BF16) {
10543            Ok(_) => panic!("expected error"),
10544            Err(e) => e,
10545        };
10546        let msg = err.to_string();
10547        assert!(
10548            msg.contains("MatMul") || msg.contains("matmul"),
10549            "error names op: {msg}"
10550        );
10551        assert!(msg.contains("BF16"), "error names dtype: {msg}");
10552        assert!(msg.contains("Cpu"), "error names available backends: {msg}");
10553    }
10554
10555    /// TransferMatrix preserves SameDevice for src == dst always.
10556    #[test]
10557    fn transfer_matrix_same_device() {
10558        let r = CapabilityRegistry::new();
10559        let m = r.build_transfer_matrix();
10560        assert_eq!(
10561            m.path(DeviceLocation::Cpu, DeviceLocation::Cpu),
10562            Some(TransferPath::SameDevice)
10563        );
10564    }
10565
10566    /// TransferMatrix entries from registered backends.
10567    #[test]
10568    fn transfer_matrix_built_from_caps() {
10569        let mut r = CapabilityRegistry::new();
10570        r.register(cuda_caps());
10571        let m = r.build_transfer_matrix();
10572
10573        // CUDA → CPU is DeviceCopy (advertised).
10574        assert_eq!(
10575            m.path(DeviceLocation::Cuda { gpu_id: 0 }, DeviceLocation::Cpu),
10576            Some(TransferPath::DeviceCopy)
10577        );
10578    }
10579
10580    /// path_or_staging falls back to HostStaging for unadvertised
10581    /// pairs.
10582    #[test]
10583    fn host_staging_fallback() {
10584        let r = CapabilityRegistry::new();
10585        let m = r.build_transfer_matrix();
10586        // No CPU registered; CPU→Cuda has no entry; staging fallback.
10587        assert_eq!(
10588            m.path_or_staging(DeviceLocation::Cpu, DeviceLocation::Cuda { gpu_id: 0 }),
10589            TransferPath::HostStaging
10590        );
10591    }
10592
10593    /// resolve_target_backend picks the first registered backend
10594    /// supporting (op, dtype).
10595    #[test]
10596    fn resolve_picks_first_match() {
10597        let mut r = CapabilityRegistry::new();
10598        r.register(cuda_caps());
10599        r.register(cpu_caps());
10600        assert_eq!(
10601            resolve_target_backend(&r, OpKind::MatMul, DType::F32).unwrap(),
10602            BackendId::Cuda
10603        );
10604    }
10605
10606    /// resolve_target_backend falls back to CPU for dtypes GPU doesn't support.
10607    #[test]
10608    fn resolve_falls_back_to_cpu() {
10609        let mut r = CapabilityRegistry::new();
10610        r.register(cuda_caps());
10611        r.register(cpu_caps());
10612        assert_eq!(
10613            resolve_target_backend(&r, OpKind::MatMul, DType::F64).unwrap(),
10614            BackendId::Cpu
10615        );
10616    }
10617
10618    /// resolve_target_backend errors with NoBackendForOp on miss.
10619    #[test]
10620    fn resolve_errors_on_unsupported() {
10621        let mut r = CapabilityRegistry::new();
10622        r.register(cpu_caps());
10623        let result = resolve_target_backend(&r, OpKind::MatMul, DType::BF16);
10624        assert!(result.is_err());
10625    }
10626
10627    /// Residency-aware resolver picks a backend with input-local
10628    /// residency when available.
10629    #[test]
10630    fn resolve_residency_aware_prefers_local() {
10631        let mut r = CapabilityRegistry::new();
10632        // CUDA registered first (would normally win ties for f32).
10633        r.register(cuda_caps());
10634        r.register(cpu_caps());
10635
10636        // Inputs live on CPU; residency-aware prefers CPU even
10637        // though CUDA also supports (MatMul, F32).
10638        let chosen = resolve_target_backend_residency_aware(
10639            &r,
10640            OpKind::MatMul,
10641            DType::F32,
10642            &[DeviceLocation::Cpu],
10643        )
10644        .unwrap();
10645        assert_eq!(chosen, BackendId::Cpu);
10646    }
10647
10648    /// Residency-aware falls back to first match when no residency
10649    /// match exists.
10650    #[test]
10651    fn resolve_residency_aware_no_local_falls_back() {
10652        let mut r = CapabilityRegistry::new();
10653        r.register(cuda_caps());
10654        r.register(cpu_caps());
10655
10656        // Inputs on a Vulkan device — no candidate matches; falls
10657        // back to first (CUDA).
10658        let chosen = resolve_target_backend_residency_aware(
10659            &r,
10660            OpKind::MatMul,
10661            DType::F32,
10662            &[DeviceLocation::Vulkan { gpu_id: 0 }],
10663        )
10664        .unwrap();
10665        assert_eq!(chosen, BackendId::Cuda);
10666    }
10667
10668    // -------- B5: kernel binding table + CPU dispatch wrappers --------
10669
10670    /// Smoke: register_cpu_kernels populates the binding table.
10671    #[test]
10672    fn register_cpu_kernels_populates_table() {
10673        let mut table = KernelBindingTable::new();
10674        assert!(table.is_empty());
10675        register_cpu_kernels(&mut table);
10676        assert!(!table.is_empty());
10677        // The (AddElementwise, F32, Cpu) binding lands.
10678        let _kernel = table
10679            .lookup(
10680                OpKind::AddElementwise,
10681                &[DType::F32, DType::F32, DType::F32],
10682                BackendId::Cpu,
10683            )
10684            .expect("registered");
10685    }
10686
10687    /// FIRST PRODUCTION FKC CONSUMER (born-red gate). `global_bindings()`
10688    /// registers the CPU elementwise-binary family (8 ops × 4 dtypes = 32
10689    /// bindings) FROM ITS KERNEL CONTRACT
10690    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`) — the sole
10691    /// registration path, now that the hand-written `table.register(...)`
10692    /// calls for this family are DELETED.
10693    ///
10694    /// For each of the 32 `(op, [dt; 3], Cpu)` keys this asserts:
10695    ///  - the binding resolves to the EXACT production wrapper fn-pointer
10696    ///    (behavior-preserving execution),
10697    ///  - `kernel_source == "portable-cpu"` — the contract's provenance tag
10698    ///    (the deleted hand-written path stamped `""`). THIS is the
10699    ///    discriminator that makes the test go red without the import wired:
10700    ///    with the hand-written binary regs removed and the import absent, the
10701    ///    family is simply missing from `global_bindings()`,
10702    ///  - caps stay empty (`strided_input == false`) and the contract's
10703    ///    audited bit-stable precision claim rode through.
10704    #[test]
10705    fn global_bindings_registers_binary_family_from_contract() {
10706        let table = global_bindings();
10707
10708        // (op, [f32, f64, bf16, f16] production wrappers) for all 8 ops.
10709        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10710            (
10711                OpKind::AddElementwise,
10712                [
10713                    add_elementwise_f32_cpu_wrapper,
10714                    add_elementwise_f64_cpu_wrapper,
10715                    add_elementwise_bf16_cpu_wrapper,
10716                    add_elementwise_f16_cpu_wrapper,
10717                ],
10718            ),
10719            (
10720                OpKind::SubElementwise,
10721                [
10722                    sub_elementwise_f32_cpu_wrapper,
10723                    sub_elementwise_f64_cpu_wrapper,
10724                    sub_elementwise_bf16_cpu_wrapper,
10725                    sub_elementwise_f16_cpu_wrapper,
10726                ],
10727            ),
10728            (
10729                OpKind::MulElementwise,
10730                [
10731                    mul_elementwise_f32_cpu_wrapper,
10732                    mul_elementwise_f64_cpu_wrapper,
10733                    mul_elementwise_bf16_cpu_wrapper,
10734                    mul_elementwise_f16_cpu_wrapper,
10735                ],
10736            ),
10737            (
10738                OpKind::DivElementwise,
10739                [
10740                    div_elementwise_f32_cpu_wrapper,
10741                    div_elementwise_f64_cpu_wrapper,
10742                    div_elementwise_bf16_cpu_wrapper,
10743                    div_elementwise_f16_cpu_wrapper,
10744                ],
10745            ),
10746            (
10747                OpKind::MaximumElementwise,
10748                [
10749                    maximum_elementwise_f32_cpu_wrapper,
10750                    maximum_elementwise_f64_cpu_wrapper,
10751                    maximum_elementwise_bf16_cpu_wrapper,
10752                    maximum_elementwise_f16_cpu_wrapper,
10753                ],
10754            ),
10755            (
10756                OpKind::MinimumElementwise,
10757                [
10758                    minimum_elementwise_f32_cpu_wrapper,
10759                    minimum_elementwise_f64_cpu_wrapper,
10760                    minimum_elementwise_bf16_cpu_wrapper,
10761                    minimum_elementwise_f16_cpu_wrapper,
10762                ],
10763            ),
10764            (
10765                OpKind::PowElementwise,
10766                [
10767                    pow_elementwise_f32_cpu_wrapper,
10768                    pow_elementwise_f64_cpu_wrapper,
10769                    pow_elementwise_bf16_cpu_wrapper,
10770                    pow_elementwise_f16_cpu_wrapper,
10771                ],
10772            ),
10773            (
10774                OpKind::RemElementwise,
10775                [
10776                    rem_elementwise_f32_cpu_wrapper,
10777                    rem_elementwise_f64_cpu_wrapper,
10778                    rem_elementwise_bf16_cpu_wrapper,
10779                    rem_elementwise_f16_cpu_wrapper,
10780                ],
10781            ),
10782        ];
10783        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10784
10785        let mut checked = 0usize;
10786        for (op, wrappers) in families {
10787            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10788                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
10789                let entry = alts
10790                    .iter()
10791                    .find(|e| e.kernel as usize == *expected as usize)
10792                    .unwrap_or_else(|| {
10793                        panic!(
10794                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10795                             FROM the elementwise-binary contract in global_bindings() \
10796                             — found {} alternative(s) with sources {:?}",
10797                            alts.len(),
10798                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10799                        )
10800                    });
10801                assert_eq!(
10802                    entry.kernel_source, "portable-cpu",
10803                    "{op:?}/{dt:?}: binary family must be contract-sourced \
10804                     (kernel_source=\"portable-cpu\"); got {:?}",
10805                    entry.kernel_source,
10806                );
10807                assert!(
10808                    !entry.caps.strided_input,
10809                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10810                );
10811                assert!(
10812                    entry.precision.bit_stable_on_same_hardware,
10813                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10814                );
10815                checked += 1;
10816            }
10817        }
10818        assert_eq!(checked, 32, "all 8 ops × 4 dtypes checked");
10819    }
10820
10821    /// FKC born-red gate for the CPU affine / clamp / powi family.
10822    /// `global_bindings()` registers the out-of-place scalar-param family
10823    /// (affine/clamp/powi × 4 dtypes + powi_backward × 4 = 16 bindings) FROM
10824    /// ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md`)
10825    /// — the sole registration path, now that the hand-written
10826    /// `table.register(...)` calls are DELETED. Asserts each (op, dtype, Cpu)
10827    /// key resolves to the EXACT production wrapper fn-pointer, is
10828    /// contract-sourced (`kernel_source == "portable-cpu"`), caps stayed
10829    /// contiguous-only, and the audited bit-stable precision claim rode through.
10830    #[test]
10831    fn global_bindings_registers_affine_clamp_powi_family_from_contract() {
10832        let table = global_bindings();
10833        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10834
10835        // Single-input forward ops → key [dt, dt].
10836        let forward: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10837            (
10838                OpKind::Affine,
10839                [
10840                    affine_f32_cpu_wrapper,
10841                    affine_f64_cpu_wrapper,
10842                    affine_bf16_cpu_wrapper,
10843                    affine_f16_cpu_wrapper,
10844                ],
10845            ),
10846            (
10847                OpKind::ClampElementwise,
10848                [
10849                    clamp_elementwise_f32_cpu_wrapper,
10850                    clamp_f64_cpu_wrapper,
10851                    clamp_bf16_cpu_wrapper,
10852                    clamp_f16_cpu_wrapper,
10853                ],
10854            ),
10855            (
10856                OpKind::PowIElementwise,
10857                [
10858                    powi_elementwise_f32_cpu_wrapper,
10859                    powi_f64_cpu_wrapper,
10860                    powi_bf16_cpu_wrapper,
10861                    powi_f16_cpu_wrapper,
10862                ],
10863            ),
10864        ];
10865
10866        let mut checked = 0usize;
10867        for (op, wrappers) in forward {
10868            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10869                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10870                let entry = alts
10871                    .iter()
10872                    .find(|e| e.kernel as usize == *expected as usize)
10873                    .unwrap_or_else(|| {
10874                        panic!(
10875                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10876                             FROM the affine-clamp-powi contract in global_bindings() \
10877                             — found {} alternative(s) with sources {:?}",
10878                            alts.len(),
10879                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10880                        )
10881                    });
10882                assert_eq!(
10883                    entry.kernel_source, "portable-cpu",
10884                    "{op:?}/{dt:?}: family must be contract-sourced \
10885                     (kernel_source=\"portable-cpu\"); got {:?}",
10886                    entry.kernel_source,
10887                );
10888                assert!(
10889                    !entry.caps.strided_input,
10890                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10891                );
10892                assert!(
10893                    entry.precision.bit_stable_on_same_hardware,
10894                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10895                );
10896                checked += 1;
10897            }
10898        }
10899
10900        // Two-input backward op → key [dt, dt, dt].
10901        let bw: [crate::kernel::KernelRef; 4] = [
10902            powi_backward_f32_cpu_wrapper,
10903            powi_backward_f64_cpu_wrapper,
10904            powi_backward_bf16_cpu_wrapper,
10905            powi_backward_f16_cpu_wrapper,
10906        ];
10907        for (dt, expected) in dts.iter().zip(bw.iter()) {
10908            let alts = table.lookup_alternatives(
10909                OpKind::PowIElementwiseBackward,
10910                &[*dt, *dt, *dt],
10911                BackendId::Cpu,
10912            );
10913            let entry = alts
10914                .iter()
10915                .find(|e| e.kernel as usize == *expected as usize)
10916                .unwrap_or_else(|| {
10917                    panic!(
10918                        "PowIElementwiseBackward/{dt:?}/Cpu: the production wrapper must \
10919                         be bound FROM the affine-clamp-powi contract in global_bindings() \
10920                         — found {} alternative(s) with sources {:?}",
10921                        alts.len(),
10922                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10923                    )
10924                });
10925            assert_eq!(
10926                entry.kernel_source, "portable-cpu",
10927                "PowIElementwiseBackward/{dt:?}: must be contract-sourced; got {:?}",
10928                entry.kernel_source,
10929            );
10930            assert!(
10931                !entry.caps.strided_input,
10932                "PowIElementwiseBackward/{dt:?}: caps preserved (contiguous-only)",
10933            );
10934            assert!(
10935                entry.precision.bit_stable_on_same_hardware,
10936                "PowIElementwiseBackward/{dt:?}: the audited bit-stable claim rode through",
10937            );
10938            checked += 1;
10939        }
10940
10941        assert_eq!(checked, 16, "3 forward ops × 4 dtypes + powi_backward × 4");
10942    }
10943
10944    /// FKC born-red gate for the CPU elementwise-unary family.
10945    /// `global_bindings()` registers the elementwise-unary family (22 ops × 4
10946    /// dtypes = 88 bindings) FROM ITS KERNEL CONTRACT
10947    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md`) via the §3.4
10948    /// multi-dtype fan-out (each per-op section declares a BASE `entry_point`
10949    /// that the importer expands to `<base>_<dtype>`) — the sole registration
10950    /// path, now that the hand-written `table.register(...)` calls are DELETED.
10951    /// Asserts each (op, dtype, Cpu) key resolves to the EXACT production
10952    /// wrapper fn-pointer, is contract-sourced (`kernel_source == "portable-cpu"`),
10953    /// caps stayed contiguous-only, and the audited bit-stable precision claim
10954    /// rode through. `gelu_tanh` (`GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
10955    /// (`GeluElementwise`, base `gelu`) are kept DISTINCT.
10956    #[test]
10957    fn global_bindings_registers_unary_family_from_contract() {
10958        let table = global_bindings();
10959        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10960
10961        // (op, [f32, f64, bf16, f16] production wrappers) for all 22 ops.
10962        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10963            (
10964                OpKind::ReluElementwise,
10965                [
10966                    relu_elementwise_f32_cpu_wrapper,
10967                    relu_elementwise_f64_cpu_wrapper,
10968                    relu_elementwise_bf16_cpu_wrapper,
10969                    relu_elementwise_f16_cpu_wrapper,
10970                ],
10971            ),
10972            (
10973                OpKind::NegElementwise,
10974                [
10975                    neg_elementwise_f32_cpu_wrapper,
10976                    neg_elementwise_f64_cpu_wrapper,
10977                    neg_elementwise_bf16_cpu_wrapper,
10978                    neg_elementwise_f16_cpu_wrapper,
10979                ],
10980            ),
10981            (
10982                OpKind::SqrElementwise,
10983                [
10984                    sqr_elementwise_f32_cpu_wrapper,
10985                    sqr_elementwise_f64_cpu_wrapper,
10986                    sqr_elementwise_bf16_cpu_wrapper,
10987                    sqr_elementwise_f16_cpu_wrapper,
10988                ],
10989            ),
10990            (
10991                OpKind::SqrtElementwise,
10992                [
10993                    sqrt_elementwise_f32_cpu_wrapper,
10994                    sqrt_elementwise_f64_cpu_wrapper,
10995                    sqrt_elementwise_bf16_cpu_wrapper,
10996                    sqrt_elementwise_f16_cpu_wrapper,
10997                ],
10998            ),
10999            (
11000                OpKind::RecipElementwise,
11001                [
11002                    recip_elementwise_f32_cpu_wrapper,
11003                    recip_elementwise_f64_cpu_wrapper,
11004                    recip_elementwise_bf16_cpu_wrapper,
11005                    recip_elementwise_f16_cpu_wrapper,
11006                ],
11007            ),
11008            (
11009                OpKind::AbsElementwise,
11010                [
11011                    abs_elementwise_f32_cpu_wrapper,
11012                    abs_elementwise_f64_cpu_wrapper,
11013                    abs_elementwise_bf16_cpu_wrapper,
11014                    abs_elementwise_f16_cpu_wrapper,
11015                ],
11016            ),
11017            (
11018                OpKind::TanhElementwise,
11019                [
11020                    tanh_elementwise_f32_cpu_wrapper,
11021                    tanh_elementwise_f64_cpu_wrapper,
11022                    tanh_elementwise_bf16_cpu_wrapper,
11023                    tanh_elementwise_f16_cpu_wrapper,
11024                ],
11025            ),
11026            (
11027                OpKind::ExpElementwise,
11028                [
11029                    exp_elementwise_f32_cpu_wrapper,
11030                    exp_elementwise_f64_cpu_wrapper,
11031                    exp_elementwise_bf16_cpu_wrapper,
11032                    exp_elementwise_f16_cpu_wrapper,
11033                ],
11034            ),
11035            (
11036                OpKind::LogElementwise,
11037                [
11038                    log_elementwise_f32_cpu_wrapper,
11039                    log_elementwise_f64_cpu_wrapper,
11040                    log_elementwise_bf16_cpu_wrapper,
11041                    log_elementwise_f16_cpu_wrapper,
11042                ],
11043            ),
11044            (
11045                OpKind::SinElementwise,
11046                [
11047                    sin_elementwise_f32_cpu_wrapper,
11048                    sin_elementwise_f64_cpu_wrapper,
11049                    sin_elementwise_bf16_cpu_wrapper,
11050                    sin_elementwise_f16_cpu_wrapper,
11051                ],
11052            ),
11053            (
11054                OpKind::CosElementwise,
11055                [
11056                    cos_elementwise_f32_cpu_wrapper,
11057                    cos_elementwise_f64_cpu_wrapper,
11058                    cos_elementwise_bf16_cpu_wrapper,
11059                    cos_elementwise_f16_cpu_wrapper,
11060                ],
11061            ),
11062            (
11063                OpKind::SigmoidElementwise,
11064                [
11065                    sigmoid_elementwise_f32_cpu_wrapper,
11066                    sigmoid_elementwise_f64_cpu_wrapper,
11067                    sigmoid_elementwise_bf16_cpu_wrapper,
11068                    sigmoid_elementwise_f16_cpu_wrapper,
11069                ],
11070            ),
11071            (
11072                OpKind::SiluElementwise,
11073                [
11074                    silu_elementwise_f32_cpu_wrapper,
11075                    silu_elementwise_f64_cpu_wrapper,
11076                    silu_elementwise_bf16_cpu_wrapper,
11077                    silu_elementwise_f16_cpu_wrapper,
11078                ],
11079            ),
11080            (
11081                OpKind::StepElementwise,
11082                [
11083                    step_elementwise_f32_cpu_wrapper,
11084                    step_elementwise_f64_cpu_wrapper,
11085                    step_elementwise_bf16_cpu_wrapper,
11086                    step_elementwise_f16_cpu_wrapper,
11087                ],
11088            ),
11089            (
11090                OpKind::GeluTanhElementwise,
11091                [
11092                    gelu_elementwise_f32_cpu_wrapper,
11093                    gelu_elementwise_f64_cpu_wrapper,
11094                    gelu_elementwise_bf16_cpu_wrapper,
11095                    gelu_elementwise_f16_cpu_wrapper,
11096                ],
11097            ),
11098            (
11099                OpKind::FloorElementwise,
11100                [
11101                    floor_elementwise_f32_cpu_wrapper,
11102                    floor_elementwise_f64_cpu_wrapper,
11103                    floor_elementwise_bf16_cpu_wrapper,
11104                    floor_elementwise_f16_cpu_wrapper,
11105                ],
11106            ),
11107            (
11108                OpKind::CeilElementwise,
11109                [
11110                    ceil_elementwise_f32_cpu_wrapper,
11111                    ceil_elementwise_f64_cpu_wrapper,
11112                    ceil_elementwise_bf16_cpu_wrapper,
11113                    ceil_elementwise_f16_cpu_wrapper,
11114                ],
11115            ),
11116            (
11117                OpKind::RoundElementwise,
11118                [
11119                    round_elementwise_f32_cpu_wrapper,
11120                    round_elementwise_f64_cpu_wrapper,
11121                    round_elementwise_bf16_cpu_wrapper,
11122                    round_elementwise_f16_cpu_wrapper,
11123                ],
11124            ),
11125            (
11126                OpKind::SignElementwise,
11127                [
11128                    sign_elementwise_f32_cpu_wrapper,
11129                    sign_elementwise_f64_cpu_wrapper,
11130                    sign_elementwise_bf16_cpu_wrapper,
11131                    sign_elementwise_f16_cpu_wrapper,
11132                ],
11133            ),
11134            (
11135                OpKind::ErfElementwise,
11136                [
11137                    erf_elementwise_f32_cpu_wrapper,
11138                    erf_elementwise_f64_cpu_wrapper,
11139                    erf_elementwise_bf16_cpu_wrapper,
11140                    erf_elementwise_f16_cpu_wrapper,
11141                ],
11142            ),
11143            (
11144                OpKind::GeluElementwise,
11145                [
11146                    gelu_erf_elementwise_f32_cpu_wrapper,
11147                    gelu_erf_elementwise_f64_cpu_wrapper,
11148                    gelu_erf_elementwise_bf16_cpu_wrapper,
11149                    gelu_erf_elementwise_f16_cpu_wrapper,
11150                ],
11151            ),
11152            (
11153                OpKind::RsqrtElementwise,
11154                [
11155                    rsqrt_elementwise_f32_cpu_wrapper,
11156                    rsqrt_elementwise_f64_cpu_wrapper,
11157                    rsqrt_elementwise_bf16_cpu_wrapper,
11158                    rsqrt_elementwise_f16_cpu_wrapper,
11159                ],
11160            ),
11161        ];
11162
11163        let mut checked = 0usize;
11164        for (op, wrappers) in families {
11165            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11166                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11167                let entry = alts
11168                    .iter()
11169                    .find(|e| e.kernel as usize == *expected as usize)
11170                    .unwrap_or_else(|| {
11171                        panic!(
11172                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11173                             FROM the elementwise-unary contract in global_bindings() \
11174                             — found {} alternative(s) with sources {:?}",
11175                            alts.len(),
11176                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11177                        )
11178                    });
11179                assert_eq!(
11180                    entry.kernel_source, "portable-cpu",
11181                    "{op:?}/{dt:?}: unary family must be contract-sourced \
11182                     (kernel_source=\"portable-cpu\"); got {:?}",
11183                    entry.kernel_source,
11184                );
11185                assert!(
11186                    !entry.caps.strided_input,
11187                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11188                );
11189                assert!(
11190                    entry.precision.bit_stable_on_same_hardware,
11191                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11192                );
11193                checked += 1;
11194            }
11195        }
11196        assert_eq!(checked, 88, "all 22 ops × 4 dtypes checked");
11197    }
11198
11199    /// FKC production consumer (born-red gate). `global_bindings()` registers
11200    /// the CPU compare + where family FROM ITS KERNEL CONTRACT
11201    /// (`fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md`) — the sole path now
11202    /// that the hand-written `table.register(...)` calls for this family are
11203    /// DELETED.
11204    ///
11205    /// Two key shapes, and getting them right IS the point of the test:
11206    ///  - COMPARE (6 ops × 4 dtypes = 24): the U8-mask operand-dtype list
11207    ///    `[T, T, U8]` (`return.out` is always `fixed(U8)`), NOT `[T, T, T]`.
11208    ///  - WHERE (1 op × 4 dtypes = 4): the ternary-select list `[U8, T, T, T]`
11209    ///    (cond U8 + a/b/out share T). `where` exercises BOTH the §3.4
11210    ///    multi-dtype fan-out (one contract section → 4 per-dtype bindings) AND
11211    ///    the `passthrough(a)` fix (output mirrors `a`=T, not the U8 cond).
11212    ///
11213    /// For each key: resolves to the EXACT production wrapper fn-pointer and
11214    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11215    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11216    /// goes red until the import is wired) — with caps contiguous and the
11217    /// audited bit-stable precision riding through.
11218    #[test]
11219    fn global_bindings_registers_compare_where_family_from_contract() {
11220        let table = global_bindings();
11221        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11222
11223        // -- COMPARE: 6 ops × 4 dtypes, key [T, T, BOOL] (GAP-168c) --
11224        let compare_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11225            (
11226                OpKind::EqualElementwise,
11227                [
11228                    eq_elementwise_f32_cpu_wrapper,
11229                    eq_elementwise_f64_cpu_wrapper,
11230                    eq_elementwise_bf16_cpu_wrapper,
11231                    eq_elementwise_f16_cpu_wrapper,
11232                ],
11233            ),
11234            (
11235                OpKind::NotEqualElementwise,
11236                [
11237                    ne_elementwise_f32_cpu_wrapper,
11238                    ne_elementwise_f64_cpu_wrapper,
11239                    ne_elementwise_bf16_cpu_wrapper,
11240                    ne_elementwise_f16_cpu_wrapper,
11241                ],
11242            ),
11243            (
11244                OpKind::LessElementwise,
11245                [
11246                    lt_elementwise_f32_cpu_wrapper,
11247                    lt_elementwise_f64_cpu_wrapper,
11248                    lt_elementwise_bf16_cpu_wrapper,
11249                    lt_elementwise_f16_cpu_wrapper,
11250                ],
11251            ),
11252            (
11253                OpKind::LessEqualElementwise,
11254                [
11255                    le_elementwise_f32_cpu_wrapper,
11256                    le_elementwise_f64_cpu_wrapper,
11257                    le_elementwise_bf16_cpu_wrapper,
11258                    le_elementwise_f16_cpu_wrapper,
11259                ],
11260            ),
11261            (
11262                OpKind::GreaterElementwise,
11263                [
11264                    gt_elementwise_f32_cpu_wrapper,
11265                    gt_elementwise_f64_cpu_wrapper,
11266                    gt_elementwise_bf16_cpu_wrapper,
11267                    gt_elementwise_f16_cpu_wrapper,
11268                ],
11269            ),
11270            (
11271                OpKind::GreaterEqualElementwise,
11272                [
11273                    ge_elementwise_f32_cpu_wrapper,
11274                    ge_elementwise_f64_cpu_wrapper,
11275                    ge_elementwise_bf16_cpu_wrapper,
11276                    ge_elementwise_f16_cpu_wrapper,
11277                ],
11278            ),
11279        ];
11280
11281        let mut checked = 0usize;
11282        for (op, wrappers) in compare_families {
11283            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11284                // Bool-mask operand-dtype list: [T, T, Bool] — NOT [T, T, T].
11285                // GAP-168(c): comparisons key on Bool, not the retired U8 mask.
11286                let alts = table.lookup_alternatives(*op, &[*dt, *dt, DType::Bool], BackendId::Cpu);
11287                let entry = alts
11288                    .iter()
11289                    .find(|e| e.kernel as usize == *expected as usize)
11290                    .unwrap_or_else(|| {
11291                        panic!(
11292                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11293                             FROM the compare-where contract in global_bindings() \
11294                             — found {} alternative(s) with sources {:?}",
11295                            alts.len(),
11296                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11297                        )
11298                    });
11299                assert_eq!(
11300                    entry.kernel_source, "portable-cpu",
11301                    "{op:?}/{dt:?}: compare family must be contract-sourced \
11302                     (kernel_source=\"portable-cpu\"); got {:?}",
11303                    entry.kernel_source,
11304                );
11305                assert!(
11306                    !entry.caps.strided_input,
11307                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11308                );
11309                assert!(
11310                    entry.precision.bit_stable_on_same_hardware,
11311                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11312                );
11313                checked += 1;
11314            }
11315        }
11316
11317        // -- WHERE: 1 op × 4 dtypes, key [U8, T, T, T] (fan-out + passthrough(a)) --
11318        let where_wrappers: [crate::kernel::KernelRef; 4] = [
11319            where_f32_cpu_wrapper,
11320            where_f64_cpu_wrapper,
11321            where_bf16_cpu_wrapper,
11322            where_f16_cpu_wrapper,
11323        ];
11324        for (dt, expected) in dts.iter().zip(where_wrappers.iter()) {
11325            // Ternary-select list: [U8 cond, T a, T b, T out].
11326            let alts = table.lookup_alternatives(
11327                OpKind::Where,
11328                &[DType::Bool, *dt, *dt, *dt],
11329                BackendId::Cpu,
11330            );
11331            let entry = alts
11332                .iter()
11333                .find(|e| e.kernel as usize == *expected as usize)
11334                .unwrap_or_else(|| {
11335                    panic!(
11336                        "Where/{dt:?}/Cpu: the production wrapper must be bound FROM \
11337                         the compare-where contract (where fans to [U8,T,T,T]) in \
11338                         global_bindings() — found {} alternative(s) with sources {:?}",
11339                        alts.len(),
11340                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11341                    )
11342                });
11343            assert_eq!(
11344                entry.kernel_source, "portable-cpu",
11345                "Where/{dt:?}: where must be contract-sourced \
11346                 (kernel_source=\"portable-cpu\"); got {:?}",
11347                entry.kernel_source,
11348            );
11349            assert!(
11350                !entry.caps.strided_input,
11351                "Where/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11352            );
11353            checked += 1;
11354        }
11355
11356        assert_eq!(checked, 28, "24 compare (6×4) + 4 where keys checked");
11357    }
11358
11359    /// FKC production consumer (born-red gate). `global_bindings()` registers
11360    /// the CPU per-axis reduce family (Sum/Mean/Max/Min × F32/F64/BF16/F16 = 16)
11361    /// FROM ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md`) — the
11362    /// sole path now that the hand-written `table.register(...)` calls for this
11363    /// family are DELETED.
11364    ///
11365    /// The binding key is the `[T, T]` operand-dtype list (input +
11366    /// `passthrough(input)` output; the reduce axes + keepdim ride in
11367    /// `OpParams::Reduce`, NOT the dtype-list). Each per-(op,dtype) section
11368    /// carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan-out).
11369    ///
11370    /// For each key: resolves to the EXACT production wrapper fn-pointer and
11371    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11372    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11373    /// goes red until the import is wired) — with caps contiguous and the audited
11374    /// bit-stable precision riding through.
11375    #[test]
11376    fn global_bindings_registers_reduce_family_from_contract() {
11377        let table = global_bindings();
11378        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11379
11380        // Sum/Mean/Max/Min × {f32,f64,bf16,f16}, key [T, T].
11381        let reduce_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11382            (
11383                OpKind::SumReduce,
11384                [
11385                    sum_reduce_f32_cpu_wrapper,
11386                    sum_reduce_f64_cpu_wrapper,
11387                    sum_reduce_bf16_cpu_wrapper,
11388                    sum_reduce_f16_cpu_wrapper,
11389                ],
11390            ),
11391            (
11392                OpKind::MeanReduce,
11393                [
11394                    mean_reduce_f32_cpu_wrapper,
11395                    mean_reduce_f64_cpu_wrapper,
11396                    mean_reduce_bf16_cpu_wrapper,
11397                    mean_reduce_f16_cpu_wrapper,
11398                ],
11399            ),
11400            (
11401                OpKind::MaxReduce,
11402                [
11403                    max_reduce_f32_cpu_wrapper,
11404                    max_reduce_f64_cpu_wrapper,
11405                    max_reduce_bf16_cpu_wrapper,
11406                    max_reduce_f16_cpu_wrapper,
11407                ],
11408            ),
11409            (
11410                OpKind::MinReduce,
11411                [
11412                    min_reduce_f32_cpu_wrapper,
11413                    min_reduce_f64_cpu_wrapper,
11414                    min_reduce_bf16_cpu_wrapper,
11415                    min_reduce_f16_cpu_wrapper,
11416                ],
11417            ),
11418        ];
11419
11420        let mut checked = 0usize;
11421        for (op, wrappers) in reduce_families {
11422            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11423                // [T, T] operand-dtype list (input + passthrough output).
11424                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11425                let entry = alts
11426                    .iter()
11427                    .find(|e| e.kernel as usize == *expected as usize)
11428                    .unwrap_or_else(|| {
11429                        panic!(
11430                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11431                             FROM the reduce contract in global_bindings() \
11432                             — found {} alternative(s) with sources {:?}",
11433                            alts.len(),
11434                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11435                        )
11436                    });
11437                assert_eq!(
11438                    entry.kernel_source, "portable-cpu",
11439                    "{op:?}/{dt:?}: reduce family must be contract-sourced \
11440                     (kernel_source=\"portable-cpu\"); got {:?}",
11441                    entry.kernel_source,
11442                );
11443                assert!(
11444                    !entry.caps.strided_input,
11445                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11446                );
11447                assert!(
11448                    entry.precision.bit_stable_on_same_hardware,
11449                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11450                );
11451                checked += 1;
11452            }
11453        }
11454        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11455    }
11456
11457    /// Born-red guard for the CPU reduce-to family FKC migration. Mirrors the
11458    /// reduce-family test across the two key shapes this family carries:
11459    /// `ReduceSumTo` / `ReduceMaxTo` are single input → `passthrough` output,
11460    /// key `[T, T]`; `ReduceMaxToBackward` is two inputs (x, upstream) +
11461    /// `passthrough(x)` output, key `[T, T, T]`. Each × {f32,f64,bf16,f16}.
11462    ///
11463    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11464    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11465    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11466    /// goes red until the import is wired) — caps contiguous, and the audited
11467    /// bit-stable precision riding through.
11468    #[test]
11469    fn global_bindings_registers_reduce_to_family_from_contract() {
11470        let table = global_bindings();
11471        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11472
11473        // ReduceSumTo / ReduceMaxTo — single input + passthrough output, key [T, T].
11474        let unary_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11475            (
11476                OpKind::ReduceSumTo,
11477                [
11478                    reduce_sum_to_f32_cpu_wrapper,
11479                    reduce_sum_to_f64_cpu_wrapper,
11480                    reduce_sum_to_bf16_cpu_wrapper,
11481                    reduce_sum_to_f16_cpu_wrapper,
11482                ],
11483            ),
11484            (
11485                OpKind::ReduceMaxTo,
11486                [
11487                    reduce_max_to_f32_cpu_wrapper,
11488                    reduce_max_to_f64_cpu_wrapper,
11489                    reduce_max_to_bf16_cpu_wrapper,
11490                    reduce_max_to_f16_cpu_wrapper,
11491                ],
11492            ),
11493        ];
11494        // ReduceMaxToBackward — two inputs (x, upstream) + passthrough(x)
11495        // output, key [T, T, T].
11496        let backward_family: (OpKind, [crate::kernel::KernelRef; 4]) = (
11497            OpKind::ReduceMaxToBackward,
11498            [
11499                reduce_max_to_backward_f32_cpu_wrapper,
11500                reduce_max_to_backward_f64_cpu_wrapper,
11501                reduce_max_to_backward_bf16_cpu_wrapper,
11502                reduce_max_to_backward_f16_cpu_wrapper,
11503            ],
11504        );
11505
11506        // Assert one (op, key, expected-wrapper) is bound FROM the contract.
11507        let assert_contract_bound =
11508            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef| {
11509                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11510                let entry = alts
11511                    .iter()
11512                    .find(|e| e.kernel as usize == expected as usize)
11513                    .unwrap_or_else(|| {
11514                        panic!(
11515                            "{op:?}/{key:?}/Cpu: the production wrapper must be bound \
11516                             FROM the reduce-to contract in global_bindings() \
11517                             — found {} alternative(s) with sources {:?}",
11518                            alts.len(),
11519                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11520                        )
11521                    });
11522                assert_eq!(
11523                    entry.kernel_source, "portable-cpu",
11524                    "{op:?}/{key:?}: reduce-to family must be contract-sourced \
11525                     (kernel_source=\"portable-cpu\"); got {:?}",
11526                    entry.kernel_source,
11527                );
11528                assert!(
11529                    !entry.caps.strided_input,
11530                    "{op:?}/{key:?}: caps preserved (contiguous-only, strided_input=false)",
11531                );
11532                assert!(
11533                    entry.precision.bit_stable_on_same_hardware,
11534                    "{op:?}/{key:?}: the contract's audited bit-stable claim rode through",
11535                );
11536            };
11537
11538        let mut checked = 0usize;
11539        for (op, wrappers) in unary_families {
11540            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11541                assert_contract_bound(*op, &[*dt, *dt], *expected);
11542                checked += 1;
11543            }
11544        }
11545        let (op, wrappers) = backward_family;
11546        for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11547            assert_contract_bound(op, &[*dt, *dt, *dt], *expected);
11548            checked += 1;
11549        }
11550        assert_eq!(checked, 12, "3 ops × 4 dtypes checked");
11551    }
11552
11553    /// Born-red guard for the CPU last-dim NORM (forward) family FKC migration.
11554    /// Softmax / LogSoftmax / RmsNorm / LayerNorm are each a SINGLE input →
11555    /// `passthrough` output, key `[T, T]` — the RMS/LayerNorm kernels carry NO
11556    /// affine gamma/beta operand (bare normalization), and outer_count/last_dim/
11557    /// eps ride in `OpParams`, so the key stays `[T, T]` (not a 3- or 4-operand
11558    /// key). Each × {f32,f64,bf16,f16} = 16 bindings.
11559    ///
11560    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11561    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11562    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11563    /// goes red until the import is wired) — caps contiguous, and the audited
11564    /// bit-stable precision riding through.
11565    #[test]
11566    fn global_bindings_registers_norm_family_from_contract() {
11567        let table = global_bindings();
11568        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11569
11570        // Softmax / LogSoftmax / RmsNorm / LayerNorm — single input +
11571        // passthrough output, key [T, T]. Wrapper order matches `dts`.
11572        let norm_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11573            (
11574                OpKind::SoftmaxLastDim,
11575                [
11576                    softmax_last_dim_f32_cpu_wrapper,
11577                    softmax_last_dim_f64_cpu_wrapper,
11578                    softmax_last_dim_bf16_cpu_wrapper,
11579                    softmax_last_dim_f16_cpu_wrapper,
11580                ],
11581            ),
11582            (
11583                OpKind::LogSoftmaxLastDim,
11584                [
11585                    log_softmax_f32_cpu_wrapper,
11586                    log_softmax_f64_cpu_wrapper,
11587                    log_softmax_bf16_cpu_wrapper,
11588                    log_softmax_f16_cpu_wrapper,
11589                ],
11590            ),
11591            (
11592                OpKind::RmsNormLastDim,
11593                [
11594                    rms_norm_last_dim_f32_cpu_wrapper,
11595                    rms_norm_last_dim_f64_cpu_wrapper,
11596                    rms_norm_last_dim_bf16_cpu_wrapper,
11597                    rms_norm_last_dim_f16_cpu_wrapper,
11598                ],
11599            ),
11600            (
11601                OpKind::LayerNormLastDim,
11602                [
11603                    layer_norm_last_dim_f32_cpu_wrapper,
11604                    layer_norm_last_dim_f64_cpu_wrapper,
11605                    layer_norm_last_dim_bf16_cpu_wrapper,
11606                    layer_norm_last_dim_f16_cpu_wrapper,
11607                ],
11608            ),
11609        ];
11610
11611        let mut checked = 0usize;
11612        for (op, wrappers) in norm_families {
11613            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11614                // [T, T] operand-dtype list (input + passthrough output).
11615                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11616                let entry = alts
11617                    .iter()
11618                    .find(|e| e.kernel as usize == *expected as usize)
11619                    .unwrap_or_else(|| {
11620                        panic!(
11621                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11622                             FROM the norm contract in global_bindings() \
11623                             — found {} alternative(s) with sources {:?}",
11624                            alts.len(),
11625                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11626                        )
11627                    });
11628                assert_eq!(
11629                    entry.kernel_source, "portable-cpu",
11630                    "{op:?}/{dt:?}: norm family must be contract-sourced \
11631                     (kernel_source=\"portable-cpu\"); got {:?}",
11632                    entry.kernel_source,
11633                );
11634                assert!(
11635                    !entry.caps.strided_input,
11636                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11637                );
11638                assert!(
11639                    entry.precision.bit_stable_on_same_hardware,
11640                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11641                );
11642                checked += 1;
11643            }
11644        }
11645        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11646    }
11647
11648    /// Born-red guard for the CPU last-dim NORM-BACKWARD family FKC migration.
11649    /// Softmax / LogSoftmax / LayerNorm / RmsNorm backward are each TWO inputs
11650    /// (the forward output-or-input `y`/`x` + the upstream gradient `g`) → ONE
11651    /// `passthrough` output — the BARE backward (no affine gamma/beta grad
11652    /// operand and no saved-stats operand; the norm kernels recompute mean/var
11653    /// or mean-square from `x` + `eps`), so the binding key is `[T, T, T]`
11654    /// (in, in, out) and outer_count / last_dim / eps ride in `OpParams`, NOT
11655    /// the dtype-list. Each × {f32,f64,bf16,f16} = 16 bindings.
11656    ///
11657    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11658    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11659    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11660    /// goes red until the import is wired) — caps contiguous, and the audited
11661    /// bit-stable precision riding through.
11662    #[test]
11663    fn global_bindings_registers_norm_backward_family_from_contract() {
11664        let table = global_bindings();
11665        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11666
11667        // Softmax / LogSoftmax / LayerNorm / RmsNorm backward — two inputs
11668        // (y/x, g) + passthrough output, key [T, T, T]. Wrapper order matches
11669        // `dts`. (LogSoftmax's wrapper fn-name `log_softmax_backward_*` differs
11670        // from its `log_softmax_last_dim_backward_*` contract symbol — the same
11671        // fn-vs-symbol split as the forward `log_softmax` case.)
11672        let backward_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11673            (
11674                OpKind::SoftmaxLastDimBackward,
11675                [
11676                    softmax_last_dim_backward_f32_cpu_wrapper,
11677                    softmax_last_dim_backward_f64_cpu_wrapper,
11678                    softmax_last_dim_backward_bf16_cpu_wrapper,
11679                    softmax_last_dim_backward_f16_cpu_wrapper,
11680                ],
11681            ),
11682            (
11683                OpKind::LogSoftmaxLastDimBackward,
11684                [
11685                    log_softmax_backward_f32_cpu_wrapper,
11686                    log_softmax_backward_f64_cpu_wrapper,
11687                    log_softmax_backward_bf16_cpu_wrapper,
11688                    log_softmax_backward_f16_cpu_wrapper,
11689                ],
11690            ),
11691            (
11692                OpKind::LayerNormLastDimBackward,
11693                [
11694                    layer_norm_last_dim_backward_f32_cpu_wrapper,
11695                    layer_norm_last_dim_backward_f64_cpu_wrapper,
11696                    layer_norm_last_dim_backward_bf16_cpu_wrapper,
11697                    layer_norm_last_dim_backward_f16_cpu_wrapper,
11698                ],
11699            ),
11700            (
11701                OpKind::RmsNormLastDimBackward,
11702                [
11703                    rms_norm_last_dim_backward_f32_cpu_wrapper,
11704                    rms_norm_last_dim_backward_f64_cpu_wrapper,
11705                    rms_norm_last_dim_backward_bf16_cpu_wrapper,
11706                    rms_norm_last_dim_backward_f16_cpu_wrapper,
11707                ],
11708            ),
11709        ];
11710
11711        let mut checked = 0usize;
11712        for (op, wrappers) in backward_families {
11713            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11714                // [T, T, T] operand-dtype list (two inputs + passthrough output).
11715                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
11716                let entry = alts
11717                    .iter()
11718                    .find(|e| e.kernel as usize == *expected as usize)
11719                    .unwrap_or_else(|| {
11720                        panic!(
11721                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11722                             FROM the norm-backward contract in global_bindings() \
11723                             — found {} alternative(s) with sources {:?}",
11724                            alts.len(),
11725                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11726                        )
11727                    });
11728                assert_eq!(
11729                    entry.kernel_source, "portable-cpu",
11730                    "{op:?}/{dt:?}: norm-backward family must be contract-sourced \
11731                     (kernel_source=\"portable-cpu\"); got {:?}",
11732                    entry.kernel_source,
11733                );
11734                assert!(
11735                    !entry.caps.strided_input,
11736                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11737                );
11738                assert!(
11739                    entry.precision.bit_stable_on_same_hardware,
11740                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11741                );
11742                checked += 1;
11743            }
11744        }
11745        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11746    }
11747
11748    /// RoPE (rotary position embedding) is ONE primitive op (`OpKind::Rope`)
11749    /// monomorphized over the four float dtypes {F32, F64, BF16, F16}. Each
11750    /// dtype is a distinct single-dtype contract section (`## rope_f32`, …) with
11751    /// a concrete `entry_point` (`fuel_cpu_backend::byte_kernels::rope_f32`), so
11752    /// none of them fan — the importer resolves each declared symbol AS-IS. RoPE
11753    /// takes THREE inputs (`x` + the precomputed `cos`/`sin` tables, all one
11754    /// dtype; the tables broadcast over the outer axis by re-indexing, NOT a
11755    /// stride-0 view) and writes ONE `passthrough(x)` output, so the binding key
11756    /// is `[T, T, T, T]` (x, cos, sin, out); outer_count / seq / head_dim ride in
11757    /// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
11758    /// `rope_dts(t)` regs.
11759    ///
11760    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11761    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11762    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11763    /// goes red until the import is wired) — caps contiguous, and the audited
11764    /// bit-stable precision riding through.
11765    #[test]
11766    fn global_bindings_registers_rope_family_from_contract() {
11767        let table = global_bindings();
11768        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11769        // Wrapper order matches `dts`.
11770        let expected_wrappers: [crate::kernel::KernelRef; 4] = [
11771            rope_f32_cpu_wrapper,
11772            rope_f64_cpu_wrapper,
11773            rope_bf16_cpu_wrapper,
11774            rope_f16_cpu_wrapper,
11775        ];
11776
11777        let mut checked = 0usize;
11778        for (dt, expected) in dts.iter().zip(expected_wrappers.iter()) {
11779            // [T, T, T, T] operand-dtype list (x, cos, sin + passthrough output).
11780            let alts =
11781                table.lookup_alternatives(OpKind::Rope, &[*dt, *dt, *dt, *dt], BackendId::Cpu);
11782            let entry = alts
11783                .iter()
11784                .find(|e| e.kernel as usize == *expected as usize)
11785                .unwrap_or_else(|| {
11786                    panic!(
11787                        "Rope/{dt:?}/Cpu: the production wrapper must be bound \
11788                         FROM the rope contract in global_bindings() \
11789                         — found {} alternative(s) with sources {:?}",
11790                        alts.len(),
11791                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11792                    )
11793                });
11794            assert_eq!(
11795                entry.kernel_source, "portable-cpu",
11796                "Rope/{dt:?}: rope family must be contract-sourced \
11797                 (kernel_source=\"portable-cpu\"); got {:?}",
11798                entry.kernel_source,
11799            );
11800            assert!(
11801                !entry.caps.strided_input,
11802                "Rope/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11803            );
11804            assert!(
11805                entry.precision.bit_stable_on_same_hardware,
11806                "Rope/{dt:?}: the contract's audited bit-stable claim rode through",
11807            );
11808            checked += 1;
11809        }
11810        assert_eq!(checked, 4, "1 op × 4 dtypes checked");
11811    }
11812
11813    /// Gate for the CPU SSM / Mamba family FULLY migrated to FKC-contract
11814    /// registration. The WHOLE family — FusedSoftmaxCrossEntropy (key
11815    /// `[T, I64, F32]` — logits T + I64 targets → fixed(F32) output),
11816    /// CausalConv1d (key `[T, T, T, T]` — x, weight, bias + passthrough(x)
11817    /// output), and the two SCAN ops SelectiveScan / SsdChunkScan (key `[T; 6]`
11818    /// — 5 inputs + the ONE bundled output slot), 4 ops × 4 dtypes = 16
11819    /// bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md`.
11820    ///
11821    /// The scans' `[T; 6]` keys are now contract-sourced too: their sections
11822    /// return a `return.bundle` multi-output (Option C, one buffer
11823    /// `[y ; last_state]`), and the importer's key-builder appends the bundle's
11824    /// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key
11825    /// tail — byte-for-byte the deleted hand-written `&[dt; 6]` regs.
11826    ///
11827    /// For each of the 16 keys: resolves to the EXACT production wrapper
11828    /// fn-pointer with `kernel_source == "portable-cpu"` (the contract
11829    /// provenance tag; the deleted hand-written path stamped `""`), caps
11830    /// contiguous, and the contract's bit-stable precision riding through.
11831    #[test]
11832    fn global_bindings_registers_ssm_family_from_contract() {
11833        let table = global_bindings();
11834        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11835
11836        // Assert one (op, key) binds `expected` FROM the contract (portable-cpu,
11837        // contiguous caps, bit-stable precision). `key` is the full binding key.
11838        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11839            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11840            let entry = alts
11841                .iter()
11842                .find(|e| e.kernel as usize == expected as usize)
11843                .unwrap_or_else(|| {
11844                    panic!(
11845                        "{label}/Cpu (key {key:?}): the production wrapper must be bound \
11846                         FROM the ssm contract in global_bindings() — found {} \
11847                         alternative(s) with sources {:?}",
11848                        alts.len(),
11849                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11850                    )
11851                });
11852            assert_eq!(
11853                entry.kernel_source, "portable-cpu",
11854                "{label}: family must be contract-sourced (kernel_source=\"portable-cpu\"); \
11855                 got {:?}",
11856                entry.kernel_source,
11857            );
11858            assert!(
11859                !entry.caps.strided_input,
11860                "{label}: caps preserved (contiguous-only)"
11861            );
11862            assert!(
11863                entry.precision.bit_stable_on_same_hardware,
11864                "{label}: contract's bit-stable claim rode through",
11865            );
11866        };
11867
11868        // Per-op wrappers, indexed to match `dts` order.
11869        let fsce: [crate::kernel::KernelRef; 4] = [
11870            fused_softmax_cross_entropy_f32_cpu_wrapper,
11871            fused_softmax_cross_entropy_f64_cpu_wrapper,
11872            fused_softmax_cross_entropy_bf16_cpu_wrapper,
11873            fused_softmax_cross_entropy_f16_cpu_wrapper,
11874        ];
11875        let conv: [crate::kernel::KernelRef; 4] = [
11876            causal_conv1d_f32_cpu_wrapper,
11877            causal_conv1d_f64_cpu_wrapper,
11878            causal_conv1d_bf16_cpu_wrapper,
11879            causal_conv1d_f16_cpu_wrapper,
11880        ];
11881        let sscan: [crate::kernel::KernelRef; 4] = [
11882            selective_scan_f32_cpu_wrapper,
11883            selective_scan_f64_cpu_wrapper,
11884            selective_scan_bf16_cpu_wrapper,
11885            selective_scan_f16_cpu_wrapper,
11886        ];
11887        let ssd: [crate::kernel::KernelRef; 4] = [
11888            ssd_chunk_scan_f32_cpu_wrapper,
11889            ssd_chunk_scan_f64_cpu_wrapper,
11890            ssd_chunk_scan_bf16_cpu_wrapper,
11891            ssd_chunk_scan_f16_cpu_wrapper,
11892        ];
11893
11894        let mut checked = 0usize;
11895        for (i, dt) in dts.iter().enumerate() {
11896            // FSCE: [logits T, targets I64, out F32].
11897            check(
11898                OpKind::FusedSoftmaxCrossEntropy,
11899                &[*dt, DType::I64, DType::F32],
11900                fsce[i],
11901                "FusedSoftmaxCrossEntropy",
11902            );
11903            // CausalConv1d: [x, weight, bias, out] all T.
11904            check(OpKind::CausalConv1d, &[*dt; 4], conv[i], "CausalConv1d");
11905            // SelectiveScan: [u, delta, a, b, c, out] = [T; 6] (5 inputs + the
11906            // ONE bundled output slot, `passthrough(u)` → T).
11907            check(OpKind::SelectiveScan, &[*dt; 6], sscan[i], "SelectiveScan");
11908            // SsdChunkScan: [x, dt, a, b, c, out] = [T; 6] (5 inputs + the ONE
11909            // bundled output slot, `passthrough(x)` → T).
11910            check(OpKind::SsdChunkScan, &[*dt; 6], ssd[i], "SsdChunkScan");
11911
11912            checked += 1;
11913        }
11914        assert_eq!(
11915            checked, 4,
11916            "4 ops × 4 dtypes checked (16 contract-sourced bindings)"
11917        );
11918    }
11919
11920    /// Gate for the CPU conv family FULLY migrated to FKC-contract registration.
11921    /// The whole family — BOTH the no-bias keys (`[T, T, T]` — x, weight + out)
11922    /// AND the with-bias keys (`[T, T, T, T]` — x, weight, bias + passthrough(x)
11923    /// output) of Conv2D and ConvTranspose2D, 2 ops × 4 dtypes × 2 operand-counts
11924    /// = 16 bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/conv.fkc.md`.
11925    ///
11926    /// The no-bias keys are now contract-sourced too: the conv contract declares
11927    /// `bias` as `optional: true`, and the importer's key-builder
11928    /// (`fkc/lower.rs` `assemble_dtype_variants`) now fans an optional LAST input
11929    /// into BOTH the with- and without-operand keys, both resolving the SAME
11930    /// wrapper. The former hand-written no-bias `table.register(...)` regs are
11931    /// DELETED (deferral closed).
11932    ///
11933    /// For each of the 16 keys: resolves to the EXACT production wrapper
11934    /// fn-pointer with `kernel_source == "portable-cpu"` — the contract
11935    /// provenance tag — caps contiguous, and the contract's bit-stable precision
11936    /// riding through.
11937    #[test]
11938    fn global_bindings_registers_conv_family_from_contract() {
11939        let table = global_bindings();
11940        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11941
11942        // Conv2D wrappers (order matches `dts`); the same wrapper serves both the
11943        // no-bias [x, weight, out] and with-bias [x, weight, bias, out] keys.
11944        let conv2d_wrappers: [crate::kernel::KernelRef; 4] = [
11945            conv2d_f32_cpu_wrapper,
11946            conv2d_f64_cpu_wrapper,
11947            conv2d_bf16_cpu_wrapper,
11948            conv2d_f16_cpu_wrapper,
11949        ];
11950        // ConvTranspose2D wrappers (order matches `dts`).
11951        let convt_wrappers: [crate::kernel::KernelRef; 4] = [
11952            conv_transpose2d_f32_cpu_wrapper,
11953            conv_transpose2d_f64_cpu_wrapper,
11954            conv_transpose2d_bf16_cpu_wrapper,
11955            conv_transpose2d_f16_cpu_wrapper,
11956        ];
11957
11958        let mut checked = 0usize;
11959        for (i, dt) in dts.iter().enumerate() {
11960            for (op, expected) in [
11961                (OpKind::Conv2D, conv2d_wrappers[i]),
11962                (OpKind::ConvTranspose2D, convt_wrappers[i]),
11963            ] {
11964                // BOTH operand-count keys: no-bias [x, weight, out] AND with-bias
11965                // [x, weight, bias, out] — all T, both bound to the SAME wrapper
11966                // from the contract's optional-operand fan.
11967                let no_bias: &[DType] = &[*dt, *dt, *dt];
11968                let with_bias: &[DType] = &[*dt, *dt, *dt, *dt];
11969                for (key, label) in [(no_bias, "no-bias"), (with_bias, "with-bias")] {
11970                    let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11971                    let entry = alts
11972                        .iter()
11973                        .find(|e| e.kernel as usize == expected as usize)
11974                        .unwrap_or_else(|| {
11975                            panic!(
11976                                "{op:?}/{dt:?}/Cpu ({label}): the production wrapper must be \
11977                                 bound FROM the conv contract in global_bindings() — found {} \
11978                                 alternative(s) with sources {:?}",
11979                                alts.len(),
11980                                alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11981                            )
11982                        });
11983                    assert_eq!(
11984                        entry.kernel_source, "portable-cpu",
11985                        "{op:?}/{dt:?} ({label}): family must be contract-sourced \
11986                         (kernel_source=\"portable-cpu\"); got {:?}",
11987                        entry.kernel_source,
11988                    );
11989                    assert!(
11990                        !entry.caps.strided_input,
11991                        "{op:?}/{dt:?} ({label}): caps preserved (contiguous-only)",
11992                    );
11993                    assert!(
11994                        entry.precision.bit_stable_on_same_hardware,
11995                        "{op:?}/{dt:?} ({label}): contract's bit-stable claim rode through",
11996                    );
11997                    checked += 1;
11998                }
11999            }
12000        }
12001        assert_eq!(
12002            checked, 16,
12003            "2 ops × 4 dtypes × 2 operand-counts checked (16 contract-sourced bindings)"
12004        );
12005    }
12006
12007    /// Gate for the CPU **padding** family's BACKWARD half migrated to
12008    /// FKC-contract registration. The four `PadBackward` per-dtype kernels
12009    /// (key `[T, T]` — grad_out + `passthrough(grad_out)` grad_in, T ∈
12010    /// {F32,F64,BF16,F16}) are IMPORTED from
12011    /// `fuel-dispatch/kernel-contracts/cpu/padding.fkc.md` — the `pad_backward_<dt>`
12012    /// single-dtype sections, each resolved AS-IS (no dtype fan-out) through the
12013    /// production `CpuLinkRegistry` (chaining `CPU_PADDING_ENTRY_POINTS`).
12014    ///
12015    /// The FORWARD `Pad` half (Constant/Reflect/Replicate) is ALSO migrated:
12016    /// the three runtime modes collapse to ONE mode-unified `(Pad, [T, T])`
12017    /// binding per dtype served by the single dtype-agnostic `pad_cpu_wrapper`
12018    /// (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
12019    /// section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
12020    /// resolving `pad_cpu_wrapper` (the fabricated `pad_cpu_<dt>` symbol → the one
12021    /// wrapper, like Flip/Roll/Concat); the three per-mode sections
12022    /// (`pad_const_cpu`/`pad_reflect_cpu`/`pad_replicate_cpu`) and the
12023    /// `pad_walk_cpu` helper stay `registrable: false` describe-only mode docs.
12024    /// See `register_cpu_padding_from_contract`.
12025    ///
12026    /// For each of the 4 backward + 6 forward keys: resolves to the EXACT
12027    /// production wrapper with `kernel_source == "portable-cpu"` (the contract
12028    /// provenance tag), caps contiguous, and the contract's bit-stable precision
12029    /// riding through.
12030    #[test]
12031    fn global_bindings_registers_padding_family_from_contract() {
12032        let table = global_bindings();
12033        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12034        // PadBackward wrappers, indexed to match `dts` order.
12035        let pad_backward: [crate::kernel::KernelRef; 4] = [
12036            pad_backward_f32_cpu_wrapper,
12037            pad_backward_f64_cpu_wrapper,
12038            pad_backward_bf16_cpu_wrapper,
12039            pad_backward_f16_cpu_wrapper,
12040        ];
12041
12042        let mut checked = 0usize;
12043        for (i, dt) in dts.iter().enumerate() {
12044            // PadBackward: [grad_out T, grad_in T] = [T, T] (passthrough(grad_out)).
12045            let key: &[DType] = &[*dt, *dt];
12046            let expected = pad_backward[i];
12047            let alts = table.lookup_alternatives(OpKind::PadBackward, key, BackendId::Cpu);
12048            let entry = alts
12049                .iter()
12050                .find(|e| e.kernel as usize == expected as usize)
12051                .unwrap_or_else(|| {
12052                    panic!(
12053                        "PadBackward/{dt:?}/Cpu: the production wrapper must be bound \
12054                         FROM the padding contract in global_bindings() — found {} \
12055                         alternative(s) with sources {:?}",
12056                        alts.len(),
12057                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12058                    )
12059                });
12060            assert_eq!(
12061                entry.kernel_source, "portable-cpu",
12062                "PadBackward/{dt:?}: family must be contract-sourced \
12063                 (kernel_source=\"portable-cpu\"); got {:?}",
12064                entry.kernel_source,
12065            );
12066            assert!(
12067                !entry.caps.strided_input,
12068                "PadBackward/{dt:?}: caps preserved (contiguous-only)",
12069            );
12070            assert!(
12071                entry.precision.bit_stable_on_same_hardware,
12072                "PadBackward/{dt:?}: contract's bit-stable claim rode through",
12073            );
12074            checked += 1;
12075        }
12076
12077        // Forward Pad (Constant/Reflect/Replicate) — ONE mode-unified `(Pad, [T, T])`
12078        // binding per dtype served by the SINGLE dtype-agnostic `pad_cpu_wrapper`
12079        // (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
12080        // section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
12081        // resolving `pad_cpu_wrapper` (fabricated `pad_cpu_<dt>` symbol → the one
12082        // wrapper, like Flip/Roll/Concat). in_shape/out_shape/padding/mode_tag/
12083        // fill_bytes ride in OpParams::Pad, NOT the dtype-list.
12084        let pad_forward_dts = [
12085            DType::U8,
12086            DType::U32,
12087            DType::BF16,
12088            DType::F16,
12089            DType::F32,
12090            DType::F64,
12091        ];
12092        for dt in pad_forward_dts {
12093            let key: &[DType] = &[dt, dt];
12094            let alts = table.lookup_alternatives(OpKind::Pad, key, BackendId::Cpu);
12095            let entry = alts
12096                .iter()
12097                .find(|e| e.kernel as usize == pad_cpu_wrapper as *const () as usize)
12098                .unwrap_or_else(|| {
12099                    panic!(
12100                        "Pad/{dt:?}/Cpu: the production wrapper must be bound \
12101                         FROM the padding contract in global_bindings() — found {} \
12102                         alternative(s) with sources {:?}",
12103                        alts.len(),
12104                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12105                    )
12106                });
12107            assert_eq!(
12108                entry.kernel_source, "portable-cpu",
12109                "Pad/{dt:?}: forward family must be contract-sourced \
12110                 (kernel_source=\"portable-cpu\"); got {:?}",
12111                entry.kernel_source,
12112            );
12113            assert!(
12114                !entry.caps.strided_input,
12115                "Pad/{dt:?}: caps preserved (contiguous-only)",
12116            );
12117            assert!(
12118                entry.precision.bit_stable_on_same_hardware,
12119                "Pad/{dt:?}: contract's bit-stable claim rode through",
12120            );
12121            checked += 1;
12122        }
12123
12124        assert_eq!(
12125            checked, 10,
12126            "4 PadBackward + 6 forward Pad dtypes checked (contract-sourced bindings)"
12127        );
12128    }
12129
12130    /// Gate for the CPU **shape-ops** family's migratable subset moved to
12131    /// FKC-contract registration. IMPORTED from
12132    /// `fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md` via the production
12133    /// `CpuLinkRegistry` (chaining `CPU_SHAPE_OPS_ENTRY_POINTS`):
12134    /// - **Flip** / **Roll** — dtype-agnostic byte reorder, key `[T, T]`, one
12135    ///   `flip_cpu_wrapper` / `roll_cpu_wrapper` per dtype (fan over the 6
12136    ///   production dtypes F32/F64/BF16/F16/U32/U8; the contract's dtype list is
12137    ///   trimmed to match production, NOT the kernel's full byte-agnostic set).
12138    /// - **CumSum** — per-dtype typed accumulation (f32/f64 native, bf16/f16 with
12139    ///   an f32 accumulator), key `[T, T]`, its SPECIFIC `cumsum_<dt>` symbol
12140    ///   resolved AS-IS (no fan), 4 dtypes.
12141    /// - **MaskedFill** — dtype-agnostic data + U8 mask, key `[T, U8, T]`, one
12142    ///   `masked_fill_cpu_wrapper` per dtype (fan over the same 6 dtypes).
12143    /// - **Concat** — variadic uniform-dtype join collapsed to the `[T, T]`
12144    ///   shorthand key, one `concat_cpu_wrapper` per dtype (fan over the 9
12145    ///   production dtypes F32/F64/BF16/F16/U32/U8/I16/I32/I64).
12146    /// - **WriteSlice** / **WriteSliceRotating** — in-place rectangular / ring
12147    ///   scatter, key `[T, T]`, one dtype-agnostic wrapper each (fan over the same
12148    ///   6 dtypes). `dest` is the in-place OUTPUT slot (not a key input); for the
12149    ///   rotating op the U32 `position` is a NON-KEY runtime operand — so the
12150    ///   contract's source-only + `out: passthrough(source)` section keys
12151    ///   `[T_source, T_out]` = `[T, T]`, matching `build_lookup_dtypes` exactly.
12152    ///
12153    /// DEFERRED (hand-written / describe-only, NOT checked here): `Contiguize`
12154    /// (no `OpKind` — an executor materialize pass) and `Triu`/`Tril` (the contract
12155    /// carries only the `triangular` chassis umbrella, `registrable: false`, not
12156    /// two per-OpKind sections). See `register_cpu_shape_ops_from_contract`.
12157    ///
12158    /// For each migrated key: resolves to the EXACT production wrapper with
12159    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12160    /// contiguous, and the contract's bit-stable precision riding through.
12161    #[test]
12162    fn global_bindings_registers_shape_ops_family_from_contract() {
12163        let table = global_bindings();
12164        let mut checked = 0usize;
12165
12166        // Assert a (op, key) resolves to `expected` with the contract provenance.
12167        let mut check =
12168            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12169                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12170                let entry = alts
12171                    .iter()
12172                    .find(|e| e.kernel as usize == expected as usize)
12173                    .unwrap_or_else(|| {
12174                        panic!(
12175                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
12176                         FROM the shape-ops contract in global_bindings() — found {} \
12177                         alternative(s) with sources {:?}",
12178                            alts.len(),
12179                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12180                        )
12181                    });
12182                assert_eq!(
12183                    entry.kernel_source, "portable-cpu",
12184                    "{op:?}/{label}: family must be contract-sourced \
12185                 (kernel_source=\"portable-cpu\"); got {:?}",
12186                    entry.kernel_source,
12187                );
12188                assert!(
12189                    !entry.caps.strided_input,
12190                    "{op:?}/{label}: caps preserved (contiguous-only)",
12191                );
12192                assert!(
12193                    entry.precision.bit_stable_on_same_hardware,
12194                    "{op:?}/{label}: contract's bit-stable claim rode through",
12195                );
12196                checked += 1;
12197            };
12198
12199        // Flip / Roll — key [T, T], one dtype-agnostic wrapper fanned per dtype.
12200        let byte_dts = [
12201            DType::F32,
12202            DType::F64,
12203            DType::BF16,
12204            DType::F16,
12205            DType::U32,
12206            DType::U8,
12207        ];
12208        for dt in byte_dts {
12209            check(OpKind::Flip, &[dt, dt], flip_cpu_wrapper, "flip");
12210            check(OpKind::Roll, &[dt, dt], roll_cpu_wrapper, "roll");
12211            // MaskedFill — key [T, U8, T].
12212            check(
12213                OpKind::MaskedFill,
12214                &[dt, DType::Bool, dt], // GAP-168(c): mask slot is Bool; the outer dt list is DATA dtypes
12215                masked_fill_cpu_wrapper,
12216                "masked_fill",
12217            );
12218        }
12219
12220        // CumSum — per-dtype typed wrappers, key [T, T], resolved AS-IS.
12221        let cumsum_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12222        let cumsum_wrappers: [crate::kernel::KernelRef; 4] = [
12223            cumsum_f32_cpu_wrapper,
12224            cumsum_f64_cpu_wrapper,
12225            cumsum_bf16_cpu_wrapper,
12226            cumsum_f16_cpu_wrapper,
12227        ];
12228        for (i, dt) in cumsum_dts.iter().enumerate() {
12229            check(OpKind::CumSum, &[*dt, *dt], cumsum_wrappers[i], "cumsum");
12230        }
12231
12232        // Concat — variadic uniform-dtype collapsed to [T, T], 9 dtypes.
12233        let concat_dts = [
12234            DType::F32,
12235            DType::F64,
12236            DType::BF16,
12237            DType::F16,
12238            DType::U32,
12239            DType::U8,
12240            DType::I16,
12241            DType::I32,
12242            DType::I64,
12243        ];
12244        for dt in concat_dts {
12245            check(OpKind::Concat, &[dt, dt], concat_cpu_wrapper, "concat");
12246        }
12247
12248        // WriteSlice / WriteSliceRotating — in-place rectangular / ring-buffer
12249        // scatter, key [T, T] (dest IS the output slot via in-place adoption;
12250        // WriteSliceRotating's `position` is a NON-KEY runtime U32 operand — see
12251        // `build_lookup_dtypes`). One dtype-agnostic wrapper each, fanned over the
12252        // 6 production dtypes (F32/F64/BF16/F16/U32/U8). The offset/modulus/axis/
12253        // ranges ride in OpParams::{WriteSlice,WriteSliceRotating}.
12254        let scatter_dts = [
12255            DType::F32,
12256            DType::F64,
12257            DType::BF16,
12258            DType::F16,
12259            DType::U32,
12260            DType::U8,
12261        ];
12262        for dt in scatter_dts {
12263            check(
12264                OpKind::WriteSlice,
12265                &[dt, dt],
12266                write_slice_cpu_wrapper,
12267                "write_slice",
12268            );
12269            check(
12270                OpKind::WriteSliceRotating,
12271                &[dt, dt],
12272                write_slice_rotating_cpu_wrapper,
12273                "write_slice_rotating",
12274            );
12275            // WriteSliceDoff — like WriteSliceRotating but the runtime operand is a
12276            // NON-KEY I64 `offset` (device-resident under CUDA), no wrap.
12277            check(
12278                OpKind::WriteSliceDoff,
12279                &[dt, dt],
12280                write_slice_doff_cpu_wrapper,
12281                "write_slice_doff",
12282            );
12283        }
12284
12285        assert_eq!(
12286            checked,
12287            6 + 6 + 6 + 4 + 9 + 6 + 6 + 6,
12288            "flip(6) + roll(6) + masked_fill(6) + cumsum(4) + concat(9) + \
12289             write_slice(6) + write_slice_rotating(6) + write_slice_doff(6) contract-sourced bindings",
12290        );
12291    }
12292
12293    /// Gate for the CPU **indexing / gather / scatter** family moved to
12294    /// FKC-contract registration. IMPORTED from
12295    /// `fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md` via the production
12296    /// `CpuLinkRegistry` (chaining `CPU_INDEXING_ENTRY_POINTS`):
12297    /// - **IndexSelect** / **Gather** — dtype-agnostic byte copy, key
12298    ///   `[T, U32, T]` (`source`, fixed-U32 `indices`, `passthrough(source)`
12299    ///   output). One `index_select_cpu_wrapper` / `gather_cpu_wrapper` per dtype
12300    ///   (the contract's ONE section declares a BASE `entry_point`
12301    ///   (`…::index_select_cpu` / `…::gather_cpu`) fanned over its dtype list, the
12302    ///   fabricated `<base>_<dt>` symbol resolving to the ONE wrapper — the
12303    ///   pad/flip umbrella precedent). The contract's dtype list is trimmed to
12304    ///   production's 9 wired dtypes (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is
12305    ///   describable (byte-agnostic) but NOT wired in production, so it is dropped
12306    ///   from the contract, NOT the kernel's full byte-agnostic set.
12307    /// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
12308    ///   native, bf16/f16 via an f32 accumulator; out seeded from `base` then
12309    ///   `+= src`), key `[T, U32, T, T]` (`base`, fixed-U32 `indices`, `src`,
12310    ///   `passthrough(base)` output). Each `index_add_<dt>` / `scatter_add_<dt>`
12311    ///   section carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no
12312    ///   fan), 4 dtypes each, mapping to its OWN typed wrapper.
12313    ///
12314    /// The `indices` operand is a FIXED single-dtype (U32) slot in every section
12315    /// (like compare's U8 mask / paged's U32 block-table), so there is NO
12316    /// independent index-dtype axis and no multi-axis `FanoutDtypeMismatch`
12317    /// deferral — the whole family migrates.
12318    ///
12319    /// For each migrated key: resolves to the EXACT production wrapper with
12320    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12321    /// contiguous, and the contract's bit-stable precision riding through.
12322    #[test]
12323    fn global_bindings_registers_indexing_family_from_contract() {
12324        let table = global_bindings();
12325        let mut checked = 0usize;
12326
12327        // Assert a (op, key) resolves to `expected` with the contract provenance.
12328        let mut check =
12329            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12330                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12331                let entry = alts
12332                    .iter()
12333                    .find(|e| e.kernel as usize == expected as usize)
12334                    .unwrap_or_else(|| {
12335                        panic!(
12336                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
12337                         FROM the indexing contract in global_bindings() — found {} \
12338                         alternative(s) with sources {:?}",
12339                            alts.len(),
12340                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12341                        )
12342                    });
12343                assert_eq!(
12344                    entry.kernel_source, "portable-cpu",
12345                    "{op:?}/{label}: family must be contract-sourced \
12346                 (kernel_source=\"portable-cpu\"); got {:?}",
12347                    entry.kernel_source,
12348                );
12349                assert!(
12350                    !entry.caps.strided_input,
12351                    "{op:?}/{label}: caps preserved (contiguous-only)",
12352                );
12353                assert!(
12354                    entry.precision.bit_stable_on_same_hardware,
12355                    "{op:?}/{label}: contract's bit-stable claim rode through",
12356                );
12357                checked += 1;
12358            };
12359
12360        // IndexSelect / Gather — dtype-agnostic byte copy, key [T, U32, T], one
12361        // wrapper fanned per dtype (9 production dtypes; I8 trimmed).
12362        let byte_dts = [
12363            DType::F32,
12364            DType::F64,
12365            DType::BF16,
12366            DType::F16,
12367            DType::U32,
12368            DType::U8,
12369            DType::I16,
12370            DType::I32,
12371            DType::I64,
12372        ];
12373        for dt in byte_dts {
12374            check(
12375                OpKind::IndexSelect,
12376                &[dt, DType::U32, dt],
12377                index_select_cpu_wrapper,
12378                "index_select",
12379            );
12380            check(
12381                OpKind::Gather,
12382                &[dt, DType::U32, dt],
12383                gather_cpu_wrapper,
12384                "gather",
12385            );
12386        }
12387
12388        // IndexAdd / ScatterAdd — per-dtype typed accumulation, key
12389        // [T, U32, T, T], each `<op>_<dt>` symbol resolved AS-IS (no fan).
12390        let acc_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12391        let index_add_wrappers: [crate::kernel::KernelRef; 4] = [
12392            index_add_f32_cpu_wrapper,
12393            index_add_f64_cpu_wrapper,
12394            index_add_bf16_cpu_wrapper,
12395            index_add_f16_cpu_wrapper,
12396        ];
12397        let scatter_add_wrappers: [crate::kernel::KernelRef; 4] = [
12398            scatter_add_f32_cpu_wrapper,
12399            scatter_add_f64_cpu_wrapper,
12400            scatter_add_bf16_cpu_wrapper,
12401            scatter_add_f16_cpu_wrapper,
12402        ];
12403        for (i, dt) in acc_dts.iter().enumerate() {
12404            check(
12405                OpKind::IndexAdd,
12406                &[*dt, DType::U32, *dt, *dt],
12407                index_add_wrappers[i],
12408                "index_add",
12409            );
12410            check(
12411                OpKind::ScatterAdd,
12412                &[*dt, DType::U32, *dt, *dt],
12413                scatter_add_wrappers[i],
12414                "scatter_add",
12415            );
12416        }
12417
12418        assert_eq!(
12419            checked,
12420            9 + 9 + 4 + 4,
12421            "index_select(9) + gather(9) + index_add(4) + scatter_add(4) \
12422             contract-sourced bindings",
12423        );
12424    }
12425
12426    /// Gate for the CPU **matmul** family moved to FKC-contract registration.
12427    /// IMPORTED from `fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md` via the production
12428    /// `CpuLinkRegistry` (chaining `CPU_MATMUL_ENTRY_POINTS`):
12429    /// - **MatMul** — bare batched matmul (`OpKind::MatMul`), key `[T, T, T]`
12430    ///   (lhs, rhs + `passthrough(lhs)` output). Each per-dtype section
12431    ///   (`## matmul_f32`, …) carries a SPECIFIC single-dtype `entry_point`
12432    ///   resolved AS-IS (no fan), 6 dtypes (F32/F64/BF16/F16 with an f32/native
12433    ///   accumulator + I8/U8 with an i32 accumulator + saturating store).
12434    /// - **FusedLinear** — fused matmul + bias-add (`OpKind::FusedLinear`), key
12435    ///   `[T, T, T, T]` (a, b, bias + `passthrough(a)` output). Reuses
12436    ///   `OpParams::Matmul` for shape; bias is a REQUIRED 1-D `[N]` operand (no
12437    ///   optional fan). 4 dtypes (F32/F64/BF16/F16).
12438    ///
12439    /// This family exercises the CRITICAL alternatives-at-the-same-key path: the
12440    /// binding table supports MULTIPLE ranked kernels per `(op, dtypes, backend)`
12441    /// key, and the MKL/AOCL BLAS siblings (external `fuel-mkl-cpu-backend` /
12442    /// `fuel-aocl-cpu-backend` crates, registered through the exported dispatch
12443    /// helpers with their own `"mkl"`/`"aocl"` `kernel_source` tags) may register
12444    /// at these SAME keys — SEPARATE and out of scope here. So this gate does NOT
12445    /// assert the portable wrapper is the SOLE alternative; it `find`s the
12446    /// portable `"portable-cpu"`-sourced entry among the alternatives.
12447    ///
12448    /// SEPARATE seams left untouched: the `FusedKernelRegistry`
12449    /// `FusedOps::FUSED_LINEAR` registration (`register_default_fused_kernels`) is
12450    /// hand-written and not FKC-imported (the matmul contract declares NO
12451    /// `fused_op` sections); the quant `QMatMul` / `Nf4Matmul` OpKinds have their
12452    /// own contracts and stay hand-written.
12453    ///
12454    /// For each migrated key: the portable wrapper is bound with
12455    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12456    /// contiguous, and the contract's bit-stable precision riding through.
12457    #[test]
12458    fn global_bindings_registers_matmul_family_from_contract() {
12459        let table = global_bindings();
12460        let mut checked = 0usize;
12461
12462        // Assert a (op, key) resolves to `expected` (the portable wrapper) with
12463        // the contract provenance — `find`ing it among any BLAS-sibling
12464        // alternatives at the same key (never asserting single-alternative).
12465        let mut check =
12466            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12467                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12468                let entry = alts
12469                    .iter()
12470                    .find(|e| e.kernel as usize == expected as usize)
12471                    .unwrap_or_else(|| {
12472                        panic!(
12473                            "{op:?}/{label}/Cpu: the portable wrapper must be bound \
12474                         FROM the matmul contract in global_bindings() — found {} \
12475                         alternative(s) with sources {:?}",
12476                            alts.len(),
12477                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12478                        )
12479                    });
12480                assert_eq!(
12481                    entry.kernel_source, "portable-cpu",
12482                    "{op:?}/{label}: portable kernel must be contract-sourced \
12483                 (kernel_source=\"portable-cpu\"); got {:?}",
12484                    entry.kernel_source,
12485                );
12486                assert!(
12487                    !entry.caps.strided_input,
12488                    "{op:?}/{label}: caps preserved (contiguous-only)",
12489                );
12490                assert!(
12491                    entry.precision.bit_stable_on_same_hardware,
12492                    "{op:?}/{label}: contract's bit-stable claim rode through",
12493                );
12494                checked += 1;
12495            };
12496
12497        // MatMul — key [T, T, T], per-dtype wrapper resolved AS-IS. 6 dtypes.
12498        let mm_dts = [
12499            DType::F32,
12500            DType::F64,
12501            DType::BF16,
12502            DType::F16,
12503            DType::I8,
12504            DType::U8,
12505        ];
12506        let mm_wrappers: [crate::kernel::KernelRef; 6] = [
12507            matmul_f32_cpu_wrapper,
12508            matmul_f64_cpu_wrapper,
12509            matmul_bf16_cpu_wrapper,
12510            matmul_f16_cpu_wrapper,
12511            matmul_i8_cpu_wrapper,
12512            matmul_u8_cpu_wrapper,
12513        ];
12514        for (i, dt) in mm_dts.iter().enumerate() {
12515            check(OpKind::MatMul, &[*dt, *dt, *dt], mm_wrappers[i], "matmul");
12516        }
12517
12518        // FusedLinear — key [T, T, T, T], per-dtype wrapper resolved AS-IS. 4 dtypes.
12519        let fl_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12520        let fl_wrappers: [crate::kernel::KernelRef; 4] = [
12521            fused_linear_f32_cpu_wrapper,
12522            fused_linear_f64_cpu_wrapper,
12523            fused_linear_bf16_cpu_wrapper,
12524            fused_linear_f16_cpu_wrapper,
12525        ];
12526        for (i, dt) in fl_dts.iter().enumerate() {
12527            check(
12528                OpKind::FusedLinear,
12529                &[*dt, *dt, *dt, *dt],
12530                fl_wrappers[i],
12531                "fused_linear",
12532            );
12533        }
12534
12535        assert_eq!(
12536            checked,
12537            6 + 4,
12538            "matmul(6) + fused_linear(4) contract-sourced bindings",
12539        );
12540    }
12541
12542    /// Gate for the CPU **attention** family's `KernelBindingTable` path migrated
12543    /// to FKC-contract registration. FlashAttn (forward) + the three
12544    /// FlashAttnBackward{Q,K,V} selectors + PagedAttn — 5 ops × 4 dtypes ×
12545    /// {no-alibi, with-alibi} = 40 bindings — are IMPORTED from
12546    /// `fuel-dispatch/kernel-contracts/cpu/attention.fkc.md` (the `op_kind:` sections).
12547    /// Each section declares `alibi_slopes` as an `optional: true` LAST input, so
12548    /// the importer's optional-operand fan registers BOTH the no-alibi key
12549    /// (`[q,k,v(,do),out]` / `[q,kc,vc,bt,cl,out]`) and the with-alibi key
12550    /// (`+alibi`), both resolving the SAME wrapper — byte-for-byte the deleted
12551    /// hand-written `no_alibi`/`with_alibi` regs. Forward FlashAttn and the three
12552    /// backward selectors share the single `OpParams::FlashAttn` carrier (no
12553    /// dedicated backward variant); PagedAttn uses `OpParams::PagedAttn`.
12554    ///
12555    /// **PagedAttn is now REGISTRABLE + contract-sourced (FDX gather-sidecar arc,
12556    /// slice A).** Its `fdx.gather: paged_blocks` pool is import METADATA (§3.9.1):
12557    /// the block_table / context_lens ride as ordinary U32 operands +
12558    /// `OpParams::PagedAttn`, so registration does not depend on the FDX gather
12559    /// VIEW (which stays [consumer-ahead]). Its bindings are asserted
12560    /// contract-sourced alongside FlashAttn below — BORN-RED discriminator: the
12561    /// deleted hand-written regs stamped an empty `kernel_source`, so the
12562    /// `kernel_source == "portable-cpu"` assertion failed until the four paged
12563    /// sections were flipped `registrable: true` + wired into
12564    /// `CPU_ATTENTION_ENTRY_POINTS`. The SEPARATE `FusedKernelRegistry`
12565    /// FLASH_ATTN* / PAGED_ATTN seam (`register_default_fused_kernels`) is
12566    /// untouched (stays hand-written, exactly as before).
12567    ///
12568    /// For each of the 40 keys: resolves to the EXACT production wrapper with
12569    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12570    /// contiguous, and the contract's bit-stable precision riding through.
12571    #[test]
12572    fn global_bindings_registers_attention_family_from_contract() {
12573        let table = global_bindings();
12574        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12575
12576        // Forward FlashAttn wrappers (order matches `dts`); the same wrapper
12577        // serves both the no-alibi [q,k,v,out] and with-alibi [q,k,v,alibi,out] keys.
12578        let fa_wrappers: [crate::kernel::KernelRef; 4] = [
12579            flash_attn_f32_cpu_wrapper,
12580            flash_attn_f64_cpu_wrapper,
12581            flash_attn_bf16_cpu_wrapper,
12582            flash_attn_f16_cpu_wrapper,
12583        ];
12584        // FlashAttnBackward{Q,K,V} wrappers (order matches `dts`).
12585        let fabq: [crate::kernel::KernelRef; 4] = [
12586            flash_attn_backward_q_f32_cpu_wrapper,
12587            flash_attn_backward_q_f64_cpu_wrapper,
12588            flash_attn_backward_q_bf16_cpu_wrapper,
12589            flash_attn_backward_q_f16_cpu_wrapper,
12590        ];
12591        let fabk: [crate::kernel::KernelRef; 4] = [
12592            flash_attn_backward_k_f32_cpu_wrapper,
12593            flash_attn_backward_k_f64_cpu_wrapper,
12594            flash_attn_backward_k_bf16_cpu_wrapper,
12595            flash_attn_backward_k_f16_cpu_wrapper,
12596        ];
12597        let fabv: [crate::kernel::KernelRef; 4] = [
12598            flash_attn_backward_v_f32_cpu_wrapper,
12599            flash_attn_backward_v_f64_cpu_wrapper,
12600            flash_attn_backward_v_bf16_cpu_wrapper,
12601            flash_attn_backward_v_f16_cpu_wrapper,
12602        ];
12603        // PagedAttn wrappers (order matches `dts`); the same wrapper serves both
12604        // the no-alibi [q,kc,vc,bt,cl,out] and with-alibi (+alibi) keys.
12605        let pa_wrappers: [crate::kernel::KernelRef; 4] = [
12606            paged_attn_f32_cpu_wrapper,
12607            paged_attn_f64_cpu_wrapper,
12608            paged_attn_bf16_cpu_wrapper,
12609            paged_attn_f16_cpu_wrapper,
12610        ];
12611
12612        // Assert `op`/`key` resolves to `expected` with the contract provenance,
12613        // FINDING it among any alternatives at the key (never single-alternative).
12614        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12615            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12616            let entry = alts
12617                .iter()
12618                .find(|e| e.kernel as usize == expected as usize)
12619                .unwrap_or_else(|| {
12620                    panic!(
12621                        "{op:?}/{label}/Cpu: the production wrapper must be bound \
12622                         FROM the attention contract in global_bindings() — found {} \
12623                         alternative(s) with sources {:?}",
12624                        alts.len(),
12625                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12626                    )
12627                });
12628            assert_eq!(
12629                entry.kernel_source, "portable-cpu",
12630                "{op:?}/{label}: family must be contract-sourced \
12631                 (kernel_source=\"portable-cpu\"); got {:?}",
12632                entry.kernel_source,
12633            );
12634            assert!(
12635                !entry.caps.strided_input,
12636                "{op:?}/{label}: caps preserved (contiguous-only)",
12637            );
12638            assert!(
12639                entry.precision.bit_stable_on_same_hardware,
12640                "{op:?}/{label}: contract's bit-stable claim rode through",
12641            );
12642        };
12643
12644        let mut checked = 0usize;
12645        for (i, dt) in dts.iter().enumerate() {
12646            // Forward: no-alibi [q,k,v,out] + with-alibi [q,k,v,alibi,out].
12647            let fa_noa: &[DType] = &[*dt, *dt, *dt, *dt];
12648            let fa_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12649            check(OpKind::FlashAttn, fa_noa, fa_wrappers[i], "flash no-alibi");
12650            check(OpKind::FlashAttn, fa_a, fa_wrappers[i], "flash with-alibi");
12651            checked += 2;
12652
12653            // Backward Q/K/V: no-alibi [q,k,v,do,out] + with-alibi [q,k,v,do,alibi,out].
12654            let bw_noa: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12655            let bw_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt, *dt];
12656            for (op, ws) in [
12657                (OpKind::FlashAttnBackwardQ, &fabq),
12658                (OpKind::FlashAttnBackwardK, &fabk),
12659                (OpKind::FlashAttnBackwardV, &fabv),
12660            ] {
12661                check(op, bw_noa, ws[i], "backward no-alibi");
12662                check(op, bw_a, ws[i], "backward with-alibi");
12663                checked += 2;
12664            }
12665
12666            // PagedAttn (FDX gather-sidecar arc, slice A): now CONTRACT-SOURCED
12667            // like FlashAttn. no-alibi [q,kc,vc,bt:U32,cl:U32,out] + with-alibi
12668            // (+alibi). BORN-RED discriminator: before the migration the paged
12669            // bindings were hand-written (`kernel_source == ""`); `check` requires
12670            // `kernel_source == "portable-cpu"`, so it fails until the four paged
12671            // sections are flipped `registrable: true` + resolved via
12672            // CPU_ATTENTION_ENTRY_POINTS. Proves the gather block is import
12673            // metadata, not a registration blocker.
12674            let pa_noa: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt];
12675            let pa_a: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt, *dt];
12676            check(OpKind::PagedAttn, pa_noa, pa_wrappers[i], "paged no-alibi");
12677            check(OpKind::PagedAttn, pa_a, pa_wrappers[i], "paged with-alibi");
12678            checked += 2;
12679        }
12680        assert_eq!(
12681            checked, 40,
12682            "FlashAttn(8) + FlashAttnBackward{{Q,K,V}}(24) + PagedAttn(8) = 40 \
12683             contract-sourced bindings",
12684        );
12685    }
12686
12687    /// The CPU **in-place scalar-param** family is registered FROM its FKC
12688    /// contract (`fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md`) via
12689    /// `register_cpu_inplace_from_contract`, NOT the deleted hand-written
12690    /// `table.register(<Op>Inplace / InplaceAffine / ClampInplace / PowIInplace,
12691    /// &unary(dt), …)` regs. 21 in-place unary ops (each fanning `[F32,F64,BF16,
12692    /// F16]` = 84) + `InplaceAffine` / `ClampInplace` / `PowIInplace` (4 dtypes
12693    /// each = 12) = 96 bindings, all keyed `[T, T]` (the single `out` operand +
12694    /// its `passthrough(out)` mirror; the executor's `InplaceKernel` arm passes
12695    /// the target as `outputs[0]`, so the wrapper takes 0 inputs + 1 output, but
12696    /// the binding-table KEY is `[T, T]`).
12697    ///
12698    /// For each of the 96 keys: resolves to the EXACT production wrapper with
12699    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12700    /// contiguous, and the contract's bit-stable precision riding through.
12701    #[test]
12702    fn global_bindings_registers_inplace_family_from_contract() {
12703        let table = global_bindings();
12704        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12705
12706        // Assert `op`/`[dt,dt]` resolves to `expected` with the contract
12707        // provenance, FINDING it among any alternatives at the key.
12708        let check = |op: OpKind, dt: DType, expected: crate::kernel::KernelRef, label: &str| {
12709            let key: &[DType] = &[dt, dt];
12710            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12711            let entry = alts
12712                .iter()
12713                .find(|e| e.kernel as usize == expected as usize)
12714                .unwrap_or_else(|| {
12715                    panic!(
12716                        "{op:?}/{label}/{dt:?}/Cpu: the production wrapper must be bound \
12717                         FROM the in-place contract in global_bindings() — found {} \
12718                         alternative(s) with sources {:?}",
12719                        alts.len(),
12720                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12721                    )
12722                });
12723            assert_eq!(
12724                entry.kernel_source, "portable-cpu",
12725                "{op:?}/{label}/{dt:?}: family must be contract-sourced \
12726                 (kernel_source=\"portable-cpu\"); got {:?}",
12727                entry.kernel_source,
12728            );
12729            assert!(
12730                !entry.caps.strided_input,
12731                "{op:?}/{label}/{dt:?}: caps preserved (contiguous-only)",
12732            );
12733            assert!(
12734                entry.precision.bit_stable_on_same_hardware,
12735                "{op:?}/{label}/{dt:?}: contract's bit-stable claim rode through",
12736            );
12737        };
12738
12739        // 21 in-place unary ops × 4 dtypes (wrapper order matches `dts`).
12740        // Each row: (OpKind, label, [f32, f64, bf16, f16] wrappers).
12741        let unary_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12742            (
12743                OpKind::ReluInplace,
12744                "relu",
12745                [
12746                    relu_inplace_f32_cpu_wrapper,
12747                    relu_inplace_f64_cpu_wrapper,
12748                    relu_inplace_bf16_cpu_wrapper,
12749                    relu_inplace_f16_cpu_wrapper,
12750                ],
12751            ),
12752            (
12753                OpKind::SiluInplace,
12754                "silu",
12755                [
12756                    silu_inplace_f32_cpu_wrapper,
12757                    silu_inplace_f64_cpu_wrapper,
12758                    silu_inplace_bf16_cpu_wrapper,
12759                    silu_inplace_f16_cpu_wrapper,
12760                ],
12761            ),
12762            (
12763                OpKind::GeluTanhInplace,
12764                "gelu_tanh",
12765                [
12766                    gelu_inplace_f32_cpu_wrapper,
12767                    gelu_inplace_f64_cpu_wrapper,
12768                    gelu_inplace_bf16_cpu_wrapper,
12769                    gelu_inplace_f16_cpu_wrapper,
12770                ],
12771            ),
12772            (
12773                OpKind::TanhInplace,
12774                "tanh",
12775                [
12776                    tanh_inplace_f32_cpu_wrapper,
12777                    tanh_inplace_f64_cpu_wrapper,
12778                    tanh_inplace_bf16_cpu_wrapper,
12779                    tanh_inplace_f16_cpu_wrapper,
12780                ],
12781            ),
12782            (
12783                OpKind::SigmoidInplace,
12784                "sigmoid",
12785                [
12786                    sigmoid_inplace_f32_cpu_wrapper,
12787                    sigmoid_inplace_f64_cpu_wrapper,
12788                    sigmoid_inplace_bf16_cpu_wrapper,
12789                    sigmoid_inplace_f16_cpu_wrapper,
12790                ],
12791            ),
12792            (
12793                OpKind::NegInplace,
12794                "neg",
12795                [
12796                    neg_inplace_f32_cpu_wrapper,
12797                    neg_inplace_f64_cpu_wrapper,
12798                    neg_inplace_bf16_cpu_wrapper,
12799                    neg_inplace_f16_cpu_wrapper,
12800                ],
12801            ),
12802            (
12803                OpKind::AbsInplace,
12804                "abs",
12805                [
12806                    abs_inplace_f32_cpu_wrapper,
12807                    abs_inplace_f64_cpu_wrapper,
12808                    abs_inplace_bf16_cpu_wrapper,
12809                    abs_inplace_f16_cpu_wrapper,
12810                ],
12811            ),
12812            (
12813                OpKind::SqrInplace,
12814                "sqr",
12815                [
12816                    sqr_inplace_f32_cpu_wrapper,
12817                    sqr_inplace_f64_cpu_wrapper,
12818                    sqr_inplace_bf16_cpu_wrapper,
12819                    sqr_inplace_f16_cpu_wrapper,
12820                ],
12821            ),
12822            (
12823                OpKind::SqrtInplace,
12824                "sqrt",
12825                [
12826                    sqrt_inplace_f32_cpu_wrapper,
12827                    sqrt_inplace_f64_cpu_wrapper,
12828                    sqrt_inplace_bf16_cpu_wrapper,
12829                    sqrt_inplace_f16_cpu_wrapper,
12830                ],
12831            ),
12832            (
12833                OpKind::RsqrtInplace,
12834                "rsqrt",
12835                [
12836                    rsqrt_inplace_f32_cpu_wrapper,
12837                    rsqrt_inplace_f64_cpu_wrapper,
12838                    rsqrt_inplace_bf16_cpu_wrapper,
12839                    rsqrt_inplace_f16_cpu_wrapper,
12840                ],
12841            ),
12842            (
12843                OpKind::RecipInplace,
12844                "recip",
12845                [
12846                    recip_inplace_f32_cpu_wrapper,
12847                    recip_inplace_f64_cpu_wrapper,
12848                    recip_inplace_bf16_cpu_wrapper,
12849                    recip_inplace_f16_cpu_wrapper,
12850                ],
12851            ),
12852            (
12853                OpKind::ExpInplace,
12854                "exp",
12855                [
12856                    exp_inplace_f32_cpu_wrapper,
12857                    exp_inplace_f64_cpu_wrapper,
12858                    exp_inplace_bf16_cpu_wrapper,
12859                    exp_inplace_f16_cpu_wrapper,
12860                ],
12861            ),
12862            (
12863                OpKind::LogInplace,
12864                "log",
12865                [
12866                    log_inplace_f32_cpu_wrapper,
12867                    log_inplace_f64_cpu_wrapper,
12868                    log_inplace_bf16_cpu_wrapper,
12869                    log_inplace_f16_cpu_wrapper,
12870                ],
12871            ),
12872            (
12873                OpKind::SinInplace,
12874                "sin",
12875                [
12876                    sin_inplace_f32_cpu_wrapper,
12877                    sin_inplace_f64_cpu_wrapper,
12878                    sin_inplace_bf16_cpu_wrapper,
12879                    sin_inplace_f16_cpu_wrapper,
12880                ],
12881            ),
12882            (
12883                OpKind::CosInplace,
12884                "cos",
12885                [
12886                    cos_inplace_f32_cpu_wrapper,
12887                    cos_inplace_f64_cpu_wrapper,
12888                    cos_inplace_bf16_cpu_wrapper,
12889                    cos_inplace_f16_cpu_wrapper,
12890                ],
12891            ),
12892            (
12893                OpKind::SignInplace,
12894                "sign",
12895                [
12896                    sign_inplace_f32_cpu_wrapper,
12897                    sign_inplace_f64_cpu_wrapper,
12898                    sign_inplace_bf16_cpu_wrapper,
12899                    sign_inplace_f16_cpu_wrapper,
12900                ],
12901            ),
12902            (
12903                OpKind::FloorInplace,
12904                "floor",
12905                [
12906                    floor_inplace_f32_cpu_wrapper,
12907                    floor_inplace_f64_cpu_wrapper,
12908                    floor_inplace_bf16_cpu_wrapper,
12909                    floor_inplace_f16_cpu_wrapper,
12910                ],
12911            ),
12912            (
12913                OpKind::CeilInplace,
12914                "ceil",
12915                [
12916                    ceil_inplace_f32_cpu_wrapper,
12917                    ceil_inplace_f64_cpu_wrapper,
12918                    ceil_inplace_bf16_cpu_wrapper,
12919                    ceil_inplace_f16_cpu_wrapper,
12920                ],
12921            ),
12922            (
12923                OpKind::RoundInplace,
12924                "round",
12925                [
12926                    round_inplace_f32_cpu_wrapper,
12927                    round_inplace_f64_cpu_wrapper,
12928                    round_inplace_bf16_cpu_wrapper,
12929                    round_inplace_f16_cpu_wrapper,
12930                ],
12931            ),
12932            (
12933                OpKind::ErfInplace,
12934                "erf",
12935                [
12936                    erf_inplace_f32_cpu_wrapper,
12937                    erf_inplace_f64_cpu_wrapper,
12938                    erf_inplace_bf16_cpu_wrapper,
12939                    erf_inplace_f16_cpu_wrapper,
12940                ],
12941            ),
12942            (
12943                OpKind::GeluInplace,
12944                "gelu",
12945                [
12946                    gelu_erf_inplace_f32_cpu_wrapper,
12947                    gelu_erf_inplace_f64_cpu_wrapper,
12948                    gelu_erf_inplace_bf16_cpu_wrapper,
12949                    gelu_erf_inplace_f16_cpu_wrapper,
12950                ],
12951            ),
12952        ];
12953
12954        // Affine / clamp / powi — scalar-param single sections. Note the affine
12955        // wrapper name is `inplace_affine_<dt>_cpu_wrapper` (words swapped vs the
12956        // `affine_inplace_<dt>` symbol).
12957        let scalar_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12958            (
12959                OpKind::InplaceAffine,
12960                "affine",
12961                [
12962                    inplace_affine_f32_cpu_wrapper,
12963                    inplace_affine_f64_cpu_wrapper,
12964                    inplace_affine_bf16_cpu_wrapper,
12965                    inplace_affine_f16_cpu_wrapper,
12966                ],
12967            ),
12968            (
12969                OpKind::ClampInplace,
12970                "clamp",
12971                [
12972                    clamp_inplace_f32_cpu_wrapper,
12973                    clamp_inplace_f64_cpu_wrapper,
12974                    clamp_inplace_bf16_cpu_wrapper,
12975                    clamp_inplace_f16_cpu_wrapper,
12976                ],
12977            ),
12978            (
12979                OpKind::PowIInplace,
12980                "powi",
12981                [
12982                    powi_inplace_f32_cpu_wrapper,
12983                    powi_inplace_f64_cpu_wrapper,
12984                    powi_inplace_bf16_cpu_wrapper,
12985                    powi_inplace_f16_cpu_wrapper,
12986                ],
12987            ),
12988        ];
12989
12990        let mut checked = 0usize;
12991        for (op, label, ws) in unary_family.iter().chain(scalar_family.iter()) {
12992            for (i, dt) in dts.iter().enumerate() {
12993                check(*op, *dt, ws[i], label);
12994                checked += 1;
12995            }
12996        }
12997        assert_eq!(
12998            checked, 96,
12999            "21 in-place unary (×4) + InplaceAffine/ClampInplace/PowIInplace (×4) = 96 \
13000             contract-sourced bindings",
13001        );
13002    }
13003
13004    /// Gate for the CPU **cast** family migrated to FKC-contract registration.
13005    /// The FULL directed-pair matrix — every ordered pair of the 11 real numeric
13006    /// dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64}, identity excluded =
13007    /// 11 × 10 = 110 pairs — is IMPORTED from
13008    /// `fuel-dispatch/kernel-contracts/cpu/cast.fkc.md` (see
13009    /// `register_cpu_cast_from_contract`). Each per-pair section declares a
13010    /// single-dtype `src` input + `fixed(DST)` output, so it does NOT dtype-fan —
13011    /// the importer keys `[SRC, DST]` (byte-for-byte the deleted hand-written
13012    /// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the SPECIFIC
13013    /// `cast_<src>_to_<dst>` byte-kernel symbol AS-IS through the production
13014    /// `CpuLinkRegistry` (chaining `CPU_CAST_ENTRY_POINTS`). Because the binding
13015    /// lookup is keyed on the TARGET dtype, every one of a target's 10 source
13016    /// pairs resolves to the SAME per-target `cast_to_<dst>_cpu_wrapper` (which
13017    /// dispatches on source internally) — the fanned byte-kernel symbols are the
13018    /// synthetic-umbrella precedent (10 distinct entry_points → 1 wrapper).
13019    ///
13020    /// For each of the 110 pairs: resolves to the EXACT production per-target
13021    /// wrapper with `kernel_source == "portable-cpu"` (the contract provenance
13022    /// tag), caps contiguous-only, and the contract's bit-stable precision riding
13023    /// through. FKC is the SOLE registration path for the whole family.
13024    #[test]
13025    fn global_bindings_registers_cast_family_from_contract() {
13026        let table = global_bindings();
13027
13028        // Per-target wrapper (the binding-table key is keyed on the TARGET dtype;
13029        // each wrapper dispatches on the source dtype internally).
13030        let targets: [(DType, crate::kernel::KernelRef); 11] = [
13031            (DType::F32, cast_to_f32_cpu_wrapper),
13032            (DType::F64, cast_to_f64_cpu_wrapper),
13033            (DType::F16, cast_to_f16_cpu_wrapper),
13034            (DType::BF16, cast_to_bf16_cpu_wrapper),
13035            (DType::F8E4M3, cast_to_f8e4m3_cpu_wrapper),
13036            (DType::U8, cast_to_u8_cpu_wrapper),
13037            (DType::I8, cast_to_i8_cpu_wrapper),
13038            (DType::U32, cast_to_u32_cpu_wrapper),
13039            (DType::I16, cast_to_i16_cpu_wrapper),
13040            (DType::I32, cast_to_i32_cpu_wrapper),
13041            (DType::I64, cast_to_i64_cpu_wrapper),
13042        ];
13043        let all_dts: [DType; 11] = [
13044            DType::F32,
13045            DType::F64,
13046            DType::F16,
13047            DType::BF16,
13048            DType::F8E4M3,
13049            DType::U8,
13050            DType::I8,
13051            DType::U32,
13052            DType::I16,
13053            DType::I32,
13054            DType::I64,
13055        ];
13056
13057        let mut checked = 0usize;
13058        for (dst, expected) in targets {
13059            for src in all_dts {
13060                if src == dst {
13061                    continue; // identity pairs are elided by the optimizer, not registered
13062                }
13063                let key: &[DType] = &[src, dst];
13064                let alts = table.lookup_alternatives(OpKind::Cast, key, BackendId::Cpu);
13065                let entry = alts
13066                    .iter()
13067                    .find(|e| e.kernel as usize == expected as usize)
13068                    .unwrap_or_else(|| {
13069                        panic!(
13070                            "Cast {src:?}->{dst:?}/Cpu: the production per-target wrapper must be \
13071                             bound FROM the cast contract in global_bindings() — found {} \
13072                             alternative(s) with sources {:?}",
13073                            alts.len(),
13074                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
13075                        )
13076                    });
13077                assert_eq!(
13078                    entry.kernel_source, "portable-cpu",
13079                    "Cast {src:?}->{dst:?}: family must be contract-sourced \
13080                     (kernel_source=\"portable-cpu\"); got {:?}",
13081                    entry.kernel_source,
13082                );
13083                assert!(
13084                    !entry.caps.strided_input,
13085                    "Cast {src:?}->{dst:?}: caps preserved (contiguous-only)",
13086                );
13087                assert!(
13088                    entry.precision.bit_stable_on_same_hardware,
13089                    "Cast {src:?}->{dst:?}: contract's bit-stable claim rode through",
13090                );
13091                checked += 1;
13092            }
13093        }
13094        assert_eq!(
13095            checked, 110,
13096            "11 target dtypes × 10 sources each = 110 directed cast pairs (identity excluded)"
13097        );
13098    }
13099
13100    /// Lookup miss returns NoBackendForOp with diagnostic data.
13101    #[test]
13102    fn binding_table_lookup_miss_errors() {
13103        let mut table = KernelBindingTable::new();
13104        register_cpu_kernels(&mut table);
13105        // I64 isn't registered for any elementwise op — must error.
13106        // (BF16/F16/F32/F64 all have AddElementwise wrappers as of
13107        // Phase C's multi-dtype expansion.)
13108        let result = table.lookup(
13109            OpKind::AddElementwise,
13110            &[DType::I64, DType::I64, DType::I64],
13111            BackendId::Cpu,
13112        );
13113        assert!(result.is_err());
13114    }
13115
13116    /// F8E4M3 ↔ {F32, F16, BF16} casts (alpha.29 CastSubBytePlan sibling
13117    /// on the CPU side) are all reachable through the binding table.
13118    #[test]
13119    fn cpu_f8e4m3_cast_pairs_registered() {
13120        let mut table = KernelBindingTable::new();
13121        register_cpu_kernels(&mut table);
13122        for other in [DType::F32, DType::F16, DType::BF16] {
13123            for (src, dst) in [(DType::F8E4M3, other), (other, DType::F8E4M3)] {
13124                table
13125                    .lookup(OpKind::Cast, &[src, dst], BackendId::Cpu)
13126                    .unwrap_or_else(|e| panic!("Cast {src:?} → {dst:?} (CPU) not registered: {e}"));
13127            }
13128        }
13129    }
13130
13131    /// Integer MatMul (i8 / u8) registrations land under the same
13132    /// `(MatMul, [T, T, T], Cpu)` key shape as the float variants.
13133    #[test]
13134    fn cpu_int_matmul_registered() {
13135        let mut table = KernelBindingTable::new();
13136        register_cpu_kernels(&mut table);
13137        for t in [DType::I8, DType::U8] {
13138            table
13139                .lookup(OpKind::MatMul, &[t, t, t], BackendId::Cpu)
13140                .unwrap_or_else(|e| panic!("MatMul {t:?} (CPU) not registered: {e}"));
13141        }
13142    }
13143
13144    /// End-to-end: register, resolve target backend, look up the
13145    /// kernel, allocate input/output Storages, call the kernel,
13146    /// verify output bytes match the elementwise sum. This is the
13147    /// proof-of-concept for the entire B-phase dispatch path.
13148    #[test]
13149    fn b5_end_to_end_add_elementwise_f32() {
13150        // 1. Build registry + capability advertisement.
13151        let mut registry = CapabilityRegistry::new();
13152        registry.register(cpu_caps());
13153
13154        // 2. Resolve which backend handles (AddElementwise, F32).
13155        let backend =
13156            resolve_target_backend(&registry, OpKind::AddElementwise, DType::F32).expect("resolve");
13157        assert_eq!(backend, BackendId::Cpu);
13158
13159        // 3. Build binding table + register CPU wrappers.
13160        let mut bindings = KernelBindingTable::new();
13161        register_cpu_kernels(&mut bindings);
13162
13163        // 4. Look up the kernel for (op, dtypes, backend).
13164        let kernel = bindings
13165            .lookup(
13166                OpKind::AddElementwise,
13167                &[DType::F32, DType::F32, DType::F32],
13168                backend,
13169            )
13170            .expect("lookup");
13171
13172        // 5. Allocate input + output Storages.
13173        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
13174        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0]);
13175        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
13176
13177        let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
13178        let mut outputs = vec![Arc::new(RwLock::new(out))];
13179
13180        // 6. Call the dispatch wrapper.
13181        kernel(&inputs, &mut outputs, &[], &OpParams::None).expect("kernel");
13182
13183        // 7. Verify output bytes match elementwise sum.
13184        let out_guard = outputs[0].read().unwrap();
13185        if let BackendStorage::Cpu(c) = &out_guard.inner {
13186            let typed: &[f32] = c.as_slice().expect("cast");
13187            assert_eq!(typed, &[11.0, 22.0, 33.0, 44.0]);
13188        } else {
13189            panic!("expected CPU output");
13190        }
13191    }
13192
13193    /// E2E: wrong number of inputs surfaces a typed error.
13194    #[test]
13195    fn b5_wrapper_arity_check() {
13196        let mut bindings = KernelBindingTable::new();
13197        register_cpu_kernels(&mut bindings);
13198        let kernel = bindings
13199            .lookup(
13200                OpKind::AddElementwise,
13201                &[DType::F32, DType::F32, DType::F32],
13202                BackendId::Cpu,
13203            )
13204            .unwrap();
13205
13206        // Only one input — should error, not panic.
13207        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
13208        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
13209        let inputs = vec![Arc::new(RwLock::new(lhs))];
13210        let mut outputs = vec![Arc::new(RwLock::new(out))];
13211
13212        let result = kernel(&inputs, &mut outputs, &[], &OpParams::None);
13213        assert!(result.is_err());
13214    }
13215
13216    /// GAP-015 regression: a held binding-table snapshot must not block a
13217    /// writer, and must not block the holder's own later reads.
13218    ///
13219    /// This is the deadlock reduced to ONE thread, which is what makes it a
13220    /// usable test. The suite-level reproducer needed `--test-threads=24+`
13221    /// to get a writer to queue against readers; here the same cycle is
13222    /// forced deterministically, because under the old
13223    /// `RwLock<KernelBindingTable>` the sequence below is a *self*-deadlock:
13224    /// `global_bindings()` returned a live `RwLockReadGuard`, so asking for
13225    /// the write lock while still holding it waited on a lock this very
13226    /// thread was blocking, forever. Under copy-on-write there is no guard
13227    /// to hold, so it just runs.
13228    ///
13229    /// Watchdog rather than a bare call, because the failure mode is a hang,
13230    /// not a panic: without the timeout this test would wedge the whole
13231    /// binary instead of reporting. Verified born-red — see the commit.
13232    #[test]
13233    fn held_snapshot_does_not_block_a_concurrent_write() {
13234        use std::sync::mpsc;
13235        use std::time::Duration;
13236
13237        let (tx, rx) = mpsc::channel();
13238        std::thread::spawn(move || {
13239            // 1. Take a snapshot and KEEP it across the write below.
13240            let snap = global_bindings();
13241            let before = snap
13242                .lookup(
13243                    OpKind::AddElementwise,
13244                    &[DType::F32, DType::F32, DType::F32],
13245                    BackendId::Cpu,
13246                )
13247                .is_ok();
13248
13249            // 2. Write while that snapshot is still alive. This is the step
13250            //    that deadlocked. The extender is intentionally a no-op —
13251            //    the hazard is the lock transition, not what gets written.
13252            extend_global_bindings(|_t| {});
13253
13254            // 3. Read again while STILL holding the original snapshot. Under
13255            //    std's anti-writer-starvation policy this is the second read
13256            //    that a queued writer would have blocked.
13257            let _snap2 = global_bindings();
13258
13259            // 4. The original snapshot stays usable — it is an owned Arc, so
13260            //    the swap in step 2 cannot invalidate it.
13261            let after = snap
13262                .lookup(
13263                    OpKind::AddElementwise,
13264                    &[DType::F32, DType::F32, DType::F32],
13265                    BackendId::Cpu,
13266                )
13267                .is_ok();
13268
13269            tx.send((before, after)).ok();
13270        });
13271
13272        match rx.recv_timeout(Duration::from_secs(30)) {
13273            Ok((before, after)) => {
13274                assert!(
13275                    before,
13276                    "CPU AddElementwise+F32 should resolve in the snapshot"
13277                );
13278                assert!(
13279                    after,
13280                    "snapshot must stay readable after a concurrent table swap"
13281                );
13282            }
13283            Err(_) => panic!(
13284                "GAP-015 regression: holding a binding-table snapshot across \
13285                 extend_global_bindings() deadlocked (30s watchdog). The read \
13286                 path must hand out an owned snapshot, not a lock guard."
13287            ),
13288        }
13289    }
13290
13291    /// Global registry auto-registers CPU on first access.
13292    #[test]
13293    fn global_registry_auto_registers_cpu() {
13294        // First access initializes the registry with CPU caps.
13295        let r = global_registry();
13296        assert!(!r.backends().is_empty());
13297        // CPU is registered.
13298        let cpu = r.backends().iter().find(|c| c.backend_id == BackendId::Cpu);
13299        assert!(cpu.is_some(), "CPU should be auto-registered");
13300    }
13301
13302    /// Global bindings auto-registers the CPU AddElementwise+F32
13303    /// wrapper on first access.
13304    #[test]
13305    fn global_bindings_auto_registers_cpu_wrappers() {
13306        let b = global_bindings();
13307        let result = b.lookup(
13308            OpKind::AddElementwise,
13309            &[DType::F32, DType::F32, DType::F32],
13310            BackendId::Cpu,
13311        );
13312        assert!(
13313            result.is_ok(),
13314            "CPU AddElementwise+F32 should be registered"
13315        );
13316    }
13317
13318    // `global_bindings_auto_registers_cuda_paths` moved to `fuel-cuda-dispatch/tests/cuda_global_install.rs` (row 137 step 6.2):
13319    // it needs the CUDA kernels in the global table, and they are registered above this crate now.
13320
13321    /// Picker-alternatives audit harness: enumerates the global binding
13322    /// table and prints every `(op, dtypes)` key with `>1` registered
13323    /// alternative (multi-backend or multi-impl within one backend). Read the
13324    /// table with `--nocapture`; the only assertion is that the table is
13325    /// non-empty, so a registry that silently emptied cannot pass as an
13326    /// empty audit.
13327    ///
13328    /// Run: `cargo test -p fuel-dispatch --features cuda,vulkan     ///     audit_multi_backend_coverage -- --nocapture`
13329    #[test]
13330    fn audit_multi_backend_coverage() {
13331        let b = global_bindings();
13332        assert!(
13333            !b.is_empty(),
13334            "the global binding table is empty, so this audit would report nothing"
13335        );
13336
13337        // Group by (op_kind, dtypes); each entry maps to the list of
13338        // (backend, n_alts_within_backend). Iterates via iter_precision
13339        // because that already exposes per-alternative tuples.
13340        // OpKind/DType aren't Ord, so we use Vec-based group lookup.
13341        /// `((op, dtypes), [(backend, count)])` -- one coverage group.
13342        type CoverageGroup = ((OpKind, Vec<DType>), Vec<(BackendId, usize)>);
13343        let mut grouped: Vec<CoverageGroup> = Vec::new();
13344        for (op, dtypes, backend, _precision) in b.iter_precision() {
13345            let key = (op, dtypes.to_vec());
13346            if let Some((_, entry)) = grouped.iter_mut().find(|(k, _)| *k == key) {
13347                if let Some(slot) = entry.iter_mut().find(|(be, _)| *be == backend) {
13348                    slot.1 += 1;
13349                } else {
13350                    entry.push((backend, 1));
13351                }
13352            } else {
13353                grouped.push((key, vec![(backend, 1)]));
13354            }
13355        }
13356        // Sort by op debug-string, then dtype list, for stable output.
13357        grouped.sort_by(|a, b| {
13358            let oa = format!("{:?}", a.0.0);
13359            let ob = format!("{:?}", b.0.0);
13360            oa.cmp(&ob).then_with(|| {
13361                let da = format!("{:?}", a.0.1);
13362                let db = format!("{:?}", b.0.1);
13363                da.cmp(&db)
13364            })
13365        });
13366
13367        let total_keys = grouped.len();
13368        let mut multi_backend = 0;
13369        let mut multi_impl_single_backend = 0;
13370        let mut single_alt = 0;
13371
13372        println!("\n=== Picker-alternatives audit ===");
13373        println!("Total unique (op, dtypes) keys: {total_keys}");
13374        println!("Total alternatives (sum):       {}", b.len());
13375        println!();
13376        println!("Keys with >1 alternative (per Judge-picking working set):");
13377        for ((op, dtypes), backends) in &grouped {
13378            let total_alts: usize = backends.iter().map(|(_, n)| *n).sum();
13379            if total_alts <= 1 {
13380                single_alt += 1;
13381                continue;
13382            }
13383            if backends.len() > 1 {
13384                multi_backend += 1;
13385            } else {
13386                multi_impl_single_backend += 1;
13387            }
13388            let backend_summary: Vec<String> = backends
13389                .iter()
13390                .map(|(be, n)| {
13391                    if *n == 1 {
13392                        format!("{be:?}")
13393                    } else {
13394                        format!("{be:?}×{n}")
13395                    }
13396                })
13397                .collect();
13398            println!(
13399                "  {op:?} {dtypes:?} → {} alts: [{}]",
13400                total_alts,
13401                backend_summary.join(", "),
13402            );
13403        }
13404        println!();
13405        println!("--- summary ---");
13406        println!("Single-alternative keys (no pick to make): {single_alt}");
13407        println!("Multi-backend keys (cross-backend pick):   {multi_backend}");
13408        println!("Multi-impl single-backend keys:            {multi_impl_single_backend}");
13409    }
13410
13411    // =========================================================================
13412    // Step E Phase C / B1 — DEVICE_INFLIGHT counter (the BALANCE gate)
13413    // =========================================================================
13414    //
13415    // The counter is PROCESS-WIDE, so these tests use sentinel `gpu_id`s no
13416    // real device uses (and that no other test in this binary touches) to stay
13417    // independent of any concurrent counter activity.
13418
13419    /// The crux of B1: after a balanced sequence of `inc`/`dec`, the per-device
13420    /// count returns to its baseline. Mirrors the executor's invariant — every
13421    /// async submit (`inc`) is matched by exactly one completion-handle `Drop`
13422    /// (`dec`), so after a realize fully drains the counter is back where it
13423    /// started (the `drain_handles` empty-map assert, in counter form).
13424    #[test]
13425    fn inflight_inc_dec_balances_to_baseline() {
13426        let loc = DeviceLocation::Cuda { gpu_id: 99_001 };
13427        let base = inflight_count(loc);
13428
13429        // N submits in flight → count rises by N.
13430        const N: u32 = 7;
13431        for i in 0..N {
13432            inflight_inc(loc);
13433            assert_eq!(
13434                inflight_count(loc),
13435                base + i + 1,
13436                "inc must raise the count"
13437            );
13438        }
13439        assert_eq!(inflight_count(loc), base + N);
13440
13441        // N completions retire → count falls back to baseline.
13442        for i in 0..N {
13443            inflight_dec(loc);
13444            assert_eq!(
13445                inflight_count(loc),
13446                base + N - i - 1,
13447                "dec must lower the count",
13448            );
13449        }
13450        assert_eq!(
13451            inflight_count(loc),
13452            base,
13453            "balanced inc/dec must return the count to its pre-sequence baseline",
13454        );
13455    }
13456
13457    /// `inflight_dec` is underflow-saturating: decrementing a device whose count
13458    /// is already 0 (or that has never been touched) leaves it at 0, never wraps
13459    /// to `u32::MAX`. A stray dec is harmless to scheduling, never a poison.
13460    #[test]
13461    fn backlog_unfed_device_has_no_estimate_then_balances() {
13462        // A location no other test touches (distinct gpu_id).
13463        let loc = DeviceLocation::Vulkan { gpu_id: 9_001 };
13464        assert_eq!(
13465            backlog_estimate_ns(loc),
13466            None,
13467            "a device nobody fed reports NO estimate, not 0"
13468        );
13469        backlog_add_ns(loc, 1_000);
13470        backlog_add_ns(loc, 500);
13471        assert_eq!(backlog_estimate_ns(loc), Some(1_500));
13472        backlog_sub_ns(loc, 1_000);
13473        assert_eq!(backlog_estimate_ns(loc), Some(500));
13474        backlog_sub_ns(loc, 9_999);
13475        assert_eq!(
13476            backlog_estimate_ns(loc),
13477            Some(0),
13478            "sub saturates at 0, and a fed-then-drained device reports 0 (idle), not None"
13479        );
13480        // Sabotage sibling: sub on a never-fed device must not create a slot.
13481        let other = DeviceLocation::Vulkan { gpu_id: 9_002 };
13482        backlog_sub_ns(other, 5);
13483        assert_eq!(backlog_estimate_ns(other), None);
13484    }
13485
13486    // ---- BacklogLedger (ROADMAP row 158, the executor feed). Each test uses its own `gpu_id` so the
13487    // process-wide table cannot be shared with another test; each clause has a sabotage sibling.
13488
13489    /// The guard's Drop subtracts EXACTLY what it added: after it the device reads Some(0) (fed, now idle),
13490    /// and while it lives the figure is the sum added.
13491    #[test]
13492    fn ledger_drop_subtracts_exactly_what_it_added() {
13493        let loc = DeviceLocation::Vulkan { gpu_id: 9_101 };
13494        {
13495            let mut ledger = BacklogLedger::new();
13496            ledger.add(loc, 1_000);
13497            ledger.add(loc, 500);
13498            assert_eq!(backlog_estimate_ns(loc), Some(1_500));
13499            assert_eq!(ledger.outstanding_ns(loc), 1_500);
13500        }
13501        assert_eq!(
13502            backlog_estimate_ns(loc),
13503            Some(0),
13504            "a realize that ended leaves its device idle (0), not stuck and not unknown"
13505        );
13506    }
13507
13508    /// Sabotage sibling of the above: a ledger that is LEAKED (never dropped) leaves the backlog up. Proves
13509    /// the balance in the test above comes from `Drop`, not from the adds cancelling by themselves.
13510    #[test]
13511    fn a_leaked_ledger_leaves_the_backlog_up() {
13512        let loc = DeviceLocation::Vulkan { gpu_id: 9_102 };
13513        let mut ledger = BacklogLedger::new();
13514        ledger.add(loc, 700);
13515        std::mem::forget(ledger);
13516        assert_eq!(
13517            backlog_estimate_ns(loc),
13518            Some(700),
13519            "without the Drop subtract the work stays counted: the guard is what balances it"
13520        );
13521    }
13522
13523    /// An error (here a panic standing in for any early `?` return) unwinding the realize still takes the
13524    /// work back out: the guard is not an Ok-path-only step.
13525    #[test]
13526    fn ledger_balances_when_the_realize_unwinds() {
13527        let loc = DeviceLocation::Vulkan { gpu_id: 9_103 };
13528        let r = std::panic::catch_unwind(|| {
13529            let mut ledger = BacklogLedger::new();
13530            ledger.add(loc, 4_000);
13531            assert_eq!(backlog_estimate_ns(loc), Some(4_000));
13532            panic!("a node failed mid-walk");
13533        });
13534        assert!(r.is_err(), "the closure must have panicked");
13535        assert_eq!(backlog_estimate_ns(loc), Some(0));
13536        // And an early `?` return, the other way a walk ends in an error.
13537        fn walk(loc: DeviceLocation) -> std::result::Result<(), &'static str> {
13538            let mut ledger = BacklogLedger::new();
13539            ledger.add(loc, 250);
13540            let failed: std::result::Result<(), &'static str> = Err("node failed");
13541            failed?;
13542            drop(ledger);
13543            Ok(())
13544        }
13545        let loc2 = DeviceLocation::Vulkan { gpu_id: 9_104 };
13546        assert!(walk(loc2).is_err());
13547        assert_eq!(backlog_estimate_ns(loc2), Some(0));
13548    }
13549
13550    /// Two realizes on one device (multi-agent serving): each takes back only its own work, so the second
13551    /// one's resolver sees the first one's outstanding backlog and nothing it did not add.
13552    #[test]
13553    fn concurrent_ledgers_each_subtract_only_their_own() {
13554        let loc = DeviceLocation::Vulkan { gpu_id: 9_105 };
13555        let mut first = BacklogLedger::new();
13556        first.add(loc, 3_000);
13557        {
13558            let mut second = BacklogLedger::new();
13559            second.add(loc, 200);
13560            assert_eq!(backlog_estimate_ns(loc), Some(3_200));
13561        }
13562        assert_eq!(
13563            backlog_estimate_ns(loc),
13564            Some(3_000),
13565            "the second realize ending must leave the first one's work counted"
13566        );
13567        drop(first);
13568        assert_eq!(backlog_estimate_ns(loc), Some(0));
13569    }
13570
13571    /// The CPU has no queue to estimate and a zero estimate is no estimate: neither may create a slot,
13572    /// because a device nobody priced must keep reporting NO estimate (`None`), never a fabricated idle.
13573    /// Positive control: a real add on the same ledger does create one.
13574    #[test]
13575    fn ledger_never_feeds_cpu_or_a_zero_estimate() {
13576        let unpriced = DeviceLocation::Vulkan { gpu_id: 9_106 };
13577        let mut ledger = BacklogLedger::new();
13578        ledger.add(DeviceLocation::Cpu, 5_000);
13579        ledger.add(unpriced, 0);
13580        assert_eq!(backlog_estimate_ns(DeviceLocation::Cpu), None);
13581        assert_eq!(backlog_estimate_ns(unpriced), None);
13582        assert_eq!(ledger.outstanding_ns(DeviceLocation::Cpu), 0);
13583        // Positive control: the same ledger, a real estimate on a real device.
13584        let priced = DeviceLocation::Vulkan { gpu_id: 9_107 };
13585        ledger.add(priced, 10);
13586        assert_eq!(backlog_estimate_ns(priced), Some(10));
13587    }
13588
13589    // ---- Retire on completion (ROADMAP row 158): the backlog is QUEUED work. A fed estimate carries a
13590    // non-blocking probe; `retire_completed` takes back exactly the estimates whose probe reports done.
13591
13592    /// Completion retires EXACTLY that op's estimate, not the others'.
13593    #[test]
13594    fn completion_retires_exactly_that_ops_estimate() {
13595        use std::sync::atomic::{AtomicBool, Ordering};
13596        let loc = DeviceLocation::Vulkan { gpu_id: 9_110 };
13597        let first = Arc::new(AtomicBool::new(false));
13598        let second = Arc::new(AtomicBool::new(false));
13599        let mut ledger = BacklogLedger::new();
13600        let (f, g) = (Arc::clone(&first), Arc::clone(&second));
13601        ledger.add_until(loc, 300, move || f.load(Ordering::Relaxed));
13602        ledger.add_until(loc, 200, move || g.load(Ordering::Relaxed));
13603        assert_eq!(backlog_estimate_ns(loc), Some(500));
13604        first.store(true, Ordering::Relaxed);
13605        ledger.retire_completed();
13606        assert_eq!(
13607            backlog_estimate_ns(loc),
13608            Some(200),
13609            "only the finished op's 300 ns left"
13610        );
13611        assert_eq!(ledger.outstanding_ns(loc), 200);
13612        second.store(true, Ordering::Relaxed);
13613        ledger.retire_completed();
13614        assert_eq!(
13615            backlog_estimate_ns(loc),
13616            Some(0),
13617            "drained, and idle (0), not unknown"
13618        );
13619        assert_eq!(ledger.outstanding_ns(loc), 0);
13620    }
13621
13622    /// Sabotage sibling: a probe that never fires retires nothing, however often `retire_completed` runs.
13623    /// (This is the cumulative behaviour the feature removes; the acceptance run reproduces it with
13624    /// `FUEL_BACKLOG_NO_RETIRE=1`.)
13625    #[test]
13626    fn a_probe_that_never_fires_retires_nothing() {
13627        let loc = DeviceLocation::Vulkan { gpu_id: 9_111 };
13628        let mut ledger = BacklogLedger::new();
13629        ledger.add_until(loc, 400, || false);
13630        ledger.add(loc, 100); // no probe at all
13631        for _ in 0..5 {
13632            ledger.retire_completed();
13633        }
13634        assert_eq!(backlog_estimate_ns(loc), Some(500));
13635        assert_eq!(ledger.outstanding_ns(loc), 500);
13636    }
13637
13638    /// An op that FAILS or is DROPPED never completes by its probe: the ledger's `Drop` still takes its
13639    /// estimate back, so the backlog cannot leak (here the ledger is dropped with a probe that never fired,
13640    /// as when an error unwinds the realize).
13641    #[test]
13642    fn a_failed_or_dropped_op_is_also_retired() {
13643        let loc = DeviceLocation::Vulkan { gpu_id: 9_112 };
13644        {
13645            let mut ledger = BacklogLedger::new();
13646            ledger.add_until(loc, 250, || false);
13647            assert_eq!(backlog_estimate_ns(loc), Some(250));
13648        }
13649        assert_eq!(backlog_estimate_ns(loc), Some(0));
13650    }
13651
13652    /// No negative backlog: retiring an estimate that something else already took back saturates at 0, it
13653    /// never wraps to a huge figure.
13654    #[test]
13655    fn retiring_never_drives_the_backlog_negative() {
13656        let loc = DeviceLocation::Vulkan { gpu_id: 9_113 };
13657        let mut ledger = BacklogLedger::new();
13658        ledger.add_until(loc, 100, || true);
13659        backlog_sub_ns(loc, 100); // another path already took it back
13660        ledger.retire_completed();
13661        assert_eq!(backlog_estimate_ns(loc), Some(0));
13662        // Positive control: the same figure after a second, normal add is exact, so the 0 above is a
13663        // saturation and not a dead counter.
13664        ledger.add_until(loc, 60, || true);
13665        assert_eq!(backlog_estimate_ns(loc), Some(60));
13666        ledger.retire_completed();
13667        assert_eq!(backlog_estimate_ns(loc), Some(0));
13668    }
13669
13670    #[test]
13671    fn inflight_dec_is_underflow_safe() {
13672        let untouched = DeviceLocation::Vulkan { gpu_id: 99_002 };
13673        // Never incremented: dec must not create a wrapped count.
13674        inflight_dec(untouched);
13675        assert_eq!(
13676            inflight_count(untouched),
13677            0,
13678            "dec on an untouched device stays 0"
13679        );
13680
13681        let loc = DeviceLocation::Vulkan { gpu_id: 99_003 };
13682        inflight_inc(loc);
13683        inflight_dec(loc);
13684        assert_eq!(inflight_count(loc), 0);
13685        // One extra dec past zero (the over-drain guard).
13686        inflight_dec(loc);
13687        assert_eq!(
13688            inflight_count(loc),
13689            0,
13690            "extra dec past zero must saturate, not wrap"
13691        );
13692    }
13693
13694    /// Distinct `DeviceLocation`s have independent slots — incrementing one
13695    /// device's count never perturbs another's (the per-device keying the
13696    /// selector relies on to compare CUDA vs Vulkan load).
13697    #[test]
13698    fn inflight_counts_are_per_device_independent() {
13699        let cuda = DeviceLocation::Cuda { gpu_id: 99_004 };
13700        let vulkan = DeviceLocation::Vulkan { gpu_id: 99_004 };
13701        let base_c = inflight_count(cuda);
13702        let base_v = inflight_count(vulkan);
13703
13704        inflight_inc(cuda);
13705        inflight_inc(cuda);
13706        inflight_inc(vulkan);
13707
13708        assert_eq!(inflight_count(cuda), base_c + 2);
13709        assert_eq!(inflight_count(vulkan), base_v + 1);
13710
13711        inflight_dec(cuda);
13712        inflight_dec(cuda);
13713        inflight_dec(vulkan);
13714        assert_eq!(inflight_count(cuda), base_c);
13715        assert_eq!(inflight_count(vulkan), base_v);
13716    }
13717
13718    /// FKC cost unification — Part A. `derive_backend_caps` reads a
13719    /// backend's kernels out of the binding table and advertises the
13720    /// `(OpKind, OUTPUT-dtype)` pairs those kernels cover — the general
13721    /// analogue of the hand-maintained `default_cpu_caps`. Verifies:
13722    /// (1) only the requested backend's keys are picked; (2) the OUTPUT
13723    /// dtype (last operand) is what's advertised for multi-dtype keys;
13724    /// (3) substrate/device match the backend. Feature-independent: it
13725    /// builds a fresh table with synthetic wrappers.
13726    #[test]
13727    fn derive_backend_caps_mirrors_binding_table_output_dtypes() {
13728        fn stub(
13729            _i: &[Arc<RwLock<Storage>>],
13730            _o: &mut [Arc<RwLock<Storage>>],
13731            _l: &[Layout],
13732            _p: &OpParams,
13733        ) -> Result<()> {
13734            Ok(())
13735        }
13736        fn stub_b(
13737            _i: &[Arc<RwLock<Storage>>],
13738            _o: &mut [Arc<RwLock<Storage>>],
13739            _l: &[Layout],
13740            _p: &OpParams,
13741        ) -> Result<()> {
13742            Ok(())
13743        }
13744        fn stub_c(
13745            _i: &[Arc<RwLock<Storage>>],
13746            _o: &mut [Arc<RwLock<Storage>>],
13747            _l: &[Layout],
13748            _p: &OpParams,
13749        ) -> Result<()> {
13750            Ok(())
13751        }
13752
13753        let mut table = KernelBindingTable::new();
13754        // A CPU key that MUST NOT bleed into the Vulkan derivation.
13755        table.register(
13756            OpKind::AddElementwise,
13757            &[DType::F32, DType::F32, DType::F32],
13758            BackendId::Cpu,
13759            stub,
13760        );
13761        // Vulkan: an elementwise key (single output dtype) ...
13762        table.register(
13763            OpKind::MulElementwise,
13764            &[DType::F32, DType::F32, DType::F32],
13765            BackendId::Vulkan,
13766            stub_b,
13767        );
13768        // ... and a MIXED-dtype key: inputs F16/F16, OUTPUT F32. The
13769        // derived pair must key on the OUTPUT dtype (F32), not an input.
13770        table.register(
13771            OpKind::MatMul,
13772            &[DType::F16, DType::F16, DType::F32],
13773            BackendId::Vulkan,
13774            stub_c,
13775        );
13776
13777        let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
13778        let caps = derive_backend_caps(BackendId::Vulkan, vk0, &table);
13779
13780        assert_eq!(caps.backend_id, BackendId::Vulkan);
13781        assert_eq!(caps.device_location, vk0);
13782        assert_eq!(caps.storage_substrate, SubstrateClass::VulkanBuffer);
13783        // Elementwise output dtype advertised.
13784        assert!(
13785            caps.op_dtype_support
13786                .contains(&(OpKind::MulElementwise, DType::F32))
13787        );
13788        // Multi-dtype key advertises the OUTPUT dtype (F32), not F16.
13789        assert!(
13790            caps.op_dtype_support
13791                .contains(&(OpKind::MatMul, DType::F32))
13792        );
13793        assert!(
13794            !caps
13795                .op_dtype_support
13796                .contains(&(OpKind::MatMul, DType::F16))
13797        );
13798        // The CPU key is NOT attributed to Vulkan.
13799        assert!(
13800            !caps
13801                .op_dtype_support
13802                .contains(&(OpKind::AddElementwise, DType::F32))
13803        );
13804        // A universal host-staging path back to CPU is advertised so the
13805        // transfer matrix can price GPU↔CPU crossings.
13806        assert!(caps
13807            .transfer_paths
13808            .iter()
13809            .any(|&(dst, path)| dst == DeviceLocation::Cpu && path == TransferPath::HostStaging));
13810    }
13811
13812    /// CapturedRun executor build-out (4b-ζ): `copy_from_cuda_wrapper`'s
13813    /// CUDA-output branch converted from allocate-and-replace
13814    /// (`slot_copy_to_new` + `*dst = copied`) to write-into
13815    /// (`CudaStorageBytes::copy_from_device`). Byte-compares the new
13816    /// write-into result against the OLD `slot_copy_to_new`-based behavior
13817    /// for a non-trivial (17-element, mixed-value) case, AND confirms the
13818    /// destination's buffer identity (device address) is preserved — the
13819    /// property capture-safety depends on (allocate-and-replace would swap
13820    /// in a fresh `Arc<DeviceBuffer<u8>>`, changing the address; write-into
13821    /// must not).
13822    #[test]
13823    #[ignore = "requires a live CUDA device"]
13824    #[cfg(feature = "cuda")]
13825    fn copy_from_cuda_wrapper_cuda_output_write_into_matches_old_behavior() {
13826        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
13827
13828        let Ok(dev) = CudaDevice::new(0) else {
13829            return fuel_test_support::hardware::skip(
13830                fuel_test_support::hardware::Hardware::Cuda,
13831                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
13832            );
13833        };
13834
13835        let src_data: Vec<f32> = (0..17).map(|i| i as f32 * 1.5 - 3.0).collect();
13836        let src_bytes: Vec<u8> = src_data.iter().flat_map(|f| f.to_le_bytes()).collect();
13837        let src_cb = CudaStorageBytes::from_cpu_bytes(&dev, &src_bytes).expect("h2d src");
13838        let src_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13839            BackendStorage::Cuda(src_cb),
13840            DType::F32,
13841        )));
13842
13843        // Pre-allocated output filled with distinguishable garbage — proves
13844        // the write-into path actually overwrites every byte, not just
13845        // reads through stale garbage by luck.
13846        let garbage: Vec<u8> = vec![0xAAu8; src_bytes.len()];
13847        let dst_cb = CudaStorageBytes::from_cpu_bytes(&dev, &garbage).expect("h2d garbage");
13848        let dst_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13849            BackendStorage::Cuda(dst_cb),
13850            DType::F32,
13851        )));
13852
13853        // Destination buffer identity BEFORE the wrapper runs.
13854        let before_ptr = {
13855            let g = dst_arc.read().unwrap();
13856            let BackendStorage::Cuda(c) = &g.inner else {
13857                panic!("not cuda")
13858            };
13859            c.buffer() as *const _ as usize
13860        };
13861
13862        let inputs = vec![Arc::clone(&src_arc)];
13863        let mut outputs = vec![Arc::clone(&dst_arc)];
13864        copy_from_cuda_wrapper(&inputs, &mut outputs, &[], &OpParams::None)
13865            .expect("copy_from_cuda_wrapper (write-into CUDA branch)");
13866
13867        let after_ptr = {
13868            let g = dst_arc.read().unwrap();
13869            let BackendStorage::Cuda(c) = &g.inner else {
13870                panic!("not cuda")
13871            };
13872            c.buffer() as *const _ as usize
13873        };
13874        assert_eq!(
13875            before_ptr, after_ptr,
13876            "write-into must preserve the output's buffer identity (device address)"
13877        );
13878
13879        let new_bytes = {
13880            let g = dst_arc.read().unwrap();
13881            let BackendStorage::Cuda(c) = &g.inner else {
13882                panic!("not cuda")
13883            };
13884            c.to_cpu_bytes().expect("d2h new")
13885        };
13886
13887        // Independently reproduce the OLD allocate-and-replace behavior
13888        // (`slot_copy_to_new`) from the SAME source, for comparison.
13889        let old_bytes = {
13890            let g = src_arc.read().unwrap();
13891            let BackendStorage::Cuda(c) = &g.inner else {
13892                panic!("not cuda")
13893            };
13894            let copied = c
13895                .slot_copy_to_new(0, c.len_bytes())
13896                .expect("slot_copy_to_new (old allocate-and-replace path)");
13897            copied.to_cpu_bytes().expect("d2h old")
13898        };
13899
13900        assert_eq!(
13901            new_bytes, old_bytes,
13902            "write-into result must byte-match the old slot_copy_to_new result"
13903        );
13904        assert_eq!(new_bytes, src_bytes, "and both must match the source bytes");
13905    }
13906}