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(crate) 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    }
2581}
2582
2583/// Dispatch wrapper for `(QMatMul, F32, Cpu)`. Two inputs:
2584/// activations (F32) and quantized weight bytes (U32-typed).
2585/// `OpParams::QMatMul` carries the quant_type + (batch, m, n, k);
2586/// the wrapper picks the right typed kernel based on quant_type.
2587///
2588/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the linear-quant fused
2589/// bundle's `qmatmul_cpu` `entry_point` symbol to this wrapper
2590/// (`CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`).
2591pub(crate) fn qmatmul_f32_cpu_wrapper(
2592    inputs: &[Arc<RwLock<Storage>>],
2593    outputs: &mut [Arc<RwLock<Storage>>],
2594    _layouts: &[Layout],
2595    params: &OpParams,
2596) -> Result<()> {
2597    if inputs.len() != 2 {
2598        return Err(Error::Msg(format!(
2599            "qmatmul wrapper expects 2 inputs (activations, weight_bytes), got {}",
2600            inputs.len(),
2601        ))
2602        .bt());
2603    }
2604    if outputs.len() != 1 {
2605        return Err(Error::Msg(format!(
2606            "qmatmul wrapper expects 1 output, got {}",
2607            outputs.len(),
2608        ))
2609        .bt());
2610    }
2611    let (quant_type, batch_count, m, n, k) = match params {
2612        OpParams::QMatMul {
2613            quant_type,
2614            batch_count,
2615            m,
2616            n,
2617            k,
2618        } => (*quant_type, *batch_count, *m, *n, *k),
2619        other => {
2620            return Err(Error::Msg(format!(
2621                "qmatmul wrapper expects OpParams::QMatMul, got {other:?}",
2622            ))
2623            .bt());
2624        }
2625    };
2626    let act_guard = read_storage(&inputs[0])?;
2627    let w_guard = read_storage(&inputs[1])?;
2628    if w_guard.dtype != DType::U32 {
2629        return Err(Error::Msg(format!(
2630            "qmatmul: weight bytes must be U32-typed (raw block stream), got {:?}",
2631            w_guard.dtype,
2632        ))
2633        .bt());
2634    }
2635    let mut out_guard = write_storage(&outputs[0])?;
2636    let act_cpu = cpu_input(&act_guard)?;
2637    let w_cpu = cpu_input(&w_guard)?;
2638    let out_cpu = cpu_output(&mut out_guard)?;
2639    qmatmul_cpu_by_type(quant_type, act_cpu, w_cpu, out_cpu, batch_count, m, n, k)
2640}
2641
2642/// Dispatch wrapper for `(WriteSlice, *, Cpu)`. Dtype-agnostic — the
2643/// underlying kernel is `write_slice_cpu(... dtype_size)`. The wrapper
2644/// reads dtype_size from the output (dest) Storage's dtype tag. Takes
2645/// 1 input (source) + 1 output (dest, mutated in place); the slab
2646/// offset rides in `OpParams::WriteSlice`. `pub(crate)` so the
2647/// shape-ops FKC contract can resolve its `write_slice_cpu` entry point
2648/// to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2649pub(crate) fn write_slice_cpu_wrapper(
2650    inputs: &[Arc<RwLock<Storage>>],
2651    outputs: &mut [Arc<RwLock<Storage>>],
2652    _layouts: &[Layout],
2653    params: &OpParams,
2654) -> Result<()> {
2655    if inputs.len() != 1 || outputs.len() != 1 {
2656        return Err(Error::Msg(format!(
2657            "write_slice wrapper expects 1 input (source) + 1 output (dest), \
2658             got {} + {}",
2659            inputs.len(),
2660            outputs.len(),
2661        ))
2662        .bt());
2663    }
2664    let (dest_shape, ranges) = match params {
2665        OpParams::WriteSlice {
2666            dest_shape, ranges, ..
2667        } => (dest_shape, ranges),
2668        other => {
2669            return Err(Error::Msg(format!(
2670                "write_slice wrapper expects OpParams::WriteSlice, got {other:?}",
2671            ))
2672            .bt());
2673        }
2674    };
2675    let src_guard = read_storage(&inputs[0])?;
2676    let src_cpu = cpu_input(&src_guard)?;
2677    let mut dest_guard = write_storage(&outputs[0])?;
2678    let dtype_size = dest_guard.dtype.size_in_bytes();
2679    let dest_cpu = cpu_output(&mut dest_guard)?;
2680    fuel_cpu_backend::byte_kernels::write_slice_cpu(
2681        src_cpu, dest_cpu, dest_shape, ranges, dtype_size,
2682    )
2683}
2684
2685/// Dispatch wrapper for `(WriteSliceRotating, *, Cpu)`. Same shape
2686/// as `write_slice_cpu_wrapper` plus a second input carrying the
2687/// dynamic position scalar (a runtime U32 operand, NOT part of the
2688/// binding-table lookup key — see `build_lookup_dtypes`). `pub(crate)`
2689/// so the shape-ops FKC contract can resolve its
2690/// `write_slice_rotating_cpu` entry point to this fn via
2691/// [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2692pub(crate) fn write_slice_rotating_cpu_wrapper(
2693    inputs: &[Arc<RwLock<Storage>>],
2694    outputs: &mut [Arc<RwLock<Storage>>],
2695    _layouts: &[Layout],
2696    params: &OpParams,
2697) -> Result<()> {
2698    if inputs.len() != 2 || outputs.len() != 1 {
2699        return Err(Error::Msg(format!(
2700            "write_slice_rotating wrapper expects 2 inputs (source, position) + 1 output (dest), \
2701             got {} + {}",
2702            inputs.len(),
2703            outputs.len(),
2704        ))
2705        .bt());
2706    }
2707    let (dest_shape, axis, modulus, ranges) =
2708        match params {
2709            OpParams::WriteSliceRotating {
2710                dest_shape,
2711                axis,
2712                modulus,
2713                ranges,
2714            } => (dest_shape, *axis, *modulus, ranges),
2715            other => return Err(Error::Msg(format!(
2716                "write_slice_rotating wrapper expects OpParams::WriteSliceRotating, got {other:?}",
2717            ))
2718            .bt()),
2719        };
2720    let src_guard = read_storage(&inputs[0])?;
2721    let src_cpu = cpu_input(&src_guard)?;
2722    let pos_guard = read_storage(&inputs[1])?;
2723    let pos_cpu = cpu_input(&pos_guard)?;
2724    let mut dest_guard = write_storage(&outputs[0])?;
2725    let dtype_size = dest_guard.dtype.size_in_bytes();
2726    let dest_cpu = cpu_output(&mut dest_guard)?;
2727    fuel_cpu_backend::byte_kernels::write_slice_rotating_cpu(
2728        src_cpu, pos_cpu, dest_cpu, dest_shape, axis, modulus, ranges, dtype_size,
2729    )
2730}
2731
2732/// Dispatch wrapper for `(WriteSliceDoff, *, Cpu)`. Like
2733/// `write_slice_rotating_cpu_wrapper` but the second input is a
2734/// rank-0 `I64` offset (the device-resident start on `axis`; read
2735/// host-side here on CPU) and there is no modulus/wrap. `pub(crate)`
2736/// so the shape-ops FKC contract can resolve its `write_slice_doff_cpu`
2737/// entry point to this fn via [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`].
2738pub(crate) fn write_slice_doff_cpu_wrapper(
2739    inputs: &[Arc<RwLock<Storage>>],
2740    outputs: &mut [Arc<RwLock<Storage>>],
2741    _layouts: &[Layout],
2742    params: &OpParams,
2743) -> Result<()> {
2744    if inputs.len() != 2 || outputs.len() != 1 {
2745        return Err(Error::Msg(format!(
2746            "write_slice_doff wrapper expects 2 inputs (source, offset) + 1 output (dest), \
2747             got {} + {}",
2748            inputs.len(),
2749            outputs.len(),
2750        ))
2751        .bt());
2752    }
2753    let (dest_shape, axis, ranges) = match params {
2754        OpParams::WriteSliceDoff {
2755            dest_shape,
2756            axis,
2757            ranges,
2758        } => (dest_shape, *axis, ranges),
2759        other => {
2760            return Err(Error::Msg(format!(
2761                "write_slice_doff wrapper expects OpParams::WriteSliceDoff, got {other:?}",
2762            ))
2763            .bt());
2764        }
2765    };
2766    let src_guard = read_storage(&inputs[0])?;
2767    let src_cpu = cpu_input(&src_guard)?;
2768    let off_guard = read_storage(&inputs[1])?;
2769    let off_cpu = cpu_input(&off_guard)?;
2770    let mut dest_guard = write_storage(&outputs[0])?;
2771    let dtype_size = dest_guard.dtype.size_in_bytes();
2772    let dest_cpu = cpu_output(&mut dest_guard)?;
2773    fuel_cpu_backend::byte_kernels::write_slice_doff_cpu(
2774        src_cpu, off_cpu, dest_cpu, dest_shape, axis, ranges, dtype_size,
2775    )
2776}
2777
2778pub(crate) fn concat_cpu_wrapper(
2779    inputs: &[Arc<RwLock<Storage>>],
2780    outputs: &mut [Arc<RwLock<Storage>>],
2781    _layouts: &[Layout],
2782    params: &OpParams,
2783) -> Result<()> {
2784    if inputs.is_empty() {
2785        return Err(Error::Msg("concat wrapper expects ≥ 1 input, got 0".to_string()).bt());
2786    }
2787    if outputs.len() != 1 {
2788        return Err(Error::Msg(format!(
2789            "concat wrapper expects 1 output, got {}",
2790            outputs.len(),
2791        ))
2792        .bt());
2793    }
2794    let (outer_count, input_dim_sizes, inner_count) = match params {
2795        OpParams::Concat {
2796            outer_count,
2797            input_dim_sizes,
2798            inner_count,
2799            ..
2800        } => (*outer_count, input_dim_sizes, *inner_count),
2801        other => {
2802            return Err(Error::Msg(format!(
2803                "concat wrapper expects OpParams::Concat, got {other:?}",
2804            ))
2805            .bt());
2806        }
2807    };
2808    if input_dim_sizes.len() != inputs.len() {
2809        return Err(Error::Msg(format!(
2810            "concat wrapper: OpParams declares {} inputs but the work item \
2811             carries {}",
2812            input_dim_sizes.len(),
2813            inputs.len(),
2814        ))
2815        .bt());
2816    }
2817    let in_guards: Vec<_> = inputs
2818        .iter()
2819        .map(read_storage)
2820        .collect::<Result<Vec<_>>>()?;
2821    let mut in_cpus: Vec<&fuel_cpu_backend::CpuStorageBytes> = Vec::with_capacity(in_guards.len());
2822    for g in &in_guards {
2823        in_cpus.push(cpu_input(g)?);
2824    }
2825    let mut out_guard = write_storage(&outputs[0])?;
2826    let dtype_size = out_guard.dtype.size_in_bytes();
2827    let out_cpu = cpu_output(&mut out_guard)?;
2828    fuel_cpu_backend::byte_kernels::concat_cpu(
2829        &in_cpus,
2830        out_cpu,
2831        outer_count,
2832        input_dim_sizes,
2833        inner_count,
2834        dtype_size,
2835    )
2836}
2837
2838/// Generate a CPU IndexAdd wrapper. Same shape across all dtypes;
2839/// only the underlying typed kernel differs.
2840macro_rules! cpu_index_add_wrapper {
2841    ($wrapper:ident, $kernel:path, $idx_ck:literal) => {
2842        // `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`) can bind
2843        // these symbols from the indexing contract.
2844        pub(crate) fn $wrapper(
2845            inputs: &[Arc<RwLock<Storage>>],
2846            outputs: &mut [Arc<RwLock<Storage>>],
2847            _layouts: &[Layout],
2848            params: &OpParams,
2849        ) -> Result<()> {
2850            if inputs.len() != 3 || outputs.len() != 1 {
2851                return Err(Error::Msg(format!(
2852                    "{}: expects 3 inputs + 1 output, got {} + {}",
2853                    $idx_ck,
2854                    inputs.len(),
2855                    outputs.len(),
2856                ))
2857                .bt());
2858            }
2859            let (outer_count, base_dim_size, n_indices, inner_count) = match params {
2860                OpParams::IndexAdd {
2861                    outer_count,
2862                    base_dim_size,
2863                    n_indices,
2864                    inner_count,
2865                } => (*outer_count, *base_dim_size, *n_indices, *inner_count),
2866                other => {
2867                    return Err(Error::Msg(format!(
2868                        "{}: expects OpParams::IndexAdd, got {other:?}",
2869                        $idx_ck,
2870                    ))
2871                    .bt())
2872                }
2873            };
2874            let base_guard = read_storage(&inputs[0])?;
2875            let idx_guard = read_storage(&inputs[1])?;
2876            if idx_guard.dtype != DType::U32 {
2877                return Err(Error::Msg(format!("{}: indices must be U32", $idx_ck,)).bt());
2878            }
2879            let src_guard = read_storage(&inputs[2])?;
2880            let mut out_guard = write_storage(&outputs[0])?;
2881            let base_cpu = cpu_input(&base_guard)?;
2882            let idx_cpu = cpu_input(&idx_guard)?;
2883            let src_cpu = cpu_input(&src_guard)?;
2884            let out_cpu = cpu_output(&mut out_guard)?;
2885            $kernel(
2886                base_cpu,
2887                idx_cpu,
2888                src_cpu,
2889                out_cpu,
2890                outer_count,
2891                base_dim_size,
2892                n_indices,
2893                inner_count,
2894            )
2895        }
2896    };
2897}
2898
2899cpu_index_add_wrapper!(
2900    index_add_f64_cpu_wrapper,
2901    fuel_cpu_backend::byte_kernels::index_add_f64,
2902    "index_add_f64"
2903);
2904cpu_index_add_wrapper!(
2905    index_add_bf16_cpu_wrapper,
2906    fuel_cpu_backend::byte_kernels::index_add_bf16,
2907    "index_add_bf16"
2908);
2909cpu_index_add_wrapper!(
2910    index_add_f16_cpu_wrapper,
2911    fuel_cpu_backend::byte_kernels::index_add_f16,
2912    "index_add_f16"
2913);
2914
2915/// Generate a CPU ScatterAdd wrapper.
2916macro_rules! cpu_scatter_add_wrapper {
2917    ($wrapper:ident, $kernel:path, $name_str:literal) => {
2918        // `pub(crate)` so the FKC `CpuLinkRegistry` can bind these symbols.
2919        pub(crate) fn $wrapper(
2920            inputs: &[Arc<RwLock<Storage>>],
2921            outputs: &mut [Arc<RwLock<Storage>>],
2922            _layouts: &[Layout],
2923            params: &OpParams,
2924        ) -> Result<()> {
2925            if inputs.len() != 3 || outputs.len() != 1 {
2926                return Err(Error::Msg(format!(
2927                    "{}: expects 3 inputs + 1 output, got {} + {}",
2928                    $name_str,
2929                    inputs.len(),
2930                    outputs.len(),
2931                ))
2932                .bt());
2933            }
2934            let (base_shape, src_shape, dim) = match params {
2935                OpParams::ScatterAdd {
2936                    base_shape,
2937                    src_shape,
2938                    dim,
2939                } => (base_shape, src_shape, *dim),
2940                other => {
2941                    return Err(Error::Msg(format!(
2942                        "{}: expects OpParams::ScatterAdd, got {other:?}",
2943                        $name_str,
2944                    ))
2945                    .bt())
2946                }
2947            };
2948            let base_guard = read_storage(&inputs[0])?;
2949            let idx_guard = read_storage(&inputs[1])?;
2950            if idx_guard.dtype != DType::U32 {
2951                return Err(Error::Msg(format!("{}: indices must be U32", $name_str,)).bt());
2952            }
2953            let src_guard = read_storage(&inputs[2])?;
2954            let mut out_guard = write_storage(&outputs[0])?;
2955            let base_cpu = cpu_input(&base_guard)?;
2956            let idx_cpu = cpu_input(&idx_guard)?;
2957            let src_cpu = cpu_input(&src_guard)?;
2958            let out_cpu = cpu_output(&mut out_guard)?;
2959            $kernel(
2960                base_cpu, idx_cpu, src_cpu, out_cpu, base_shape, src_shape, dim,
2961            )
2962        }
2963    };
2964}
2965
2966cpu_scatter_add_wrapper!(
2967    scatter_add_f64_cpu_wrapper,
2968    fuel_cpu_backend::byte_kernels::scatter_add_f64,
2969    "scatter_add_f64"
2970);
2971cpu_scatter_add_wrapper!(
2972    scatter_add_bf16_cpu_wrapper,
2973    fuel_cpu_backend::byte_kernels::scatter_add_bf16,
2974    "scatter_add_bf16"
2975);
2976cpu_scatter_add_wrapper!(
2977    scatter_add_f16_cpu_wrapper,
2978    fuel_cpu_backend::byte_kernels::scatter_add_f16,
2979    "scatter_add_f16"
2980);
2981
2982/// Build a CPU Affine wrapper for any element type. Cast from f64
2983/// scalars in OpParams::Affine to the target arithmetic type
2984/// happens inside the macro (different cast for f64 vs half).
2985macro_rules! cpu_affine_wrapper_native {
2986    ($wrapper:ident, $kernel:path, $T:ty) => {
2987        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
2988        // real production wrapper for the affine-clamp-powi contract import.
2989        pub(crate) fn $wrapper(
2990            inputs: &[Arc<RwLock<Storage>>],
2991            outputs: &mut [Arc<RwLock<Storage>>],
2992            _layouts: &[Layout],
2993            params: &OpParams,
2994        ) -> Result<()> {
2995            if inputs.len() != 1 || outputs.len() != 1 {
2996                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
2997            }
2998            let (mul, add) = match params {
2999                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3000                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3001            };
3002            let in_guard = read_storage(&inputs[0])?;
3003            let mut out_guard = write_storage(&outputs[0])?;
3004            let in_cpu = cpu_input(&in_guard)?;
3005            let out_cpu = cpu_output(&mut out_guard)?;
3006            $kernel(in_cpu, out_cpu, mul, add)
3007        }
3008    };
3009}
3010
3011cpu_affine_wrapper_native!(
3012    affine_f64_cpu_wrapper,
3013    fuel_cpu_backend::byte_kernels::affine_f64,
3014    f64
3015);
3016
3017macro_rules! cpu_affine_wrapper_half {
3018    ($wrapper:ident, $kernel:path) => {
3019        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3020        // real production wrapper for the affine-clamp-powi contract import.
3021        pub(crate) fn $wrapper(
3022            inputs: &[Arc<RwLock<Storage>>],
3023            outputs: &mut [Arc<RwLock<Storage>>],
3024            _layouts: &[Layout],
3025            params: &OpParams,
3026        ) -> Result<()> {
3027            if inputs.len() != 1 || outputs.len() != 1 {
3028                return Err(Error::Msg("affine: 1 input + 1 output".to_string()).bt());
3029            }
3030            let (mul, add) = match params {
3031                OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3032                other => return Err(Error::Msg(format!("affine: bad params {other:?}")).bt()),
3033            };
3034            let in_guard = read_storage(&inputs[0])?;
3035            let mut out_guard = write_storage(&outputs[0])?;
3036            let in_cpu = cpu_input(&in_guard)?;
3037            let out_cpu = cpu_output(&mut out_guard)?;
3038            $kernel(in_cpu, out_cpu, mul, add)
3039        }
3040    };
3041}
3042
3043cpu_affine_wrapper_half!(
3044    affine_bf16_cpu_wrapper,
3045    fuel_cpu_backend::byte_kernels::affine_bf16
3046);
3047cpu_affine_wrapper_half!(
3048    affine_f16_cpu_wrapper,
3049    fuel_cpu_backend::byte_kernels::affine_f16
3050);
3051
3052macro_rules! cpu_clamp_wrapper {
3053    ($wrapper:ident, $kernel:path, $T:ty) => {
3054        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3055        // real production wrapper for the affine-clamp-powi contract import.
3056        pub(crate) fn $wrapper(
3057            inputs: &[Arc<RwLock<Storage>>],
3058            outputs: &mut [Arc<RwLock<Storage>>],
3059            _layouts: &[Layout],
3060            params: &OpParams,
3061        ) -> Result<()> {
3062            if inputs.len() != 1 || outputs.len() != 1 {
3063                return Err(Error::Msg("clamp: 1 input + 1 output".to_string()).bt());
3064            }
3065            let (min, max) = match params {
3066                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3067                other => return Err(Error::Msg(format!("clamp: bad params {other:?}")).bt()),
3068            };
3069            let in_guard = read_storage(&inputs[0])?;
3070            let mut out_guard = write_storage(&outputs[0])?;
3071            let in_cpu = cpu_input(&in_guard)?;
3072            let out_cpu = cpu_output(&mut out_guard)?;
3073            $kernel(in_cpu, out_cpu, min, max)
3074        }
3075    };
3076}
3077
3078cpu_clamp_wrapper!(
3079    clamp_f64_cpu_wrapper,
3080    fuel_cpu_backend::byte_kernels::clamp_f64,
3081    f64
3082);
3083cpu_clamp_wrapper!(
3084    clamp_bf16_cpu_wrapper,
3085    fuel_cpu_backend::byte_kernels::clamp_bf16,
3086    f32
3087);
3088cpu_clamp_wrapper!(
3089    clamp_f16_cpu_wrapper,
3090    fuel_cpu_backend::byte_kernels::clamp_f16,
3091    f32
3092);
3093
3094macro_rules! cpu_powi_wrapper {
3095    ($wrapper:ident, $kernel:path) => {
3096        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3097        // real production wrapper for the affine-clamp-powi contract import.
3098        pub(crate) fn $wrapper(
3099            inputs: &[Arc<RwLock<Storage>>],
3100            outputs: &mut [Arc<RwLock<Storage>>],
3101            _layouts: &[Layout],
3102            params: &OpParams,
3103        ) -> Result<()> {
3104            if inputs.len() != 1 || outputs.len() != 1 {
3105                return Err(Error::Msg("powi: 1 input + 1 output".to_string()).bt());
3106            }
3107            let exp = match params {
3108                OpParams::PowI { exp } => *exp,
3109                other => return Err(Error::Msg(format!("powi: bad params {other:?}")).bt()),
3110            };
3111            let in_guard = read_storage(&inputs[0])?;
3112            let mut out_guard = write_storage(&outputs[0])?;
3113            let in_cpu = cpu_input(&in_guard)?;
3114            let out_cpu = cpu_output(&mut out_guard)?;
3115            $kernel(in_cpu, out_cpu, exp)
3116        }
3117    };
3118}
3119
3120cpu_powi_wrapper!(
3121    powi_f64_cpu_wrapper,
3122    fuel_cpu_backend::byte_kernels::powi_f64
3123);
3124cpu_powi_wrapper!(
3125    powi_bf16_cpu_wrapper,
3126    fuel_cpu_backend::byte_kernels::powi_bf16
3127);
3128cpu_powi_wrapper!(
3129    powi_f16_cpu_wrapper,
3130    fuel_cpu_backend::byte_kernels::powi_f16
3131);
3132
3133// ArgMax/ArgMin per-input-dtype wrappers. The existing
3134// `cpu_arg_dim_wrapper!` macro hardcodes F32 input — generalize it
3135// for non-F32 input dtypes.
3136macro_rules! cpu_arg_dim_wrapper_typed {
3137    ($wrapper:ident, $kernel:path, $expected_in_dtype:expr, $op_name:literal) => {
3138        fn $wrapper(
3139            inputs: &[Arc<RwLock<Storage>>],
3140            outputs: &mut [Arc<RwLock<Storage>>],
3141            layouts: &[Layout],
3142            params: &OpParams,
3143        ) -> Result<()> {
3144            if inputs.len() != 1 || outputs.len() != 1 {
3145                return Err(Error::Msg(format!("{}: 1 input + 1 output", $op_name,)).bt());
3146            }
3147            let dims = match params {
3148                OpParams::Reduce { dims, .. } => dims,
3149                other => {
3150                    return Err(Error::Msg(format!(
3151                        "{}: expects OpParams::Reduce, got {other:?}",
3152                        $op_name,
3153                    ))
3154                    .bt())
3155                }
3156            };
3157            if dims.len() != 1 {
3158                return Err(Error::Msg(format!(
3159                    "{}: expects exactly 1 reduce dim, got {dims:?}",
3160                    $op_name,
3161                ))
3162                .bt());
3163            }
3164            let dim = dims[0];
3165            let input_layout = layouts.first().ok_or_else(|| {
3166                Error::Msg(format!(
3167                    "{}: layouts empty (executor must pass input layout at [0])",
3168                    $op_name,
3169                ))
3170                .bt()
3171            })?;
3172            let in_guard = read_storage(&inputs[0])?;
3173            if in_guard.dtype != $expected_in_dtype {
3174                return Err(Error::Msg(format!(
3175                    "{}: expects input dtype {:?}, got {:?}",
3176                    $op_name, $expected_in_dtype, in_guard.dtype,
3177                ))
3178                .bt());
3179            }
3180            let mut out_guard = write_storage(&outputs[0])?;
3181            let in_cpu = cpu_input(&in_guard)?;
3182            let out_cpu = cpu_output(&mut out_guard)?;
3183            $kernel(in_cpu, out_cpu, input_layout.shape().dims(), dim)
3184        }
3185    };
3186}
3187
3188// New ArgMax/ArgMin entries are keyed on output U32 like the
3189// existing ones, but we need separate wrappers per input dtype.
3190// Use a dispatch macro that combines them.
3191fn argmax_dim_u32_cpu_dispatch(
3192    inputs: &[Arc<RwLock<Storage>>],
3193    outputs: &mut [Arc<RwLock<Storage>>],
3194    _layouts: &[Layout],
3195    params: &OpParams,
3196) -> Result<()> {
3197    let in_dtype = read_storage(&inputs[0])?.dtype;
3198    match in_dtype {
3199        DType::F32 => argmax_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3200        DType::F64 => argmax_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3201        DType::BF16 => argmax_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3202        DType::F16 => argmax_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3203        other => Err(Error::Msg(format!("argmax_dim: unsupported input dtype {other:?}",)).bt()),
3204    }
3205}
3206
3207fn argmin_dim_u32_cpu_dispatch(
3208    inputs: &[Arc<RwLock<Storage>>],
3209    outputs: &mut [Arc<RwLock<Storage>>],
3210    _layouts: &[Layout],
3211    params: &OpParams,
3212) -> Result<()> {
3213    let in_dtype = read_storage(&inputs[0])?.dtype;
3214    match in_dtype {
3215        DType::F32 => argmin_dim_u32_cpu_wrapper(inputs, outputs, _layouts, params),
3216        DType::F64 => argmin_dim_f64_only_wrapper(inputs, outputs, _layouts, params),
3217        DType::BF16 => argmin_dim_bf16_only_wrapper(inputs, outputs, _layouts, params),
3218        DType::F16 => argmin_dim_f16_only_wrapper(inputs, outputs, _layouts, params),
3219        other => Err(Error::Msg(format!("argmin_dim: unsupported input dtype {other:?}",)).bt()),
3220    }
3221}
3222
3223cpu_arg_dim_wrapper_typed!(
3224    argmax_dim_f64_only_wrapper,
3225    fuel_cpu_backend::byte_kernels::argmax_dim_f64,
3226    DType::F64,
3227    "argmax_dim_f64"
3228);
3229cpu_arg_dim_wrapper_typed!(
3230    argmin_dim_f64_only_wrapper,
3231    fuel_cpu_backend::byte_kernels::argmin_dim_f64,
3232    DType::F64,
3233    "argmin_dim_f64"
3234);
3235cpu_arg_dim_wrapper_typed!(
3236    argmax_dim_bf16_only_wrapper,
3237    fuel_cpu_backend::byte_kernels::argmax_dim_bf16,
3238    DType::BF16,
3239    "argmax_dim_bf16"
3240);
3241cpu_arg_dim_wrapper_typed!(
3242    argmin_dim_bf16_only_wrapper,
3243    fuel_cpu_backend::byte_kernels::argmin_dim_bf16,
3244    DType::BF16,
3245    "argmin_dim_bf16"
3246);
3247cpu_arg_dim_wrapper_typed!(
3248    argmax_dim_f16_only_wrapper,
3249    fuel_cpu_backend::byte_kernels::argmax_dim_f16,
3250    DType::F16,
3251    "argmax_dim_f16"
3252);
3253cpu_arg_dim_wrapper_typed!(
3254    argmin_dim_f16_only_wrapper,
3255    fuel_cpu_backend::byte_kernels::argmin_dim_f16,
3256    DType::F16,
3257    "argmin_dim_f16"
3258);
3259
3260/// Dispatch wrapper for `(Affine, F32, Cpu)`. Extracts scalar
3261/// coefficients from `OpParams::Affine`.
3262pub(crate) fn affine_f32_cpu_wrapper(
3263    inputs: &[Arc<RwLock<Storage>>],
3264    outputs: &mut [Arc<RwLock<Storage>>],
3265    _layouts: &[Layout],
3266    params: &OpParams,
3267) -> Result<()> {
3268    if inputs.len() != 1 || outputs.len() != 1 {
3269        return Err(Error::Msg(format!(
3270            "affine wrapper expects 1 input + 1 output, got {} + {}",
3271            inputs.len(),
3272            outputs.len(),
3273        ))
3274        .bt());
3275    }
3276    let (mul, add) = match params {
3277        OpParams::Affine { mul, add } => (*mul as f32, *add as f32),
3278        other => {
3279            return Err(Error::Msg(format!(
3280                "affine wrapper expects OpParams::Affine, got {other:?}",
3281            ))
3282            .bt());
3283        }
3284    };
3285    let in_guard = read_storage(&inputs[0])?;
3286    let mut out_guard = write_storage(&outputs[0])?;
3287    let in_cpu = cpu_input(&in_guard)?;
3288    let out_cpu = cpu_output(&mut out_guard)?;
3289    fuel_cpu_backend::byte_kernels::affine_f32(in_cpu, out_cpu, mul, add)
3290}
3291
3292/// Dispatch wrapper macro for in-place affine on CPU. Inputs is
3293/// empty (the executor's `WorkItemKind::InplaceKernel` arm passes the
3294/// target Arc as `outputs[0]`); the kernel reads + writes through the
3295/// single write lock.
3296macro_rules! cpu_affine_inplace_wrapper {
3297    ($name:ident, $kernel:ident, $T:ty) => {
3298        pub(crate) fn $name(
3299            inputs: &[Arc<RwLock<Storage>>],
3300            outputs: &mut [Arc<RwLock<Storage>>],
3301            _layouts: &[Layout],
3302            params: &OpParams,
3303        ) -> Result<()> {
3304            if !inputs.is_empty() || outputs.len() != 1 {
3305                return Err(Error::Msg(format!(
3306                    concat!(
3307                        stringify!($name),
3308                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3309                    ),
3310                    inputs.len(),
3311                    outputs.len(),
3312                ))
3313                .bt());
3314            }
3315            let (mul, add) = match params {
3316                OpParams::Affine { mul, add } => (*mul as $T, *add as $T),
3317                other => {
3318                    return Err(Error::Msg(format!(
3319                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3320                        other,
3321                    ))
3322                    .bt())
3323                }
3324            };
3325            let mut out_guard = write_storage(&outputs[0])?;
3326            let out_cpu = cpu_output(&mut out_guard)?;
3327            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3328        }
3329    };
3330    ($name:ident, $kernel:ident, $T:ty, half) => {
3331        pub(crate) fn $name(
3332            inputs: &[Arc<RwLock<Storage>>],
3333            outputs: &mut [Arc<RwLock<Storage>>],
3334            _layouts: &[Layout],
3335            params: &OpParams,
3336        ) -> Result<()> {
3337            if !inputs.is_empty() || outputs.len() != 1 {
3338                return Err(Error::Msg(format!(
3339                    concat!(
3340                        stringify!($name),
3341                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3342                    ),
3343                    inputs.len(),
3344                    outputs.len(),
3345                ))
3346                .bt());
3347            }
3348            let (mul, add) = match params {
3349                OpParams::Affine { mul, add } => (*mul, *add),
3350                other => {
3351                    return Err(Error::Msg(format!(
3352                        concat!(stringify!($name), ": expected OpParams::Affine, got {:?}"),
3353                        other,
3354                    ))
3355                    .bt())
3356                }
3357            };
3358            let mut out_guard = write_storage(&outputs[0])?;
3359            let out_cpu = cpu_output(&mut out_guard)?;
3360            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, mul, add)
3361        }
3362    };
3363}
3364
3365cpu_affine_inplace_wrapper!(inplace_affine_f32_cpu_wrapper, affine_inplace_f32, f32);
3366cpu_affine_inplace_wrapper!(inplace_affine_f64_cpu_wrapper, affine_inplace_f64, f64);
3367cpu_affine_inplace_wrapper!(
3368    inplace_affine_bf16_cpu_wrapper,
3369    affine_inplace_bf16,
3370    f64,
3371    half
3372);
3373cpu_affine_inplace_wrapper!(
3374    inplace_affine_f16_cpu_wrapper,
3375    affine_inplace_f16,
3376    f64,
3377    half
3378);
3379
3380/// Dispatch wrapper macro for in-place clamp on CPU. Same shape as
3381/// `cpu_affine_inplace_wrapper!` (no inputs, target as outputs[0]),
3382/// but pulls `(min, max)` from `OpParams::Clamp`.
3383macro_rules! cpu_clamp_inplace_wrapper {
3384    ($name:ident, $kernel:ident, $T:ty) => {
3385        pub(crate) fn $name(
3386            inputs: &[Arc<RwLock<Storage>>],
3387            outputs: &mut [Arc<RwLock<Storage>>],
3388            _layouts: &[Layout],
3389            params: &OpParams,
3390        ) -> Result<()> {
3391            if !inputs.is_empty() || outputs.len() != 1 {
3392                return Err(Error::Msg(format!(
3393                    concat!(
3394                        stringify!($name),
3395                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3396                    ),
3397                    inputs.len(),
3398                    outputs.len(),
3399                ))
3400                .bt());
3401            }
3402            let (min, max) = match params {
3403                OpParams::Clamp { min, max } => (*min as $T, *max as $T),
3404                other => {
3405                    return Err(Error::Msg(format!(
3406                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3407                        other,
3408                    ))
3409                    .bt())
3410                }
3411            };
3412            let mut out_guard = write_storage(&outputs[0])?;
3413            let out_cpu = cpu_output(&mut out_guard)?;
3414            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3415        }
3416    };
3417    ($name:ident, $kernel:ident, $T:ty, half) => {
3418        pub(crate) fn $name(
3419            inputs: &[Arc<RwLock<Storage>>],
3420            outputs: &mut [Arc<RwLock<Storage>>],
3421            _layouts: &[Layout],
3422            params: &OpParams,
3423        ) -> Result<()> {
3424            if !inputs.is_empty() || outputs.len() != 1 {
3425                return Err(Error::Msg(format!(
3426                    concat!(
3427                        stringify!($name),
3428                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3429                    ),
3430                    inputs.len(),
3431                    outputs.len(),
3432                ))
3433                .bt());
3434            }
3435            let (min, max) = match params {
3436                OpParams::Clamp { min, max } => (*min, *max),
3437                other => {
3438                    return Err(Error::Msg(format!(
3439                        concat!(stringify!($name), ": expected OpParams::Clamp, got {:?}"),
3440                        other,
3441                    ))
3442                    .bt())
3443                }
3444            };
3445            let mut out_guard = write_storage(&outputs[0])?;
3446            let out_cpu = cpu_output(&mut out_guard)?;
3447            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, min, max)
3448        }
3449    };
3450}
3451
3452cpu_clamp_inplace_wrapper!(clamp_inplace_f32_cpu_wrapper, clamp_inplace_f32, f32);
3453cpu_clamp_inplace_wrapper!(clamp_inplace_f64_cpu_wrapper, clamp_inplace_f64, f64);
3454cpu_clamp_inplace_wrapper!(
3455    clamp_inplace_bf16_cpu_wrapper,
3456    clamp_inplace_bf16,
3457    f64,
3458    half
3459);
3460cpu_clamp_inplace_wrapper!(clamp_inplace_f16_cpu_wrapper, clamp_inplace_f16, f64, half);
3461
3462/// Dispatch wrapper macro for in-place powi on CPU. Pulls `exp` from
3463/// `OpParams::PowI`.
3464macro_rules! cpu_powi_inplace_wrapper {
3465    ($name:ident, $kernel:ident) => {
3466        pub(crate) fn $name(
3467            inputs: &[Arc<RwLock<Storage>>],
3468            outputs: &mut [Arc<RwLock<Storage>>],
3469            _layouts: &[Layout],
3470            params: &OpParams,
3471        ) -> Result<()> {
3472            if !inputs.is_empty() || outputs.len() != 1 {
3473                return Err(Error::Msg(format!(
3474                    concat!(
3475                        stringify!($name),
3476                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3477                    ),
3478                    inputs.len(),
3479                    outputs.len(),
3480                ))
3481                .bt());
3482            }
3483            let exp = match params {
3484                OpParams::PowI { exp } => *exp,
3485                other => {
3486                    return Err(Error::Msg(format!(
3487                        concat!(stringify!($name), ": expected OpParams::PowI, got {:?}"),
3488                        other,
3489                    ))
3490                    .bt())
3491                }
3492            };
3493            let mut out_guard = write_storage(&outputs[0])?;
3494            let out_cpu = cpu_output(&mut out_guard)?;
3495            fuel_cpu_backend::byte_kernels::$kernel(out_cpu, exp)
3496        }
3497    };
3498}
3499
3500cpu_powi_inplace_wrapper!(powi_inplace_f32_cpu_wrapper, powi_inplace_f32);
3501cpu_powi_inplace_wrapper!(powi_inplace_f64_cpu_wrapper, powi_inplace_f64);
3502cpu_powi_inplace_wrapper!(powi_inplace_bf16_cpu_wrapper, powi_inplace_bf16);
3503cpu_powi_inplace_wrapper!(powi_inplace_f16_cpu_wrapper, powi_inplace_f16);
3504
3505/// Dispatch wrapper macro for in-place elementwise unary ops on CPU.
3506/// Same shape as `cpu_affine_inplace_wrapper!` (inputs empty, target
3507/// adopted as outputs[0] by the executor), but the kernel takes no
3508/// scalar params — just the target buffer.
3509macro_rules! cpu_unary_inplace_wrapper {
3510    ($name:ident, $kernel:ident) => {
3511        pub(crate) fn $name(
3512            inputs: &[Arc<RwLock<Storage>>],
3513            outputs: &mut [Arc<RwLock<Storage>>],
3514            _layouts: &[Layout],
3515            _params: &OpParams,
3516        ) -> Result<()> {
3517            if !inputs.is_empty() || outputs.len() != 1 {
3518                return Err(Error::Msg(format!(
3519                    concat!(
3520                        stringify!($name),
3521                        ": expected 0 inputs + 1 output (target adopted by executor), got {} + {}"
3522                    ),
3523                    inputs.len(),
3524                    outputs.len(),
3525                ))
3526                .bt());
3527            }
3528            let mut out_guard = write_storage(&outputs[0])?;
3529            let out_cpu = cpu_output(&mut out_guard)?;
3530            fuel_cpu_backend::byte_kernels::$kernel(out_cpu)
3531        }
3532    };
3533}
3534
3535cpu_unary_inplace_wrapper!(relu_inplace_f32_cpu_wrapper, relu_inplace_f32);
3536cpu_unary_inplace_wrapper!(silu_inplace_f32_cpu_wrapper, silu_inplace_f32);
3537cpu_unary_inplace_wrapper!(gelu_inplace_f32_cpu_wrapper, gelu_inplace_f32);
3538cpu_unary_inplace_wrapper!(tanh_inplace_f32_cpu_wrapper, tanh_inplace_f32);
3539cpu_unary_inplace_wrapper!(sigmoid_inplace_f32_cpu_wrapper, sigmoid_inplace_f32);
3540
3541cpu_unary_inplace_wrapper!(relu_inplace_f64_cpu_wrapper, relu_inplace_f64);
3542cpu_unary_inplace_wrapper!(silu_inplace_f64_cpu_wrapper, silu_inplace_f64);
3543cpu_unary_inplace_wrapper!(gelu_inplace_f64_cpu_wrapper, gelu_inplace_f64);
3544cpu_unary_inplace_wrapper!(tanh_inplace_f64_cpu_wrapper, tanh_inplace_f64);
3545cpu_unary_inplace_wrapper!(sigmoid_inplace_f64_cpu_wrapper, sigmoid_inplace_f64);
3546
3547cpu_unary_inplace_wrapper!(relu_inplace_bf16_cpu_wrapper, relu_inplace_bf16);
3548cpu_unary_inplace_wrapper!(silu_inplace_bf16_cpu_wrapper, silu_inplace_bf16);
3549cpu_unary_inplace_wrapper!(gelu_inplace_bf16_cpu_wrapper, gelu_inplace_bf16);
3550cpu_unary_inplace_wrapper!(tanh_inplace_bf16_cpu_wrapper, tanh_inplace_bf16);
3551cpu_unary_inplace_wrapper!(sigmoid_inplace_bf16_cpu_wrapper, sigmoid_inplace_bf16);
3552
3553cpu_unary_inplace_wrapper!(relu_inplace_f16_cpu_wrapper, relu_inplace_f16);
3554cpu_unary_inplace_wrapper!(silu_inplace_f16_cpu_wrapper, silu_inplace_f16);
3555cpu_unary_inplace_wrapper!(gelu_inplace_f16_cpu_wrapper, gelu_inplace_f16);
3556cpu_unary_inplace_wrapper!(tanh_inplace_f16_cpu_wrapper, tanh_inplace_f16);
3557cpu_unary_inplace_wrapper!(sigmoid_inplace_f16_cpu_wrapper, sigmoid_inplace_f16);
3558
3559// In-place unary op family expansion (2026-05-30) — 16 new ops × 4
3560// dtypes. Each wrapper is identical in shape to the original 5-op
3561// starter set; the chassis handles per-dtype math.
3562cpu_unary_inplace_wrapper!(neg_inplace_f32_cpu_wrapper, neg_inplace_f32);
3563cpu_unary_inplace_wrapper!(neg_inplace_f64_cpu_wrapper, neg_inplace_f64);
3564cpu_unary_inplace_wrapper!(neg_inplace_bf16_cpu_wrapper, neg_inplace_bf16);
3565cpu_unary_inplace_wrapper!(neg_inplace_f16_cpu_wrapper, neg_inplace_f16);
3566
3567cpu_unary_inplace_wrapper!(abs_inplace_f32_cpu_wrapper, abs_inplace_f32);
3568cpu_unary_inplace_wrapper!(abs_inplace_f64_cpu_wrapper, abs_inplace_f64);
3569cpu_unary_inplace_wrapper!(abs_inplace_bf16_cpu_wrapper, abs_inplace_bf16);
3570cpu_unary_inplace_wrapper!(abs_inplace_f16_cpu_wrapper, abs_inplace_f16);
3571
3572cpu_unary_inplace_wrapper!(sqr_inplace_f32_cpu_wrapper, sqr_inplace_f32);
3573cpu_unary_inplace_wrapper!(sqr_inplace_f64_cpu_wrapper, sqr_inplace_f64);
3574cpu_unary_inplace_wrapper!(sqr_inplace_bf16_cpu_wrapper, sqr_inplace_bf16);
3575cpu_unary_inplace_wrapper!(sqr_inplace_f16_cpu_wrapper, sqr_inplace_f16);
3576
3577cpu_unary_inplace_wrapper!(sqrt_inplace_f32_cpu_wrapper, sqrt_inplace_f32);
3578cpu_unary_inplace_wrapper!(sqrt_inplace_f64_cpu_wrapper, sqrt_inplace_f64);
3579cpu_unary_inplace_wrapper!(sqrt_inplace_bf16_cpu_wrapper, sqrt_inplace_bf16);
3580cpu_unary_inplace_wrapper!(sqrt_inplace_f16_cpu_wrapper, sqrt_inplace_f16);
3581
3582cpu_unary_inplace_wrapper!(rsqrt_inplace_f32_cpu_wrapper, rsqrt_inplace_f32);
3583cpu_unary_inplace_wrapper!(rsqrt_inplace_f64_cpu_wrapper, rsqrt_inplace_f64);
3584cpu_unary_inplace_wrapper!(rsqrt_inplace_bf16_cpu_wrapper, rsqrt_inplace_bf16);
3585cpu_unary_inplace_wrapper!(rsqrt_inplace_f16_cpu_wrapper, rsqrt_inplace_f16);
3586
3587cpu_unary_inplace_wrapper!(recip_inplace_f32_cpu_wrapper, recip_inplace_f32);
3588cpu_unary_inplace_wrapper!(recip_inplace_f64_cpu_wrapper, recip_inplace_f64);
3589cpu_unary_inplace_wrapper!(recip_inplace_bf16_cpu_wrapper, recip_inplace_bf16);
3590cpu_unary_inplace_wrapper!(recip_inplace_f16_cpu_wrapper, recip_inplace_f16);
3591
3592cpu_unary_inplace_wrapper!(exp_inplace_f32_cpu_wrapper, exp_inplace_f32);
3593cpu_unary_inplace_wrapper!(exp_inplace_f64_cpu_wrapper, exp_inplace_f64);
3594cpu_unary_inplace_wrapper!(exp_inplace_bf16_cpu_wrapper, exp_inplace_bf16);
3595cpu_unary_inplace_wrapper!(exp_inplace_f16_cpu_wrapper, exp_inplace_f16);
3596
3597cpu_unary_inplace_wrapper!(log_inplace_f32_cpu_wrapper, log_inplace_f32);
3598cpu_unary_inplace_wrapper!(log_inplace_f64_cpu_wrapper, log_inplace_f64);
3599cpu_unary_inplace_wrapper!(log_inplace_bf16_cpu_wrapper, log_inplace_bf16);
3600cpu_unary_inplace_wrapper!(log_inplace_f16_cpu_wrapper, log_inplace_f16);
3601
3602cpu_unary_inplace_wrapper!(sin_inplace_f32_cpu_wrapper, sin_inplace_f32);
3603cpu_unary_inplace_wrapper!(sin_inplace_f64_cpu_wrapper, sin_inplace_f64);
3604cpu_unary_inplace_wrapper!(sin_inplace_bf16_cpu_wrapper, sin_inplace_bf16);
3605cpu_unary_inplace_wrapper!(sin_inplace_f16_cpu_wrapper, sin_inplace_f16);
3606
3607cpu_unary_inplace_wrapper!(cos_inplace_f32_cpu_wrapper, cos_inplace_f32);
3608cpu_unary_inplace_wrapper!(cos_inplace_f64_cpu_wrapper, cos_inplace_f64);
3609cpu_unary_inplace_wrapper!(cos_inplace_bf16_cpu_wrapper, cos_inplace_bf16);
3610cpu_unary_inplace_wrapper!(cos_inplace_f16_cpu_wrapper, cos_inplace_f16);
3611
3612cpu_unary_inplace_wrapper!(sign_inplace_f32_cpu_wrapper, sign_inplace_f32);
3613cpu_unary_inplace_wrapper!(sign_inplace_f64_cpu_wrapper, sign_inplace_f64);
3614cpu_unary_inplace_wrapper!(sign_inplace_bf16_cpu_wrapper, sign_inplace_bf16);
3615cpu_unary_inplace_wrapper!(sign_inplace_f16_cpu_wrapper, sign_inplace_f16);
3616
3617cpu_unary_inplace_wrapper!(floor_inplace_f32_cpu_wrapper, floor_inplace_f32);
3618cpu_unary_inplace_wrapper!(floor_inplace_f64_cpu_wrapper, floor_inplace_f64);
3619cpu_unary_inplace_wrapper!(floor_inplace_bf16_cpu_wrapper, floor_inplace_bf16);
3620cpu_unary_inplace_wrapper!(floor_inplace_f16_cpu_wrapper, floor_inplace_f16);
3621
3622cpu_unary_inplace_wrapper!(ceil_inplace_f32_cpu_wrapper, ceil_inplace_f32);
3623cpu_unary_inplace_wrapper!(ceil_inplace_f64_cpu_wrapper, ceil_inplace_f64);
3624cpu_unary_inplace_wrapper!(ceil_inplace_bf16_cpu_wrapper, ceil_inplace_bf16);
3625cpu_unary_inplace_wrapper!(ceil_inplace_f16_cpu_wrapper, ceil_inplace_f16);
3626
3627cpu_unary_inplace_wrapper!(round_inplace_f32_cpu_wrapper, round_inplace_f32);
3628cpu_unary_inplace_wrapper!(round_inplace_f64_cpu_wrapper, round_inplace_f64);
3629cpu_unary_inplace_wrapper!(round_inplace_bf16_cpu_wrapper, round_inplace_bf16);
3630cpu_unary_inplace_wrapper!(round_inplace_f16_cpu_wrapper, round_inplace_f16);
3631
3632cpu_unary_inplace_wrapper!(erf_inplace_f32_cpu_wrapper, erf_inplace_f32);
3633cpu_unary_inplace_wrapper!(erf_inplace_f64_cpu_wrapper, erf_inplace_f64);
3634cpu_unary_inplace_wrapper!(erf_inplace_bf16_cpu_wrapper, erf_inplace_bf16);
3635cpu_unary_inplace_wrapper!(erf_inplace_f16_cpu_wrapper, erf_inplace_f16);
3636
3637cpu_unary_inplace_wrapper!(gelu_erf_inplace_f32_cpu_wrapper, gelu_erf_inplace_f32);
3638cpu_unary_inplace_wrapper!(gelu_erf_inplace_f64_cpu_wrapper, gelu_erf_inplace_f64);
3639cpu_unary_inplace_wrapper!(gelu_erf_inplace_bf16_cpu_wrapper, gelu_erf_inplace_bf16);
3640cpu_unary_inplace_wrapper!(gelu_erf_inplace_f16_cpu_wrapper, gelu_erf_inplace_f16);
3641
3642/// Dispatch wrapper for `(ClampElementwise, F32, Cpu)`.
3643pub(crate) fn clamp_elementwise_f32_cpu_wrapper(
3644    inputs: &[Arc<RwLock<Storage>>],
3645    outputs: &mut [Arc<RwLock<Storage>>],
3646    _layouts: &[Layout],
3647    params: &OpParams,
3648) -> Result<()> {
3649    if inputs.len() != 1 || outputs.len() != 1 {
3650        return Err(Error::Msg(format!(
3651            "clamp wrapper expects 1 input + 1 output, got {} + {}",
3652            inputs.len(),
3653            outputs.len(),
3654        ))
3655        .bt());
3656    }
3657    let (min, max) = match params {
3658        OpParams::Clamp { min, max } => (*min as f32, *max as f32),
3659        other => {
3660            return Err(Error::Msg(format!(
3661                "clamp wrapper expects OpParams::Clamp, got {other:?}",
3662            ))
3663            .bt());
3664        }
3665    };
3666    let in_guard = read_storage(&inputs[0])?;
3667    let mut out_guard = write_storage(&outputs[0])?;
3668    let in_cpu = cpu_input(&in_guard)?;
3669    let out_cpu = cpu_output(&mut out_guard)?;
3670    fuel_cpu_backend::byte_kernels::clamp_f32(in_cpu, out_cpu, min, max)
3671}
3672
3673/// Dispatch wrapper for `(PowIElementwise, F32, Cpu)`.
3674pub(crate) fn powi_elementwise_f32_cpu_wrapper(
3675    inputs: &[Arc<RwLock<Storage>>],
3676    outputs: &mut [Arc<RwLock<Storage>>],
3677    _layouts: &[Layout],
3678    params: &OpParams,
3679) -> Result<()> {
3680    if inputs.len() != 1 || outputs.len() != 1 {
3681        return Err(Error::Msg(format!(
3682            "powi wrapper expects 1 input + 1 output, got {} + {}",
3683            inputs.len(),
3684            outputs.len(),
3685        ))
3686        .bt());
3687    }
3688    let exp = match params {
3689        OpParams::PowI { exp } => *exp,
3690        other => {
3691            return Err(Error::Msg(format!(
3692                "powi wrapper expects OpParams::PowI, got {other:?}",
3693            ))
3694            .bt());
3695        }
3696    };
3697    let in_guard = read_storage(&inputs[0])?;
3698    let mut out_guard = write_storage(&outputs[0])?;
3699    let in_cpu = cpu_input(&in_guard)?;
3700    let out_cpu = cpu_output(&mut out_guard)?;
3701    fuel_cpu_backend::byte_kernels::powi_f32(in_cpu, out_cpu, exp)
3702}
3703
3704/// Build a `(2 inputs `(x, upstream)`, 1 output, OpParams::PowI)` CPU
3705/// dispatch wrapper for the per-dtype PowIBackward kernels.
3706macro_rules! cpu_powi_backward_wrapper {
3707    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3708        // pub(crate) so the FKC link registry (fkc::cpu_link) can name the
3709        // real production wrapper for the affine-clamp-powi contract import.
3710        pub(crate) fn $wrapper(
3711            inputs: &[Arc<RwLock<Storage>>],
3712            outputs: &mut [Arc<RwLock<Storage>>],
3713            _layouts: &[Layout],
3714            params: &OpParams,
3715        ) -> Result<()> {
3716            if inputs.len() != 2 || outputs.len() != 1 {
3717                return Err(Error::Msg(format!(
3718                    "{} wrapper expects 2 inputs + 1 output, got {} + {}",
3719                    $op_name,
3720                    inputs.len(),
3721                    outputs.len(),
3722                ))
3723                .bt());
3724            }
3725            let exp = match params {
3726                OpParams::PowI { exp } => *exp,
3727                other => {
3728                    return Err(Error::Msg(format!(
3729                        "{} wrapper expects OpParams::PowI, got {other:?}",
3730                        $op_name,
3731                    ))
3732                    .bt())
3733                }
3734            };
3735            let x_guard = read_storage(&inputs[0])?;
3736            let up_guard = read_storage(&inputs[1])?;
3737            let mut out_guard = write_storage(&outputs[0])?;
3738            let x_cpu = cpu_input(&x_guard)?;
3739            let up_cpu = cpu_input(&up_guard)?;
3740            let out_cpu = cpu_output(&mut out_guard)?;
3741            $kernel(x_cpu, up_cpu, out_cpu, exp)
3742        }
3743    };
3744}
3745
3746cpu_powi_backward_wrapper!(
3747    powi_backward_f32_cpu_wrapper,
3748    fuel_cpu_backend::byte_kernels::powi_backward_f32,
3749    "powi_backward_f32"
3750);
3751cpu_powi_backward_wrapper!(
3752    powi_backward_f64_cpu_wrapper,
3753    fuel_cpu_backend::byte_kernels::powi_backward_f64,
3754    "powi_backward_f64"
3755);
3756cpu_powi_backward_wrapper!(
3757    powi_backward_bf16_cpu_wrapper,
3758    fuel_cpu_backend::byte_kernels::powi_backward_bf16,
3759    "powi_backward_bf16"
3760);
3761cpu_powi_backward_wrapper!(
3762    powi_backward_f16_cpu_wrapper,
3763    fuel_cpu_backend::byte_kernels::powi_backward_f16,
3764    "powi_backward_f16"
3765);
3766
3767/// Build a CPU reduction wrapper that calls a typed `(input,
3768/// output, input_shape, dims)` reduce kernel. Verifies the
3769/// `OpParams::Reduce` variant and forwards the shape + dims to the
3770/// kernel.
3771macro_rules! cpu_reduce_wrapper {
3772    ($wrapper:ident, $kernel:path, $op_name:literal) => {
3773        pub(crate) fn $wrapper(
3774            inputs: &[Arc<RwLock<Storage>>],
3775            outputs: &mut [Arc<RwLock<Storage>>],
3776            layouts: &[Layout],
3777            params: &OpParams,
3778        ) -> Result<()> {
3779            if inputs.len() != 1 {
3780                return Err(Error::Msg(format!(
3781                    "{} wrapper expects 1 input, got {}",
3782                    $op_name,
3783                    inputs.len(),
3784                ))
3785                .bt());
3786            }
3787            if outputs.len() != 1 {
3788                return Err(Error::Msg(format!(
3789                    "{} wrapper expects 1 output, got {}",
3790                    $op_name,
3791                    outputs.len(),
3792                ))
3793                .bt());
3794            }
3795            let dims = match params {
3796                OpParams::Reduce { dims, .. } => dims,
3797                other => {
3798                    return Err(Error::Msg(format!(
3799                        "{} wrapper expects OpParams::Reduce, got {:?}",
3800                        $op_name, other,
3801                    ))
3802                    .bt())
3803                }
3804            };
3805            let input_layout = layouts.first().ok_or_else(|| {
3806                Error::Msg(format!(
3807                    "{} wrapper: layouts empty (executor must pass input layout at [0])",
3808                    $op_name,
3809                ))
3810                .bt()
3811            })?;
3812            // The pipelined executor's auto-Contiguize pass
3813            // (stage 4 of Layout-on-Node) materializes contiguous
3814            // bytes for every kernel input before this wrapper is
3815            // called — so by the time we reach here, the input
3816            // bytes match `input_layout.shape()` in row-major
3817            // order. We pass only the shape to the typed kernel.
3818            let input_shape: &[usize] = input_layout.shape().dims();
3819            let in_guard = read_storage(&inputs[0])?;
3820            let mut out_guard = write_storage(&outputs[0])?;
3821            let in_cpu = cpu_input(&in_guard)?;
3822            let out_cpu = cpu_output(&mut out_guard)?;
3823            $kernel(in_cpu, out_cpu, input_shape, dims)
3824        }
3825    };
3826}
3827
3828cpu_reduce_wrapper!(
3829    sum_reduce_f32_cpu_wrapper,
3830    fuel_cpu_backend::byte_kernels::sum_reduce_f32,
3831    "sum_reduce"
3832);
3833cpu_reduce_wrapper!(
3834    max_reduce_f32_cpu_wrapper,
3835    fuel_cpu_backend::byte_kernels::max_reduce_f32,
3836    "max_reduce"
3837);
3838cpu_reduce_wrapper!(
3839    min_reduce_f32_cpu_wrapper,
3840    fuel_cpu_backend::byte_kernels::min_reduce_f32,
3841    "min_reduce"
3842);
3843cpu_reduce_wrapper!(
3844    mean_reduce_f32_cpu_wrapper,
3845    fuel_cpu_backend::byte_kernels::mean_reduce_f32,
3846    "mean_reduce"
3847);
3848cpu_reduce_wrapper!(
3849    sum_reduce_f64_cpu_wrapper,
3850    fuel_cpu_backend::byte_kernels::sum_reduce_f64,
3851    "sum_reduce"
3852);
3853cpu_reduce_wrapper!(
3854    max_reduce_f64_cpu_wrapper,
3855    fuel_cpu_backend::byte_kernels::max_reduce_f64,
3856    "max_reduce"
3857);
3858cpu_reduce_wrapper!(
3859    min_reduce_f64_cpu_wrapper,
3860    fuel_cpu_backend::byte_kernels::min_reduce_f64,
3861    "min_reduce"
3862);
3863cpu_reduce_wrapper!(
3864    mean_reduce_f64_cpu_wrapper,
3865    fuel_cpu_backend::byte_kernels::mean_reduce_f64,
3866    "mean_reduce"
3867);
3868
3869cpu_reduce_wrapper!(
3870    sum_reduce_bf16_cpu_wrapper,
3871    fuel_cpu_backend::byte_kernels::sum_reduce_bf16,
3872    "sum_reduce"
3873);
3874cpu_reduce_wrapper!(
3875    max_reduce_bf16_cpu_wrapper,
3876    fuel_cpu_backend::byte_kernels::max_reduce_bf16,
3877    "max_reduce"
3878);
3879cpu_reduce_wrapper!(
3880    min_reduce_bf16_cpu_wrapper,
3881    fuel_cpu_backend::byte_kernels::min_reduce_bf16,
3882    "min_reduce"
3883);
3884cpu_reduce_wrapper!(
3885    mean_reduce_bf16_cpu_wrapper,
3886    fuel_cpu_backend::byte_kernels::mean_reduce_bf16,
3887    "mean_reduce"
3888);
3889
3890cpu_reduce_wrapper!(
3891    sum_reduce_f16_cpu_wrapper,
3892    fuel_cpu_backend::byte_kernels::sum_reduce_f16,
3893    "sum_reduce"
3894);
3895cpu_reduce_wrapper!(
3896    max_reduce_f16_cpu_wrapper,
3897    fuel_cpu_backend::byte_kernels::max_reduce_f16,
3898    "max_reduce"
3899);
3900cpu_reduce_wrapper!(
3901    min_reduce_f16_cpu_wrapper,
3902    fuel_cpu_backend::byte_kernels::min_reduce_f16,
3903    "min_reduce"
3904);
3905cpu_reduce_wrapper!(
3906    mean_reduce_f16_cpu_wrapper,
3907    fuel_cpu_backend::byte_kernels::mean_reduce_f16,
3908    "mean_reduce"
3909);
3910
3911/// Generate a dispatch wrapper for `(Cast, <target>, Cpu)`. The
3912/// binding-table key is keyed on the *target* dtype (= the
3913/// Node's dtype = the output Storage's dtype); the wrapper reads
3914/// the input Storage's dtype at runtime and dispatches to the
3915/// right typed conversion kernel.
3916macro_rules! cpu_cast_wrapper {
3917    (
3918        $wrapper:ident,
3919        $target_dtype:expr,
3920        $target_name:literal,
3921        { $( $source:pat => $kernel:path ),+ $(,)? } $(,)?
3922    ) => {
3923        // `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the
3924        // real production wrapper and the importer can bind it FROM the contract.
3925        pub(crate) fn $wrapper(
3926            inputs: &[Arc<RwLock<Storage>>],
3927            outputs: &mut [Arc<RwLock<Storage>>],
3928            _layouts: &[Layout],
3929            _params: &OpParams,
3930        ) -> Result<()> {
3931            if inputs.len() != 1 {
3932                return Err(Error::Msg(format!(
3933                    "cast→{} wrapper expects 1 input, got {}",
3934                    $target_name,
3935                    inputs.len(),
3936                ))
3937                .bt());
3938            }
3939            if outputs.len() != 1 {
3940                return Err(Error::Msg(format!(
3941                    "cast→{} wrapper expects 1 output, got {}",
3942                    $target_name,
3943                    outputs.len(),
3944                ))
3945                .bt());
3946            }
3947            let in_guard = read_storage(&inputs[0])?;
3948            let mut out_guard = write_storage(&outputs[0])?;
3949            let source_dtype = in_guard.dtype;
3950            let in_cpu = cpu_input(&in_guard)?;
3951            let out_cpu = cpu_output(&mut out_guard)?;
3952            match source_dtype {
3953                $( $source => $kernel(in_cpu, out_cpu), )+
3954                other => Err(Error::Msg(format!(
3955                    "cast→{}: source dtype {:?} not yet wired (Phase C \
3956                     extends the cast matrix as needed)",
3957                    $target_name, other,
3958                ))
3959                .bt()),
3960            }
3961        }
3962    };
3963}
3964
3965/// Dispatch wrapper for `(Conv2D, *, Cpu)`. Two or three inputs
3966/// (x, weight, optional bias). Shapes + geometry flow through
3967/// `OpParams::Conv2D`.
3968/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
3969/// production wrapper and the importer can bind it FROM the contract.
3970macro_rules! cpu_conv2d_wrapper {
3971    ($name:ident, $kernel:path) => {
3972        pub(crate) fn $name(
3973            inputs: &[Arc<RwLock<Storage>>],
3974            outputs: &mut [Arc<RwLock<Storage>>],
3975            _layouts: &[Layout],
3976            params: &OpParams,
3977        ) -> Result<()> {
3978            if inputs.len() != 2 && inputs.len() != 3 {
3979                return Err(Error::Msg(format!(
3980                    "conv2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
3981                    inputs.len(),
3982                ))
3983                .bt());
3984            }
3985            if outputs.len() != 1 {
3986                return Err(Error::Msg(format!(
3987                    "conv2d wrapper expects 1 output, got {}",
3988                    outputs.len(),
3989                ))
3990                .bt());
3991            }
3992            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) = match params {
3993                OpParams::Conv2D {
3994                    x_shape,
3995                    w_shape,
3996                    out_shape,
3997                    stride,
3998                    padding,
3999                    dilation,
4000                    groups,
4001                } => (
4002                    *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4003                ),
4004                other => {
4005                    return Err(Error::Msg(format!(
4006                        "conv2d wrapper expects OpParams::Conv2D, got {other:?}",
4007                    ))
4008                    .bt())
4009                }
4010            };
4011            let x_guard = read_storage(&inputs[0])?;
4012            let w_guard = read_storage(&inputs[1])?;
4013            let bias_guard = match inputs.get(2) {
4014                Some(arc) => Some(read_storage(arc)?),
4015                None => None,
4016            };
4017            let mut out_guard = write_storage(&outputs[0])?;
4018            let x_cpu = cpu_input(&x_guard)?;
4019            let w_cpu = cpu_input(&w_guard)?;
4020            let bias_cpu = match &bias_guard {
4021                Some(g) => Some(cpu_input(g)?),
4022                None => None,
4023            };
4024            let out_cpu = cpu_output(&mut out_guard)?;
4025            $kernel(
4026                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4027                dilation, groups,
4028            )
4029        }
4030    };
4031}
4032
4033cpu_conv2d_wrapper!(
4034    conv2d_f32_cpu_wrapper,
4035    fuel_cpu_backend::byte_kernels::conv2d_f32
4036);
4037cpu_conv2d_wrapper!(
4038    conv2d_f64_cpu_wrapper,
4039    fuel_cpu_backend::byte_kernels::conv2d_f64
4040);
4041cpu_conv2d_wrapper!(
4042    conv2d_bf16_cpu_wrapper,
4043    fuel_cpu_backend::byte_kernels::conv2d_bf16
4044);
4045cpu_conv2d_wrapper!(
4046    conv2d_f16_cpu_wrapper,
4047    fuel_cpu_backend::byte_kernels::conv2d_f16
4048);
4049
4050/// Dispatch wrapper for `(ConvTranspose2D, *, Cpu)`. Two or three
4051/// inputs (x, weight, [bias]). Geometry flows through
4052/// `OpParams::ConvTranspose2D`.
4053/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4054/// production wrapper and the importer can bind it FROM the contract.
4055macro_rules! cpu_conv_transpose2d_wrapper {
4056    ($name:ident, $kernel:path) => {
4057        pub(crate) fn $name(
4058            inputs: &[Arc<RwLock<Storage>>],
4059            outputs: &mut [Arc<RwLock<Storage>>],
4060            _layouts: &[Layout],
4061            params: &OpParams,
4062        ) -> Result<()> {
4063            if inputs.len() != 2 && inputs.len() != 3 {
4064                return Err(Error::Msg(format!(
4065                    "conv_transpose2d wrapper expects 2 or 3 inputs (x, weight, [bias]), got {}",
4066                    inputs.len(),
4067                ))
4068                .bt());
4069            }
4070            if outputs.len() != 1 {
4071                return Err(Error::Msg(format!(
4072                    "conv_transpose2d wrapper expects 1 output, got {}",
4073                    outputs.len(),
4074                ))
4075                .bt());
4076            }
4077            let (x_shape, w_shape, out_shape, stride, padding, dilation, groups) =
4078                match params {
4079                    OpParams::ConvTranspose2D {
4080                        x_shape,
4081                        w_shape,
4082                        out_shape,
4083                        stride,
4084                        padding,
4085                        output_padding: _,
4086                        dilation,
4087                        groups,
4088                    } => (
4089                        *x_shape, *w_shape, *out_shape, *stride, *padding, *dilation, *groups,
4090                    ),
4091                    other => return Err(Error::Msg(format!(
4092                        "conv_transpose2d wrapper expects OpParams::ConvTranspose2D, got {other:?}",
4093                    ))
4094                    .bt()),
4095                };
4096            let x_guard = read_storage(&inputs[0])?;
4097            let w_guard = read_storage(&inputs[1])?;
4098            let bias_guard = match inputs.get(2) {
4099                Some(arc) => Some(read_storage(arc)?),
4100                None => None,
4101            };
4102            let mut out_guard = write_storage(&outputs[0])?;
4103            let x_cpu = cpu_input(&x_guard)?;
4104            let w_cpu = cpu_input(&w_guard)?;
4105            let bias_cpu = match &bias_guard {
4106                Some(g) => Some(cpu_input(g)?),
4107                None => None,
4108            };
4109            let out_cpu = cpu_output(&mut out_guard)?;
4110            $kernel(
4111                x_cpu, w_cpu, bias_cpu, out_cpu, x_shape, w_shape, out_shape, stride, padding,
4112                dilation, groups,
4113            )
4114        }
4115    };
4116}
4117
4118cpu_conv_transpose2d_wrapper!(
4119    conv_transpose2d_f32_cpu_wrapper,
4120    fuel_cpu_backend::byte_kernels::conv_transpose2d_f32
4121);
4122cpu_conv_transpose2d_wrapper!(
4123    conv_transpose2d_f64_cpu_wrapper,
4124    fuel_cpu_backend::byte_kernels::conv_transpose2d_f64
4125);
4126cpu_conv_transpose2d_wrapper!(
4127    conv_transpose2d_bf16_cpu_wrapper,
4128    fuel_cpu_backend::byte_kernels::conv_transpose2d_bf16
4129);
4130cpu_conv_transpose2d_wrapper!(
4131    conv_transpose2d_f16_cpu_wrapper,
4132    fuel_cpu_backend::byte_kernels::conv_transpose2d_f16
4133);
4134
4135/// Dispatch wrapper for `(ReduceSumTo, *, Cpu)`. Single input → single
4136/// output; shapes flow through `OpParams::ReduceSumTo`.
4137/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4138/// production wrapper and the importer can bind it FROM the contract.
4139macro_rules! cpu_reduce_sum_to_wrapper {
4140    ($name:ident, $kernel:path) => {
4141        pub(crate) fn $name(
4142            inputs: &[Arc<RwLock<Storage>>],
4143            outputs: &mut [Arc<RwLock<Storage>>],
4144            _layouts: &[Layout],
4145            params: &OpParams,
4146        ) -> Result<()> {
4147            if inputs.len() != 1 {
4148                return Err(Error::Msg(format!(
4149                    "reduce_sum_to wrapper expects 1 input, got {}",
4150                    inputs.len(),
4151                ))
4152                .bt());
4153            }
4154            if outputs.len() != 1 {
4155                return Err(Error::Msg(format!(
4156                    "reduce_sum_to wrapper expects 1 output, got {}",
4157                    outputs.len(),
4158                ))
4159                .bt());
4160            }
4161            let (input_shape, output_shape) = match params {
4162                OpParams::ReduceSumTo {
4163                    input_shape,
4164                    output_shape,
4165                } => (input_shape.clone(), output_shape.clone()),
4166                other => {
4167                    return Err(Error::Msg(format!(
4168                        "reduce_sum_to wrapper expects OpParams::ReduceSumTo, got {other:?}",
4169                    ))
4170                    .bt())
4171                }
4172            };
4173            let in_guard = read_storage(&inputs[0])?;
4174            let mut out_guard = write_storage(&outputs[0])?;
4175            let in_cpu = cpu_input(&in_guard)?;
4176            let out_cpu = cpu_output(&mut out_guard)?;
4177            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4178        }
4179    };
4180}
4181
4182cpu_reduce_sum_to_wrapper!(
4183    reduce_sum_to_f32_cpu_wrapper,
4184    fuel_cpu_backend::byte_kernels::reduce_sum_to_f32
4185);
4186cpu_reduce_sum_to_wrapper!(
4187    reduce_sum_to_f64_cpu_wrapper,
4188    fuel_cpu_backend::byte_kernels::reduce_sum_to_f64
4189);
4190cpu_reduce_sum_to_wrapper!(
4191    reduce_sum_to_bf16_cpu_wrapper,
4192    fuel_cpu_backend::byte_kernels::reduce_sum_to_bf16
4193);
4194cpu_reduce_sum_to_wrapper!(
4195    reduce_sum_to_f16_cpu_wrapper,
4196    fuel_cpu_backend::byte_kernels::reduce_sum_to_f16
4197);
4198
4199/// Dispatch wrapper for `(ReduceMaxTo, *, Cpu)`. Single input → single
4200/// output; shapes flow through `OpParams::ReduceMaxTo`.
4201/// `pub(crate)` so the FKC `link_registry` (`fkc::cpu_link`) can name the real
4202/// production wrapper and the importer can bind it FROM the contract.
4203macro_rules! cpu_reduce_max_to_wrapper {
4204    ($name:ident, $kernel:path) => {
4205        pub(crate) fn $name(
4206            inputs: &[Arc<RwLock<Storage>>],
4207            outputs: &mut [Arc<RwLock<Storage>>],
4208            _layouts: &[Layout],
4209            params: &OpParams,
4210        ) -> Result<()> {
4211            if inputs.len() != 1 {
4212                return Err(Error::Msg(format!(
4213                    "reduce_max_to wrapper expects 1 input, got {}",
4214                    inputs.len(),
4215                ))
4216                .bt());
4217            }
4218            if outputs.len() != 1 {
4219                return Err(Error::Msg(format!(
4220                    "reduce_max_to wrapper expects 1 output, got {}",
4221                    outputs.len(),
4222                ))
4223                .bt());
4224            }
4225            let (input_shape, output_shape) = match params {
4226                OpParams::ReduceMaxTo {
4227                    input_shape,
4228                    output_shape,
4229                } => (input_shape.clone(), output_shape.clone()),
4230                other => {
4231                    return Err(Error::Msg(format!(
4232                        "reduce_max_to wrapper expects OpParams::ReduceMaxTo, got {other:?}",
4233                    ))
4234                    .bt())
4235                }
4236            };
4237            let in_guard = read_storage(&inputs[0])?;
4238            let mut out_guard = write_storage(&outputs[0])?;
4239            let in_cpu = cpu_input(&in_guard)?;
4240            let out_cpu = cpu_output(&mut out_guard)?;
4241            $kernel(in_cpu, out_cpu, &input_shape, &output_shape)
4242        }
4243    };
4244}
4245
4246cpu_reduce_max_to_wrapper!(
4247    reduce_max_to_f32_cpu_wrapper,
4248    fuel_cpu_backend::byte_kernels::reduce_max_to_f32
4249);
4250cpu_reduce_max_to_wrapper!(
4251    reduce_max_to_f64_cpu_wrapper,
4252    fuel_cpu_backend::byte_kernels::reduce_max_to_f64
4253);
4254cpu_reduce_max_to_wrapper!(
4255    reduce_max_to_bf16_cpu_wrapper,
4256    fuel_cpu_backend::byte_kernels::reduce_max_to_bf16
4257);
4258cpu_reduce_max_to_wrapper!(
4259    reduce_max_to_f16_cpu_wrapper,
4260    fuel_cpu_backend::byte_kernels::reduce_max_to_f16
4261);
4262
4263/// Dispatch wrapper for `(FusedLinear, *, Cpu)`. Three inputs
4264/// (lhs, rhs, bias). Reuses `OpParams::Matmul` for shape.
4265macro_rules! cpu_fused_linear_wrapper {
4266    ($wrapper:ident, $kernel:path) => {
4267        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
4268        // contract's `fused_linear_<dt>` `entry_point` symbols to these wrappers.
4269        pub(crate) fn $wrapper(
4270            inputs: &[Arc<RwLock<Storage>>],
4271            outputs: &mut [Arc<RwLock<Storage>>],
4272            _layouts: &[Layout],
4273            params: &OpParams,
4274        ) -> Result<()> {
4275            if inputs.len() != 3 {
4276                return Err(Error::Msg(format!(
4277                    "fused_linear wrapper expects 3 inputs (lhs, rhs, bias), got {}",
4278                    inputs.len(),
4279                ))
4280                .bt());
4281            }
4282            if outputs.len() != 1 {
4283                return Err(Error::Msg(format!(
4284                    "fused_linear wrapper expects 1 output, got {}",
4285                    outputs.len(),
4286                ))
4287                .bt());
4288            }
4289            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
4290                OpParams::Matmul {
4291                    lhs_batch_dims,
4292                    rhs_batch_dims,
4293                    m,
4294                    n,
4295                    k,
4296                    ..
4297                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
4298                other => {
4299                    return Err(Error::Msg(format!(
4300                        "fused_linear wrapper expects OpParams::Matmul, got {other:?}",
4301                    ))
4302                    .bt())
4303                }
4304            };
4305            let lhs_guard = read_storage(&inputs[0])?;
4306            let rhs_guard = read_storage(&inputs[1])?;
4307            let bias_guard = read_storage(&inputs[2])?;
4308            let mut out_guard = write_storage(&outputs[0])?;
4309            let lhs_cpu = cpu_input(&lhs_guard)?;
4310            let rhs_cpu = cpu_input(&rhs_guard)?;
4311            let bias_cpu = cpu_input(&bias_guard)?;
4312            let out_cpu = cpu_output(&mut out_guard)?;
4313            $kernel(
4314                lhs_cpu,
4315                rhs_cpu,
4316                bias_cpu,
4317                out_cpu,
4318                lhs_batch_dims,
4319                rhs_batch_dims,
4320                m,
4321                n,
4322                k,
4323            )
4324        }
4325    };
4326}
4327
4328cpu_fused_linear_wrapper!(
4329    fused_linear_f32_cpu_wrapper,
4330    fuel_cpu_backend::byte_kernels::fused_linear_f32
4331);
4332cpu_fused_linear_wrapper!(
4333    fused_linear_f64_cpu_wrapper,
4334    fuel_cpu_backend::byte_kernels::fused_linear_f64
4335);
4336cpu_fused_linear_wrapper!(
4337    fused_linear_bf16_cpu_wrapper,
4338    fuel_cpu_backend::byte_kernels::fused_linear_bf16
4339);
4340cpu_fused_linear_wrapper!(
4341    fused_linear_f16_cpu_wrapper,
4342    fuel_cpu_backend::byte_kernels::fused_linear_f16
4343);
4344
4345/// Per-dtype FusedSoftmaxCrossEntropy dispatch wrapper. Two inputs
4346/// (logits T, targets I64) → one F32 output (the FSCE declared dtype,
4347/// regardless of logits dtype — losses accumulate in f64, narrow to
4348/// f32). Translates the `Reduction` enum from the FusedOpParams
4349/// payload (which lives on the graph node) to the kernel's `u8` tag —
4350/// the kernel intentionally stays free of fuel-graph dependencies.
4351macro_rules! cpu_fused_softmax_cross_entropy_wrapper {
4352    ($wrapper:ident, $kernel:path) => {
4353        pub(crate) fn $wrapper(
4354            inputs: &[Arc<RwLock<Storage>>],
4355            outputs: &mut [Arc<RwLock<Storage>>],
4356            _layouts: &[Layout],
4357            params: &OpParams,
4358        ) -> Result<()> {
4359            if inputs.len() != 2 {
4360                return Err(Error::Msg(format!(
4361                    "fused_softmax_cross_entropy wrapper expects 2 inputs (logits, targets), got {}",
4362                    inputs.len(),
4363                ))
4364                .bt());
4365            }
4366            if outputs.len() != 1 {
4367                return Err(Error::Msg(format!(
4368                    "fused_softmax_cross_entropy wrapper expects 1 output, got {}",
4369                    outputs.len(),
4370                ))
4371                .bt());
4372            }
4373            let (n_rows, vocab, reduction, ignore_index) = match params {
4374                OpParams::FusedSoftmaxCrossEntropy {
4375                    n_rows, vocab, reduction, ignore_index,
4376                } => (*n_rows, *vocab, *reduction, *ignore_index),
4377                other => {
4378                    return Err(Error::Msg(format!(
4379                        "fused_softmax_cross_entropy wrapper expects \
4380                         OpParams::FusedSoftmaxCrossEntropy, got {other:?}",
4381                    ))
4382                    .bt());
4383                }
4384            };
4385            let reduction_tag = match reduction {
4386                fuel_graph::registry::Reduction::Mean => fuel_cpu_backend::byte_kernels::REDUCTION_MEAN,
4387                fuel_graph::registry::Reduction::Sum  => fuel_cpu_backend::byte_kernels::REDUCTION_SUM,
4388                fuel_graph::registry::Reduction::None => fuel_cpu_backend::byte_kernels::REDUCTION_NONE,
4389            };
4390            let logits_guard = read_storage(&inputs[0])?;
4391            let targets_guard = read_storage(&inputs[1])?;
4392            let mut out_guard = write_storage(&outputs[0])?;
4393            let logits_cpu = cpu_input(&logits_guard)?;
4394            let targets_cpu = cpu_input(&targets_guard)?;
4395            let out_cpu = cpu_output(&mut out_guard)?;
4396            $kernel(
4397                logits_cpu, targets_cpu, out_cpu,
4398                n_rows, vocab, reduction_tag, ignore_index,
4399            )
4400        }
4401    };
4402}
4403
4404cpu_fused_softmax_cross_entropy_wrapper!(
4405    fused_softmax_cross_entropy_f32_cpu_wrapper,
4406    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f32
4407);
4408cpu_fused_softmax_cross_entropy_wrapper!(
4409    fused_softmax_cross_entropy_f64_cpu_wrapper,
4410    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f64
4411);
4412cpu_fused_softmax_cross_entropy_wrapper!(
4413    fused_softmax_cross_entropy_bf16_cpu_wrapper,
4414    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_bf16
4415);
4416cpu_fused_softmax_cross_entropy_wrapper!(
4417    fused_softmax_cross_entropy_f16_cpu_wrapper,
4418    fuel_cpu_backend::byte_kernels::fused_softmax_cross_entropy_f16
4419);
4420
4421/// Per-dtype CausalConv1d dispatch wrapper. Three inputs (x, weight,
4422/// bias) → one output. Geometry + `use_silu` flow through
4423/// `OpParams::CausalConv1d`. All four inputs/outputs share the same
4424/// dtype `T`; the binding-table key is `[T, T, T, T]`.
4425macro_rules! cpu_causal_conv1d_wrapper {
4426    ($wrapper:ident, $kernel:path) => {
4427        pub(crate) fn $wrapper(
4428            inputs: &[Arc<RwLock<Storage>>],
4429            outputs: &mut [Arc<RwLock<Storage>>],
4430            _layouts: &[Layout],
4431            params: &OpParams,
4432        ) -> Result<()> {
4433            if inputs.len() != 3 {
4434                return Err(Error::Msg(format!(
4435                    "causal_conv1d wrapper expects 3 inputs (x, weight, bias), got {}",
4436                    inputs.len(),
4437                ))
4438                .bt());
4439            }
4440            if outputs.len() != 1 {
4441                return Err(Error::Msg(format!(
4442                    "causal_conv1d wrapper expects 1 output, got {}",
4443                    outputs.len(),
4444                ))
4445                .bt());
4446            }
4447            let (batch, channels, seq_in, seq_out, kernel, use_silu) = match params {
4448                OpParams::CausalConv1d {
4449                    batch,
4450                    channels,
4451                    seq_in,
4452                    seq_out,
4453                    kernel,
4454                    use_silu,
4455                } => (*batch, *channels, *seq_in, *seq_out, *kernel, *use_silu),
4456                other => {
4457                    return Err(Error::Msg(format!(
4458                        "causal_conv1d wrapper expects OpParams::CausalConv1d, got {other:?}",
4459                    ))
4460                    .bt());
4461                }
4462            };
4463            let x_guard = read_storage(&inputs[0])?;
4464            let w_guard = read_storage(&inputs[1])?;
4465            let bias_guard = read_storage(&inputs[2])?;
4466            let mut out_guard = write_storage(&outputs[0])?;
4467            let x_cpu = cpu_input(&x_guard)?;
4468            let w_cpu = cpu_input(&w_guard)?;
4469            let bias_cpu = cpu_input(&bias_guard)?;
4470            let out_cpu = cpu_output(&mut out_guard)?;
4471            $kernel(
4472                x_cpu, w_cpu, bias_cpu, out_cpu, batch, channels, seq_in, seq_out, kernel, use_silu,
4473            )
4474        }
4475    };
4476}
4477
4478cpu_causal_conv1d_wrapper!(
4479    causal_conv1d_f32_cpu_wrapper,
4480    fuel_cpu_backend::byte_kernels::causal_conv1d_f32
4481);
4482cpu_causal_conv1d_wrapper!(
4483    causal_conv1d_f64_cpu_wrapper,
4484    fuel_cpu_backend::byte_kernels::causal_conv1d_f64
4485);
4486cpu_causal_conv1d_wrapper!(
4487    causal_conv1d_bf16_cpu_wrapper,
4488    fuel_cpu_backend::byte_kernels::causal_conv1d_bf16
4489);
4490cpu_causal_conv1d_wrapper!(
4491    causal_conv1d_f16_cpu_wrapper,
4492    fuel_cpu_backend::byte_kernels::causal_conv1d_f16
4493);
4494
4495/// Per-dtype SelectiveScan dispatch wrapper. Five inputs (u, delta,
4496/// a, b, c) → one output (y). Geometry + `delta_softplus` flow
4497/// through `OpParams::SelectiveScan`. All six tensors share dtype `T`;
4498/// the binding-table key is `[T; 6]`.
4499macro_rules! cpu_selective_scan_wrapper {
4500    ($wrapper:ident, $kernel:path) => {
4501        pub(crate) fn $wrapper(
4502            inputs: &[Arc<RwLock<Storage>>],
4503            outputs: &mut [Arc<RwLock<Storage>>],
4504            _layouts: &[Layout],
4505            params: &OpParams,
4506        ) -> Result<()> {
4507            if inputs.len() != 5 {
4508                return Err(Error::Msg(format!(
4509                    "selective_scan wrapper expects 5 inputs (u, delta, a, b, c), got {}",
4510                    inputs.len(),
4511                ))
4512                .bt());
4513            }
4514            if outputs.len() != 1 {
4515                return Err(Error::Msg(format!(
4516                    "selective_scan wrapper expects 1 output, got {}",
4517                    outputs.len(),
4518                ))
4519                .bt());
4520            }
4521            let (batch, seqlen, dim, dstate, delta_softplus) = match params {
4522                OpParams::SelectiveScan {
4523                    batch,
4524                    seqlen,
4525                    dim,
4526                    dstate,
4527                    delta_softplus,
4528                } => (*batch, *seqlen, *dim, *dstate, *delta_softplus),
4529                other => {
4530                    return Err(Error::Msg(format!(
4531                        "selective_scan wrapper expects OpParams::SelectiveScan, got {other:?}",
4532                    ))
4533                    .bt());
4534                }
4535            };
4536            let u_guard = read_storage(&inputs[0])?;
4537            let delta_guard = read_storage(&inputs[1])?;
4538            let a_guard = read_storage(&inputs[2])?;
4539            let b_guard = read_storage(&inputs[3])?;
4540            let c_guard = read_storage(&inputs[4])?;
4541            let mut out_guard = write_storage(&outputs[0])?;
4542            let u_cpu = cpu_input(&u_guard)?;
4543            let delta_cpu = cpu_input(&delta_guard)?;
4544            let a_cpu = cpu_input(&a_guard)?;
4545            let b_cpu = cpu_input(&b_guard)?;
4546            let c_cpu = cpu_input(&c_guard)?;
4547            let out_cpu = cpu_output(&mut out_guard)?;
4548            $kernel(
4549                u_cpu,
4550                delta_cpu,
4551                a_cpu,
4552                b_cpu,
4553                c_cpu,
4554                out_cpu,
4555                batch,
4556                seqlen,
4557                dim,
4558                dstate,
4559                delta_softplus,
4560            )
4561        }
4562    };
4563}
4564
4565cpu_selective_scan_wrapper!(
4566    selective_scan_f32_cpu_wrapper,
4567    fuel_cpu_backend::byte_kernels::selective_scan_f32
4568);
4569cpu_selective_scan_wrapper!(
4570    selective_scan_f64_cpu_wrapper,
4571    fuel_cpu_backend::byte_kernels::selective_scan_f64
4572);
4573cpu_selective_scan_wrapper!(
4574    selective_scan_bf16_cpu_wrapper,
4575    fuel_cpu_backend::byte_kernels::selective_scan_bf16
4576);
4577cpu_selective_scan_wrapper!(
4578    selective_scan_f16_cpu_wrapper,
4579    fuel_cpu_backend::byte_kernels::selective_scan_f16
4580);
4581
4582/// Per-input-dtype NonZeroIndices dispatch wrapper. One input `x`
4583/// (the value tensor) → one bundled output `[indices [capacity] U32 ;
4584/// count [1] U32]`. `capacity` flows through `OpParams::NonZeroIndices`;
4585/// the binding-table key is `[input_dtype, U32]` (input + the primary
4586/// output-slot dtype). The `count_sym` field is consumed by the executor
4587/// after the kernel runs (the SymEnv bind seam), not here.
4588macro_rules! cpu_nonzero_indices_wrapper {
4589    ($wrapper:ident, $kernel:path) => {
4590        pub(crate) fn $wrapper(
4591            inputs: &[Arc<RwLock<Storage>>],
4592            outputs: &mut [Arc<RwLock<Storage>>],
4593            _layouts: &[Layout],
4594            params: &OpParams,
4595        ) -> Result<()> {
4596            if inputs.len() != 1 {
4597                return Err(Error::Msg(format!(
4598                    "nonzero_indices wrapper expects 1 input, got {}",
4599                    inputs.len(),
4600                ))
4601                .bt());
4602            }
4603            if outputs.len() != 1 {
4604                return Err(Error::Msg(format!(
4605                    "nonzero_indices wrapper expects 1 output, got {}",
4606                    outputs.len(),
4607                ))
4608                .bt());
4609            }
4610            let capacity = match params {
4611                OpParams::NonZeroIndices { capacity, .. } => *capacity,
4612                other => {
4613                    return Err(Error::Msg(format!(
4614                        "nonzero_indices wrapper expects OpParams::NonZeroIndices, got {other:?}",
4615                    ))
4616                    .bt());
4617                }
4618            };
4619            let x_guard = read_storage(&inputs[0])?;
4620            let mut out_guard = write_storage(&outputs[0])?;
4621            let x_cpu = cpu_input(&x_guard)?;
4622            let out_cpu = cpu_output(&mut out_guard)?;
4623            $kernel(x_cpu, out_cpu, capacity)
4624        }
4625    };
4626}
4627
4628cpu_nonzero_indices_wrapper!(
4629    nonzero_indices_f32_cpu_wrapper,
4630    fuel_cpu_backend::byte_kernels::nonzero_indices_f32
4631);
4632cpu_nonzero_indices_wrapper!(
4633    nonzero_indices_u32_cpu_wrapper,
4634    fuel_cpu_backend::byte_kernels::nonzero_indices_u32
4635);
4636
4637/// Per-dtype SsdChunkScan dispatch wrapper. Five inputs (x, dt, a,
4638/// b, c) → one output (y). Geometry + `chunk_size` flow through
4639/// `OpParams::SsdChunkScan`. All six tensors share dtype `T`; the
4640/// binding-table key is `[T; 6]`.
4641macro_rules! cpu_ssd_chunk_scan_wrapper {
4642    ($wrapper:ident, $kernel:path) => {
4643        pub(crate) fn $wrapper(
4644            inputs: &[Arc<RwLock<Storage>>],
4645            outputs: &mut [Arc<RwLock<Storage>>],
4646            _layouts: &[Layout],
4647            params: &OpParams,
4648        ) -> Result<()> {
4649            if inputs.len() != 5 {
4650                return Err(Error::Msg(format!(
4651                    "ssd_chunk_scan wrapper expects 5 inputs (x, dt, a, b, c), got {}",
4652                    inputs.len(),
4653                ))
4654                .bt());
4655            }
4656            if outputs.len() != 1 {
4657                return Err(Error::Msg(format!(
4658                    "ssd_chunk_scan wrapper expects 1 output, got {}",
4659                    outputs.len(),
4660                ))
4661                .bt());
4662            }
4663            let (batch, seqlen, heads, head_dim, state_dim, chunk_size) = match params {
4664                OpParams::SsdChunkScan {
4665                    batch,
4666                    seqlen,
4667                    heads,
4668                    head_dim,
4669                    state_dim,
4670                    chunk_size,
4671                } => (*batch, *seqlen, *heads, *head_dim, *state_dim, *chunk_size),
4672                other => {
4673                    return Err(Error::Msg(format!(
4674                        "ssd_chunk_scan wrapper expects OpParams::SsdChunkScan, got {other:?}",
4675                    ))
4676                    .bt());
4677                }
4678            };
4679            let x_guard = read_storage(&inputs[0])?;
4680            let dt_guard = read_storage(&inputs[1])?;
4681            let a_guard = read_storage(&inputs[2])?;
4682            let b_guard = read_storage(&inputs[3])?;
4683            let c_guard = read_storage(&inputs[4])?;
4684            let mut out_guard = write_storage(&outputs[0])?;
4685            let x_cpu = cpu_input(&x_guard)?;
4686            let dt_cpu = cpu_input(&dt_guard)?;
4687            let a_cpu = cpu_input(&a_guard)?;
4688            let b_cpu = cpu_input(&b_guard)?;
4689            let c_cpu = cpu_input(&c_guard)?;
4690            let out_cpu = cpu_output(&mut out_guard)?;
4691            $kernel(
4692                x_cpu, dt_cpu, a_cpu, b_cpu, c_cpu, out_cpu, batch, seqlen, heads, head_dim,
4693                state_dim, chunk_size,
4694            )
4695        }
4696    };
4697}
4698
4699cpu_ssd_chunk_scan_wrapper!(
4700    ssd_chunk_scan_f32_cpu_wrapper,
4701    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f32
4702);
4703cpu_ssd_chunk_scan_wrapper!(
4704    ssd_chunk_scan_f64_cpu_wrapper,
4705    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f64
4706);
4707cpu_ssd_chunk_scan_wrapper!(
4708    ssd_chunk_scan_bf16_cpu_wrapper,
4709    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_bf16
4710);
4711cpu_ssd_chunk_scan_wrapper!(
4712    ssd_chunk_scan_f16_cpu_wrapper,
4713    fuel_cpu_backend::byte_kernels::ssd_chunk_scan_f16
4714);
4715
4716/// Per-dtype Nf4Matmul wrapper. Three inputs (activations, w_packed
4717/// U8, absmax F32) → one output of the activations' dtype.
4718/// `block_size` flows through `OpParams::Nf4Matmul`.
4719macro_rules! cpu_nf4_matmul_wrapper {
4720    ($wrapper:ident, $kernel:path) => {
4721        fn $wrapper(
4722            inputs: &[Arc<RwLock<Storage>>],
4723            outputs: &mut [Arc<RwLock<Storage>>],
4724            _layouts: &[Layout],
4725            params: &OpParams,
4726        ) -> Result<()> {
4727            if inputs.len() != 3 {
4728                return Err(Error::Msg(format!(
4729                    "nf4_matmul wrapper expects 3 inputs (activations, w_packed, absmax), got {}",
4730                    inputs.len(),
4731                ))
4732                .bt());
4733            }
4734            if outputs.len() != 1 {
4735                return Err(Error::Msg(format!(
4736                    "nf4_matmul wrapper expects 1 output, got {}",
4737                    outputs.len(),
4738                ))
4739                .bt());
4740            }
4741            let (batch, m, n, k, block_size) = match params {
4742                OpParams::Nf4Matmul {
4743                    batch,
4744                    m,
4745                    n,
4746                    k,
4747                    block_size,
4748                } => (*batch, *m, *n, *k, *block_size),
4749                other => {
4750                    return Err(Error::Msg(format!(
4751                        "nf4_matmul wrapper expects OpParams::Nf4Matmul, got {other:?}",
4752                    ))
4753                    .bt());
4754                }
4755            };
4756            let a_guard = read_storage(&inputs[0])?;
4757            let w_guard = read_storage(&inputs[1])?;
4758            let abs_guard = read_storage(&inputs[2])?;
4759            let mut out_guard = write_storage(&outputs[0])?;
4760            let a_cpu = cpu_input(&a_guard)?;
4761            let w_cpu = cpu_input(&w_guard)?;
4762            let abs_cpu = cpu_input(&abs_guard)?;
4763            let out_cpu = cpu_output(&mut out_guard)?;
4764            $kernel(a_cpu, w_cpu, abs_cpu, out_cpu, batch, m, n, k, block_size)
4765        }
4766    };
4767}
4768
4769cpu_nf4_matmul_wrapper!(
4770    nf4_matmul_f32_cpu_wrapper,
4771    fuel_cpu_backend::byte_kernels::nf4_matmul_f32
4772);
4773cpu_nf4_matmul_wrapper!(
4774    nf4_matmul_f16_cpu_wrapper,
4775    fuel_cpu_backend::byte_kernels::nf4_matmul_f16
4776);
4777cpu_nf4_matmul_wrapper!(
4778    nf4_matmul_bf16_cpu_wrapper,
4779    fuel_cpu_backend::byte_kernels::nf4_matmul_bf16
4780);
4781
4782/// Dispatch wrapper for `(FlashAttn, *, Cpu)`. Three or four inputs
4783/// (q, k, v, optional alibi_slopes). Geometry + math params flow
4784/// through `OpParams::FlashAttn`.
4785macro_rules! cpu_flash_attn_wrapper {
4786    ($wrapper:ident, $kernel:path) => {
4787        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
4788        // contract's forward-FlashAttn `entry_point` symbols to these wrappers.
4789        pub(crate) fn $wrapper(
4790            inputs: &[Arc<RwLock<Storage>>],
4791            outputs: &mut [Arc<RwLock<Storage>>],
4792            _layouts: &[Layout],
4793            params: &OpParams,
4794        ) -> Result<()> {
4795            if inputs.len() != 3 && inputs.len() != 4 {
4796                return Err(Error::Msg(format!(
4797                    "flash_attn wrapper expects 3 or 4 inputs (q, k, v, [alibi]), got {}",
4798                    inputs.len(),
4799                ))
4800                .bt());
4801            }
4802            if outputs.len() != 1 {
4803                return Err(Error::Msg(format!(
4804                    "flash_attn wrapper expects 1 output, got {}",
4805                    outputs.len(),
4806                ))
4807                .bt());
4808            }
4809            let (b, hq, hkv, sq, sk, d, k_len, scale, causal, wl, wr, softcap) = match params {
4810                OpParams::FlashAttn {
4811                    b,
4812                    hq,
4813                    hkv,
4814                    sq,
4815                    sk,
4816                    d,
4817                    k_len,
4818                    softmax_scale,
4819                    causal,
4820                    window_size_left,
4821                    window_size_right,
4822                    softcap,
4823                } => (
4824                    *b,
4825                    *hq,
4826                    *hkv,
4827                    *sq,
4828                    *sk,
4829                    *d,
4830                    *k_len,
4831                    *softmax_scale,
4832                    *causal,
4833                    *window_size_left,
4834                    *window_size_right,
4835                    *softcap,
4836                ),
4837                other => {
4838                    return Err(Error::Msg(format!(
4839                        "flash_attn wrapper expects OpParams::FlashAttn, got {other:?}",
4840                    ))
4841                    .bt())
4842                }
4843            };
4844            let q_guard = read_storage(&inputs[0])?;
4845            let k_guard = read_storage(&inputs[1])?;
4846            let v_guard = read_storage(&inputs[2])?;
4847            let alibi_guard = match inputs.get(3) {
4848                Some(arc) => Some(read_storage(arc)?),
4849                None => None,
4850            };
4851            let mut out_guard = write_storage(&outputs[0])?;
4852            let q_cpu = cpu_input(&q_guard)?;
4853            let k_cpu = cpu_input(&k_guard)?;
4854            let v_cpu = cpu_input(&v_guard)?;
4855            let alibi_cpu = match &alibi_guard {
4856                Some(g) => Some(cpu_input(g)?),
4857                None => None,
4858            };
4859            let out_cpu = cpu_output(&mut out_guard)?;
4860            $kernel(
4861                q_cpu, k_cpu, v_cpu, alibi_cpu, out_cpu, b, hq, hkv, sq, sk, d, k_len, scale,
4862                causal, wl, wr, softcap,
4863            )
4864        }
4865    };
4866}
4867
4868cpu_flash_attn_wrapper!(
4869    flash_attn_f32_cpu_wrapper,
4870    fuel_cpu_backend::byte_kernels::flash_attn_f32
4871);
4872cpu_flash_attn_wrapper!(
4873    flash_attn_f64_cpu_wrapper,
4874    fuel_cpu_backend::byte_kernels::flash_attn_f64
4875);
4876cpu_flash_attn_wrapper!(
4877    flash_attn_bf16_cpu_wrapper,
4878    fuel_cpu_backend::byte_kernels::flash_attn_bf16
4879);
4880cpu_flash_attn_wrapper!(
4881    flash_attn_f16_cpu_wrapper,
4882    fuel_cpu_backend::byte_kernels::flash_attn_f16
4883);
4884
4885/// Dispatch wrapper for `(FlashAttnBackward{Q,K,V}, *, Cpu)`. Four or
4886/// five inputs `(q, k, v, do, [alibi])`; one output (one of dQ/dK/dV).
4887/// The CPU kernel always computes all three gradients; this wrapper
4888/// only persists the requested one.
4889macro_rules! cpu_flash_attn_backward_wrapper {
4890    ($wrapper:ident, $kernel:path, $which:expr) => {
4891        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the attention
4892        // contract's FlashAttnBackward{Q,K,V} `entry_point` symbols to these wrappers.
4893        pub(crate) fn $wrapper(
4894            inputs: &[Arc<RwLock<Storage>>],
4895            outputs: &mut [Arc<RwLock<Storage>>],
4896            _layouts: &[Layout],
4897            params: &OpParams,
4898        ) -> Result<()> {
4899            if inputs.len() != 4 && inputs.len() != 5 {
4900                return Err(Error::Msg(format!(
4901                    "flash_attn_backward wrapper expects 4 or 5 inputs (q, k, v, do, [alibi]), got {}",
4902                    inputs.len(),
4903                ))
4904                .bt());
4905            }
4906            if outputs.len() != 1 {
4907                return Err(Error::Msg(format!(
4908                    "flash_attn_backward wrapper expects 1 output, got {}",
4909                    outputs.len(),
4910                ))
4911                .bt());
4912            }
4913            let (b, hq, hkv, sq, sk, d, scale, causal, wl, wr, softcap) = match params {
4914                OpParams::FlashAttn {
4915                    b, hq, hkv, sq, sk, d,
4916                    softmax_scale, causal,
4917                    window_size_left, window_size_right, softcap,
4918                    // Backward is the static (full-K) training path; the
4919                    // recompute attends the full K extent. k_len ignored.
4920                    k_len: _,
4921                } => (
4922                    *b, *hq, *hkv, *sq, *sk, *d,
4923                    *softmax_scale, *causal,
4924                    *window_size_left, *window_size_right, *softcap,
4925                ),
4926                other => {
4927                    return Err(Error::Msg(format!(
4928                        "flash_attn_backward wrapper expects OpParams::FlashAttn, got {other:?}",
4929                    ))
4930                    .bt())
4931                }
4932            };
4933            let q_guard = read_storage(&inputs[0])?;
4934            let k_guard = read_storage(&inputs[1])?;
4935            let v_guard = read_storage(&inputs[2])?;
4936            let do_guard = read_storage(&inputs[3])?;
4937            let alibi_guard = match inputs.get(4) {
4938                Some(arc) => Some(read_storage(arc)?),
4939                None => None,
4940            };
4941            let mut out_guard = write_storage(&outputs[0])?;
4942            let q_cpu = cpu_input(&q_guard)?;
4943            let k_cpu = cpu_input(&k_guard)?;
4944            let v_cpu = cpu_input(&v_guard)?;
4945            let do_cpu = cpu_input(&do_guard)?;
4946            let alibi_cpu = match &alibi_guard {
4947                Some(g) => Some(cpu_input(g)?),
4948                None => None,
4949            };
4950            let out_cpu = cpu_output(&mut out_guard)?;
4951            $kernel(
4952                q_cpu, k_cpu, v_cpu, do_cpu, alibi_cpu, out_cpu, $which,
4953                b, hq, hkv, sq, sk, d,
4954                scale, causal, wl, wr, softcap,
4955            )
4956        }
4957    };
4958}
4959
4960cpu_flash_attn_backward_wrapper!(
4961    flash_attn_backward_q_f32_cpu_wrapper,
4962    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4963    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4964);
4965cpu_flash_attn_backward_wrapper!(
4966    flash_attn_backward_k_f32_cpu_wrapper,
4967    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4968    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4969);
4970cpu_flash_attn_backward_wrapper!(
4971    flash_attn_backward_v_f32_cpu_wrapper,
4972    fuel_cpu_backend::byte_kernels::flash_attn_backward_f32,
4973    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
4974);
4975cpu_flash_attn_backward_wrapper!(
4976    flash_attn_backward_q_f64_cpu_wrapper,
4977    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4978    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4979);
4980cpu_flash_attn_backward_wrapper!(
4981    flash_attn_backward_k_f64_cpu_wrapper,
4982    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4983    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4984);
4985cpu_flash_attn_backward_wrapper!(
4986    flash_attn_backward_v_f64_cpu_wrapper,
4987    fuel_cpu_backend::byte_kernels::flash_attn_backward_f64,
4988    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
4989);
4990cpu_flash_attn_backward_wrapper!(
4991    flash_attn_backward_q_bf16_cpu_wrapper,
4992    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
4993    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
4994);
4995cpu_flash_attn_backward_wrapper!(
4996    flash_attn_backward_k_bf16_cpu_wrapper,
4997    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
4998    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
4999);
5000cpu_flash_attn_backward_wrapper!(
5001    flash_attn_backward_v_bf16_cpu_wrapper,
5002    fuel_cpu_backend::byte_kernels::flash_attn_backward_bf16,
5003    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5004);
5005cpu_flash_attn_backward_wrapper!(
5006    flash_attn_backward_q_f16_cpu_wrapper,
5007    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5008    fuel_cpu_backend::byte_kernels::FaBackwardWhich::Q
5009);
5010cpu_flash_attn_backward_wrapper!(
5011    flash_attn_backward_k_f16_cpu_wrapper,
5012    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5013    fuel_cpu_backend::byte_kernels::FaBackwardWhich::K
5014);
5015cpu_flash_attn_backward_wrapper!(
5016    flash_attn_backward_v_f16_cpu_wrapper,
5017    fuel_cpu_backend::byte_kernels::flash_attn_backward_f16,
5018    fuel_cpu_backend::byte_kernels::FaBackwardWhich::V
5019);
5020
5021/// Dispatch wrapper for `(PagedAttn, *, Cpu)`. 5 or 6 inputs (q,
5022/// k_cache, v_cache, block_table, context_lens, optional alibi_slopes).
5023macro_rules! cpu_paged_attn_wrapper {
5024    ($wrapper:ident, $kernel:path) => {
5025        // `pub(crate)` so the FKC `CpuLinkRegistry` (`CPU_ATTENTION_ENTRY_POINTS`)
5026        // can resolve the paged sections' `byte_kernels::paged_attn_<dt>` symbols
5027        // to these wrappers (the attention family is contract-sourced; §3.9.1).
5028        pub(crate) fn $wrapper(
5029            inputs: &[Arc<RwLock<Storage>>],
5030            outputs: &mut [Arc<RwLock<Storage>>],
5031            _layouts: &[Layout],
5032            params: &OpParams,
5033        ) -> Result<()> {
5034            if inputs.len() != 5 && inputs.len() != 6 {
5035                return Err(Error::Msg(format!(
5036                    "paged_attn wrapper expects 5 or 6 inputs, got {}",
5037                    inputs.len(),
5038                ))
5039                .bt());
5040            }
5041            if outputs.len() != 1 {
5042                return Err(Error::Msg(format!(
5043                    "paged_attn wrapper expects 1 output, got {}",
5044                    outputs.len(),
5045                ))
5046                .bt());
5047            }
5048            let (b, hq, hkv, sq, d, block_size, max_blocks_per_seq, num_blocks, scale, softcap) =
5049                match params {
5050                    OpParams::PagedAttn {
5051                        b,
5052                        hq,
5053                        hkv,
5054                        sq,
5055                        d,
5056                        block_size,
5057                        max_blocks_per_seq,
5058                        num_blocks,
5059                        softmax_scale,
5060                        softcap,
5061                    } => (
5062                        *b,
5063                        *hq,
5064                        *hkv,
5065                        *sq,
5066                        *d,
5067                        *block_size,
5068                        *max_blocks_per_seq,
5069                        *num_blocks,
5070                        *softmax_scale,
5071                        *softcap,
5072                    ),
5073                    other => {
5074                        return Err(Error::Msg(format!(
5075                            "paged_attn wrapper expects OpParams::PagedAttn, got {other:?}",
5076                        ))
5077                        .bt())
5078                    }
5079                };
5080            let q_g = read_storage(&inputs[0])?;
5081            let kc_g = read_storage(&inputs[1])?;
5082            let vc_g = read_storage(&inputs[2])?;
5083            let bt_g = read_storage(&inputs[3])?;
5084            let cl_g = read_storage(&inputs[4])?;
5085            let alibi_g = match inputs.get(5) {
5086                Some(arc) => Some(read_storage(arc)?),
5087                None => None,
5088            };
5089            if bt_g.dtype != DType::U32 || cl_g.dtype != DType::U32 {
5090                return Err(Error::Msg(format!(
5091                    "paged_attn: block_table and context_lens must be U32, got {:?} / {:?}",
5092                    bt_g.dtype, cl_g.dtype,
5093                ))
5094                .bt());
5095            }
5096            let mut out_guard = write_storage(&outputs[0])?;
5097            let q_cpu = cpu_input(&q_g)?;
5098            let kc_cpu = cpu_input(&kc_g)?;
5099            let vc_cpu = cpu_input(&vc_g)?;
5100            let bt_cpu = cpu_input(&bt_g)?;
5101            let cl_cpu = cpu_input(&cl_g)?;
5102            let alibi_cpu = match &alibi_g {
5103                Some(g) => Some(cpu_input(g)?),
5104                None => None,
5105            };
5106            let out_cpu = cpu_output(&mut out_guard)?;
5107            $kernel(
5108                q_cpu,
5109                kc_cpu,
5110                vc_cpu,
5111                bt_cpu,
5112                cl_cpu,
5113                alibi_cpu,
5114                out_cpu,
5115                b,
5116                hq,
5117                hkv,
5118                sq,
5119                d,
5120                block_size,
5121                max_blocks_per_seq,
5122                num_blocks,
5123                scale,
5124                softcap,
5125            )
5126        }
5127    };
5128}
5129
5130cpu_paged_attn_wrapper!(
5131    paged_attn_f32_cpu_wrapper,
5132    fuel_cpu_backend::byte_kernels::paged_attn_f32
5133);
5134cpu_paged_attn_wrapper!(
5135    paged_attn_f64_cpu_wrapper,
5136    fuel_cpu_backend::byte_kernels::paged_attn_f64
5137);
5138cpu_paged_attn_wrapper!(
5139    paged_attn_bf16_cpu_wrapper,
5140    fuel_cpu_backend::byte_kernels::paged_attn_bf16
5141);
5142cpu_paged_attn_wrapper!(
5143    paged_attn_f16_cpu_wrapper,
5144    fuel_cpu_backend::byte_kernels::paged_attn_f16
5145);
5146
5147// Cast wrappers — one per TARGET dtype, each matching every other source
5148// dtype. Together they cover the full 11×10 = 110 directed pair matrix
5149// (identity pairs excluded; the optimizer elides them). Every real numeric
5150// dtype is a complete closed cast basis.
5151cpu_cast_wrapper!(
5152    cast_to_f32_cpu_wrapper,
5153    DType::F32,
5154    "f32",
5155    {
5156        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f32,
5157        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f32,
5158        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f32,
5159        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f32,
5160        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f32,
5161        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f32,
5162        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f32,
5163        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f32,
5164        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f32,
5165        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f32,
5166        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f32,
5167    },
5168);
5169cpu_cast_wrapper!(
5170    cast_to_f64_cpu_wrapper,
5171    DType::F64,
5172    "f64",
5173    {
5174        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f64,
5175        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f64,
5176        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f64,
5177        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f64,
5178        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f64,
5179        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f64,
5180        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f64,
5181        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f64,
5182        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f64,
5183        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f64,
5184        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f64,
5185    },
5186);
5187cpu_cast_wrapper!(
5188    cast_to_bf16_cpu_wrapper,
5189    DType::BF16,
5190    "bf16",
5191    {
5192        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bf16,
5193        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bf16,
5194        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bf16,
5195        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bf16,
5196        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bf16,
5197        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bf16,
5198        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bf16,
5199        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bf16,
5200        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bf16,
5201        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bf16,
5202        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_bf16,
5203    },
5204);
5205cpu_cast_wrapper!(
5206    cast_to_f16_cpu_wrapper,
5207    DType::F16,
5208    "f16",
5209    {
5210        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f16,
5211        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f16,
5212        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f16,
5213        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_f16,
5214        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f16,
5215        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f16,
5216        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f16,
5217        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f16,
5218        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f16,
5219        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f16,
5220        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f16,
5221    },
5222);
5223cpu_cast_wrapper!(
5224    cast_to_f8e4m3_cpu_wrapper,
5225    DType::F8E4M3,
5226    "f8e4m3",
5227    {
5228        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_f8e4m3,
5229        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_f8e4m3,
5230        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_f8e4m3,
5231        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_f8e4m3,
5232        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_f8e4m3,
5233        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_f8e4m3,
5234        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_f8e4m3,
5235        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_f8e4m3,
5236        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_f8e4m3,
5237        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_f8e4m3,
5238        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_f8e4m3,
5239    },
5240);
5241cpu_cast_wrapper!(
5242    cast_to_u8_cpu_wrapper,
5243    DType::U8,
5244    "u8",
5245    {
5246        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u8,
5247        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u8,
5248        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u8,
5249        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u8,
5250        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u8,
5251        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u8,
5252        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_u8,
5253        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u8,
5254        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u8,
5255        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u8,
5256        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u8,
5257    },
5258);
5259cpu_cast_wrapper!(
5260    cast_to_i8_cpu_wrapper,
5261    DType::I8,
5262    "i8",
5263    {
5264        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i8,
5265        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i8,
5266        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i8,
5267        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i8,
5268        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i8,
5269        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i8,
5270        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i8,
5271        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i8,
5272        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i8,
5273        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i8,
5274        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i8,
5275    },
5276);
5277cpu_cast_wrapper!(
5278    cast_to_u32_cpu_wrapper,
5279    DType::U32,
5280    "u32",
5281    {
5282        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_u32,
5283        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_u32,
5284        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_u32,
5285        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_u32,
5286        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_u32,
5287        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_u32,
5288        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_u32,
5289        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_u32,
5290        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_u32,
5291        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_u32,
5292        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_u32,
5293    },
5294);
5295cpu_cast_wrapper!(
5296    cast_to_i16_cpu_wrapper,
5297    DType::I16,
5298    "i16",
5299    {
5300        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i16,
5301        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i16,
5302        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i16,
5303        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i16,
5304        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i16,
5305        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i16,
5306        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i16,
5307        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i16,
5308        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i16,
5309        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i16,
5310        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i16,
5311    },
5312);
5313cpu_cast_wrapper!(
5314    cast_to_i32_cpu_wrapper,
5315    DType::I32,
5316    "i32",
5317    {
5318        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i32,
5319        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i32,
5320        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i32,
5321        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i32,
5322        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i32,
5323        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i32,
5324        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i32,
5325        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i32,
5326        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i32,
5327        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_i32,
5328        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i32,
5329    },
5330);
5331cpu_cast_wrapper!(
5332    cast_to_i64_cpu_wrapper,
5333    DType::I64,
5334    "i64",
5335    {
5336        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_i64,
5337        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_i64,
5338        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_i64,
5339        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_i64,
5340        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_i64,
5341        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_i64,
5342        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_i64,
5343        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_i64,
5344        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_i64,
5345        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_i64,
5346        DType::Bool    => fuel_cpu_backend::byte_kernels::cast_bool_to_i64,
5347    },
5348);
5349
5350// Cast TO Bool (GAP-168) -- the 12th target. `Bool` is byte-backed like `U8`,
5351// so this wrapper exists precisely to keep the two DISTINGUISHABLE: every arm
5352// runs a real `!= 0` conversion rather than reinterpreting the source bytes.
5353cpu_cast_wrapper!(
5354    cast_to_bool_cpu_wrapper,
5355    DType::Bool,
5356    "bool",
5357    {
5358        DType::F32     => fuel_cpu_backend::byte_kernels::cast_f32_to_bool,
5359        DType::F64     => fuel_cpu_backend::byte_kernels::cast_f64_to_bool,
5360        DType::F16     => fuel_cpu_backend::byte_kernels::cast_f16_to_bool,
5361        DType::BF16    => fuel_cpu_backend::byte_kernels::cast_bf16_to_bool,
5362        DType::F8E4M3  => fuel_cpu_backend::byte_kernels::cast_f8e4m3_to_bool,
5363        DType::U8      => fuel_cpu_backend::byte_kernels::cast_u8_to_bool,
5364        DType::I8      => fuel_cpu_backend::byte_kernels::cast_i8_to_bool,
5365        DType::U32     => fuel_cpu_backend::byte_kernels::cast_u32_to_bool,
5366        DType::I16     => fuel_cpu_backend::byte_kernels::cast_i16_to_bool,
5367        DType::I32     => fuel_cpu_backend::byte_kernels::cast_i32_to_bool,
5368        DType::I64     => fuel_cpu_backend::byte_kernels::cast_i64_to_bool,
5369    },
5370);
5371
5372/// Dispatch wrapper for `(MatMul, F32, Cpu)`. Extracts the
5373/// `OpParams::Matmul { m, n, k }` and forwards to the typed
5374/// kernel. Both inputs are guaranteed contiguous f32 by the
5375/// executor's auto-Contiguize pass.
5376///
5377/// `pub(crate)` so the FKC `CpuLinkRegistry` (`fkc::cpu_link`,
5378/// [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) can resolve the matmul contract's
5379/// `entry_point` symbol to this exact wrapper fn-pointer.
5380pub(crate) fn matmul_f32_cpu_wrapper(
5381    inputs: &[Arc<RwLock<Storage>>],
5382    outputs: &mut [Arc<RwLock<Storage>>],
5383    _layouts: &[Layout],
5384    params: &OpParams,
5385) -> Result<()> {
5386    if inputs.len() != 2 {
5387        return Err(Error::Msg(format!(
5388            "matmul wrapper expects 2 inputs, got {}",
5389            inputs.len(),
5390        ))
5391        .bt());
5392    }
5393    if outputs.len() != 1 {
5394        return Err(Error::Msg(format!(
5395            "matmul wrapper expects 1 output, got {}",
5396            outputs.len(),
5397        ))
5398        .bt());
5399    }
5400    let (lhs_batch_dims, rhs_batch_dims, m, n, k, m_compute) = match params {
5401        OpParams::Matmul {
5402            lhs_batch_dims,
5403            rhs_batch_dims,
5404            m,
5405            n,
5406            k,
5407            m_compute,
5408        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k, m_compute),
5409        other => {
5410            return Err(Error::Msg(format!(
5411                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5412            ))
5413            .bt());
5414        }
5415    };
5416    // Data-determined-M (sparse MoE): `m` is the row capacity; compute only
5417    // `rows`. `Deferred` must have been resolved at execute before the
5418    // kernel runs (see resolve_deferred_matmul).
5419    let rows = match m_compute {
5420        MatmulM::All => m,
5421        MatmulM::Rows(c) => *c,
5422        MatmulM::Deferred(d) => {
5423            return Err(Error::Msg(format!(
5424                "matmul_f32 wrapper: unresolved data-determined row count {d:?} \
5425                 (must be resolved at execute before the kernel runs)",
5426            ))
5427            .bt());
5428        }
5429    };
5430    let lhs_guard = read_storage(&inputs[0])?;
5431    let rhs_guard = read_storage(&inputs[1])?;
5432    let mut out_guard = write_storage(&outputs[0])?;
5433    let lhs_cpu = cpu_input(&lhs_guard)?;
5434    let rhs_cpu = cpu_input(&rhs_guard)?;
5435    let out_cpu = cpu_output(&mut out_guard)?;
5436    fuel_cpu_backend::byte_kernels::matmul_f32_capacity(
5437        lhs_cpu,
5438        rhs_cpu,
5439        out_cpu,
5440        lhs_batch_dims,
5441        rhs_batch_dims,
5442        m,
5443        rows,
5444        n,
5445        k,
5446    )
5447}
5448
5449/// Build a CPU matmul wrapper for any element type. The wrapper
5450/// shape is identical across dtypes — it just forwards to a typed
5451/// kernel that has the matching `(lhs, rhs, out, lhs_batch_dims,
5452/// rhs_batch_dims, m, n, k) -> Result<()>` signature.
5453macro_rules! cpu_matmul_wrapper {
5454    ($wrapper:ident, $kernel:path, $type_name:literal) => {
5455        // `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul
5456        // contract's `entry_point` symbols to these wrapper fn-pointers.
5457        pub(crate) fn $wrapper(
5458            inputs: &[Arc<RwLock<Storage>>],
5459            outputs: &mut [Arc<RwLock<Storage>>],
5460            _layouts: &[Layout],
5461            params: &OpParams,
5462        ) -> Result<()> {
5463            if inputs.len() != 2 {
5464                return Err(Error::Msg(format!(
5465                    "matmul wrapper expects 2 inputs, got {}",
5466                    inputs.len(),
5467                ))
5468                .bt());
5469            }
5470            if outputs.len() != 1 {
5471                return Err(Error::Msg(format!(
5472                    "matmul wrapper expects 1 output, got {}",
5473                    outputs.len(),
5474                ))
5475                .bt());
5476            }
5477            let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5478                OpParams::Matmul {
5479                    lhs_batch_dims,
5480                    rhs_batch_dims,
5481                    m,
5482                    n,
5483                    k,
5484                    ..
5485                } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5486                other => {
5487                    return Err(Error::Msg(format!(
5488                        "matmul wrapper expects OpParams::Matmul, got {other:?}",
5489                    ))
5490                    .bt())
5491                }
5492            };
5493            let lhs_guard = read_storage(&inputs[0])?;
5494            let rhs_guard = read_storage(&inputs[1])?;
5495            let mut out_guard = write_storage(&outputs[0])?;
5496            let lhs_cpu = cpu_input(&lhs_guard)?;
5497            let rhs_cpu = cpu_input(&rhs_guard)?;
5498            let out_cpu = cpu_output(&mut out_guard)?;
5499            let _ = $type_name;
5500            $kernel(
5501                lhs_cpu,
5502                rhs_cpu,
5503                out_cpu,
5504                lhs_batch_dims,
5505                rhs_batch_dims,
5506                m,
5507                n,
5508                k,
5509            )
5510        }
5511    };
5512}
5513
5514cpu_matmul_wrapper!(
5515    matmul_bf16_cpu_wrapper,
5516    fuel_cpu_backend::byte_kernels::matmul_bf16,
5517    "matmul_bf16"
5518);
5519cpu_matmul_wrapper!(
5520    matmul_f16_cpu_wrapper,
5521    fuel_cpu_backend::byte_kernels::matmul_f16,
5522    "matmul_f16"
5523);
5524cpu_matmul_wrapper!(
5525    matmul_f32_bf16_cpu_wrapper,
5526    fuel_cpu_backend::byte_kernels::matmul_f32_bf16,
5527    "matmul_f32_bf16"
5528);
5529cpu_matmul_wrapper!(
5530    matmul_f32_f16_cpu_wrapper,
5531    fuel_cpu_backend::byte_kernels::matmul_f32_f16,
5532    "matmul_f32_f16"
5533);
5534cpu_matmul_wrapper!(
5535    matmul_i8_cpu_wrapper,
5536    fuel_cpu_backend::byte_kernels::matmul_i8,
5537    "matmul_i8"
5538);
5539cpu_matmul_wrapper!(
5540    matmul_u8_cpu_wrapper,
5541    fuel_cpu_backend::byte_kernels::matmul_u8,
5542    "matmul_u8"
5543);
5544
5545/// f64 mirror of [`matmul_f32_cpu_wrapper`]. Same OpKind
5546/// (MatMul); the binding-table key picks this entry when the
5547/// node's dtype is F64.
5548///
5549/// `pub(crate)` so the FKC `CpuLinkRegistry` can resolve the matmul contract's
5550/// `entry_point` symbol to this exact wrapper fn-pointer.
5551pub(crate) fn matmul_f64_cpu_wrapper(
5552    inputs: &[Arc<RwLock<Storage>>],
5553    outputs: &mut [Arc<RwLock<Storage>>],
5554    _layouts: &[Layout],
5555    params: &OpParams,
5556) -> Result<()> {
5557    if inputs.len() != 2 {
5558        return Err(Error::Msg(format!(
5559            "matmul wrapper expects 2 inputs, got {}",
5560            inputs.len(),
5561        ))
5562        .bt());
5563    }
5564    if outputs.len() != 1 {
5565        return Err(Error::Msg(format!(
5566            "matmul wrapper expects 1 output, got {}",
5567            outputs.len(),
5568        ))
5569        .bt());
5570    }
5571    let (lhs_batch_dims, rhs_batch_dims, m, n, k) = match params {
5572        OpParams::Matmul {
5573            lhs_batch_dims,
5574            rhs_batch_dims,
5575            m,
5576            n,
5577            k,
5578            ..
5579        } => (lhs_batch_dims, rhs_batch_dims, *m, *n, *k),
5580        other => {
5581            return Err(Error::Msg(format!(
5582                "matmul wrapper expects OpParams::Matmul, got {other:?}",
5583            ))
5584            .bt());
5585        }
5586    };
5587    let lhs_guard = read_storage(&inputs[0])?;
5588    let rhs_guard = read_storage(&inputs[1])?;
5589    let mut out_guard = write_storage(&outputs[0])?;
5590    let lhs_cpu = cpu_input(&lhs_guard)?;
5591    let rhs_cpu = cpu_input(&rhs_guard)?;
5592    let out_cpu = cpu_output(&mut out_guard)?;
5593    fuel_cpu_backend::byte_kernels::matmul_f64(
5594        lhs_cpu,
5595        rhs_cpu,
5596        out_cpu,
5597        lhs_batch_dims,
5598        rhs_batch_dims,
5599        m,
5600        n,
5601        k,
5602    )
5603}
5604
5605/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cpu)` — copy from a
5606/// CPU source storage into a freshly-allocated output on any target
5607/// backend. The executor allocates the output on `target_location`
5608/// via [`crate::pipelined::WorkItemKind::Copy`] before this wrapper
5609/// runs; the wrapper switches on the output's `BackendStorage`
5610/// variant to pick the H2D path.
5611///
5612/// - CPU output → memcpy (CPU→CPU).
5613/// - CUDA output → `CudaStorageBytes::write_from_host` (H2D via
5614///   `cuMemcpyHtoD`).
5615/// - Vulkan output → `VulkanBackend::write_bytes` (H2D via staging
5616///   buffer + `vkCmdCopyBuffer`).
5617///
5618/// Bridge-retirement Phase 2 (CPU→CPU) + Phase 3b (CPU→GPU). The
5619/// wrapper-internal match on output variant is the pragmatic shape
5620/// while the binding-table key `(op, dtypes, source_backend)` doesn't
5621/// yet encode the target. A future binding-table-key extension would
5622/// split this into per-(source, target) sub-wrappers without changing
5623/// the call surface.
5624///
5625/// Replaces:
5626/// * The per-variant `match self` in `BackendStorage::read_to_cpu_bytes`
5627///   (Phase 2 deletion).
5628/// * `fuel-tensor::pipelined_bridge::upload_host_buffer`'s per-
5629///   `DeviceLocation` match (Phase 3b deletion).
5630fn copy_from_cpu_wrapper(
5631    inputs: &[Arc<RwLock<Storage>>],
5632    outputs: &mut [Arc<RwLock<Storage>>],
5633    _layouts: &[Layout],
5634    _params: &OpParams,
5635) -> Result<()> {
5636    if inputs.len() != 1 || outputs.len() != 1 {
5637        return Err(Error::Msg(format!(
5638            "copy_from_cpu_wrapper: expected 1 input + 1 output, got {} + {}",
5639            inputs.len(),
5640            outputs.len(),
5641        ))
5642        .bt());
5643    }
5644    let in_guard = read_storage(&inputs[0])?;
5645    let src = cpu_input(&in_guard)?;
5646    let mut out_guard = write_storage(&outputs[0])?;
5647    // Truncate source bytes to the destination's byte count — the
5648    // executor allocates the output exactly `node.shape.elem_count *
5649    // dtype.size_in_bytes()` bytes. Host buffers from Op::Const slots
5650    // may be larger (shared storage across views); we copy only the
5651    // destination-sized prefix. Mirrors the deleted
5652    // `upload_host_buffer`'s `truncate_to` parameter.
5653    let n_out = out_guard.inner.len_bytes();
5654    let n_src = src.len_bytes();
5655    let n = n_src.min(n_out);
5656    let src_slice = &src.bytes()[..n];
5657    match &mut out_guard.inner {
5658        BackendStorage::Cpu(dst) => {
5659            dst.bytes_mut()[..n].copy_from_slice(src_slice);
5660        }
5661        #[cfg(feature = "cuda")]
5662        BackendStorage::Cuda(dst) => {
5663            // CUDA write_from_host requires src.len() == dst.len_bytes.
5664            // The executor sized the output to `n_out`; we truncated
5665            // src to `n` = min(n_src, n_out). When n < n_out the
5666            // remaining bytes stay uninit; for the Op::Const upload
5667            // path this matches the deleted upload_host_buffer's
5668            // behavior (truncated host bytes uploaded as-is).
5669            if n == n_out {
5670                dst.write_from_host(src_slice)?;
5671            } else {
5672                // Pad: copy src into a staging vec sized exactly n_out
5673                // with trailing zeros. Rare path (size mismatch).
5674                let mut staged = vec![0_u8; n_out];
5675                staged[..n].copy_from_slice(src_slice);
5676                dst.write_from_host(&staged)?;
5677            }
5678        }
5679        #[cfg(feature = "vulkan")]
5680        BackendStorage::Vulkan(dst) => {
5681            let backend = dst
5682                .backend()
5683                .ok_or_else(|| {
5684                    Error::Msg(
5685                        "copy_from_cpu_wrapper: Vulkan output has no attached \
5686                 backend handle. The executor's Op::Copy arm must allocate \
5687                 via VulkanBackend::alloc_bytes_handle (which attaches \
5688                 the handle)."
5689                            .to_string(),
5690                    )
5691                    .bt()
5692                })?
5693                .clone();
5694            if n == n_out {
5695                backend.write_bytes(dst, src_slice)?;
5696            } else {
5697                let mut staged = vec![0_u8; n_out];
5698                staged[..n].copy_from_slice(src_slice);
5699                backend.write_bytes(dst, &staged)?;
5700            }
5701        }
5702        #[allow(unreachable_patterns)]
5703        other => {
5704            return Err(Error::Msg(format!(
5705                "copy_from_cpu_wrapper: output backend not wired ({other:?}); \
5706                 CPU + CUDA + Vulkan covered, Metal extends when its \
5707                 byte-storage substrate is ready.",
5708            ))
5709            .bt());
5710        }
5711    }
5712    Ok(())
5713}
5714
5715/// The authored CPU elementwise-binary kernel contract, embedded into the
5716/// binary. This is the PRODUCTION `include_str!` (distinct from the identical
5717/// path used in the `fkc::register` test module); `register_cpu_binary_from_contract`
5718/// parses + lowers it and binds the family FROM THE CONTRACT.
5719const CPU_ELEMENTWISE_BINARY_CONTRACT: &str =
5720    include_str!("../kernel-contracts/cpu/elementwise-binary.fkc.md");
5721
5722/// Register the CPU elementwise-binary family (8 ops × 4 dtypes = 32
5723/// bindings) by IMPORTING its FKC kernel contract — the FIRST production
5724/// FKC consumer. FKC is unconditional core infrastructure, so this is the
5725/// ONE registration path for the family: there is no hand-written fallback
5726/// (deleting it was the point — a build that lost the importer would silently
5727/// lose the family).
5728///
5729/// The authored contract `fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`
5730/// is parsed + lowered and each `entry_point` symbol resolved through the
5731/// production [`crate::fkc::CpuLinkRegistry`] to the exact same wrapper
5732/// fn-pointers the CPU backend exposes (`add_elementwise_f32_cpu_wrapper`, …;
5733/// the very map [`crate::fkc::CPU_BINARY_ENTRY_POINTS`] holds). Relative to the
5734/// deleted hand-written registrations this is behavior-preserving: identical
5735/// kernels + caps; the binding's `kernel_source` becomes the contract's
5736/// `"portable-cpu"` tag and its precision the contract's audited claim. Cost is
5737/// preserved because this runs BEFORE the `fill_unset_cpu_cost` pass, which
5738/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind
5739/// cost fn every other CPU primitive gets.
5740///
5741/// Fused-registry decision: the elementwise-binary family declares NO fused
5742/// ops (`provider.fused` is empty), and `register_cpu_kernels` threads only a
5743/// `KernelBindingTable` — there is no paired global `FusedKernelRegistry` at
5744/// this seam (the static `crate::fused::default_kernel_registry()` is built
5745/// independently). So `register_into`'s required fused argument is a local
5746/// throwaway that provably stays empty.
5747///
5748/// Init-boundary fail-fast: a parse/lower/link failure of the embedded,
5749/// authored contract is a programmer error surfaced once here via `expect`
5750/// (mirroring the `finalize().expect(...)` convention in [`global_bindings`]).
5751/// It cannot fail for a runtime-data reason — the contract is `include_str!`'d
5752/// into the binary and the link registry is exhaustive for this family.
5753fn register_cpu_binary_from_contract(table: &mut KernelBindingTable) {
5754    let provider = crate::fkc::import_bundle_str(
5755        CPU_ELEMENTWISE_BINARY_CONTRACT,
5756        &crate::fkc::CpuLinkRegistry,
5757    )
5758    .expect(
5759        "authored CPU elementwise-binary contract must import \
5760                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5761    );
5762    debug_assert!(
5763        provider.fused.is_empty(),
5764        "elementwise-binary contract declares no fused ops",
5765    );
5766    let mut fused = crate::fused::FusedKernelRegistry::new();
5767    provider
5768        .register_into(table, &mut fused)
5769        .expect("CPU elementwise-binary contract must register into the binding table");
5770}
5771
5772/// The authored CPU affine / clamp / powi kernel contract, embedded into the
5773/// binary (the PRODUCTION `include_str!`). `register_cpu_affine_clamp_powi_from_contract`
5774/// parses + lowers it and binds the family FROM THE CONTRACT.
5775const CPU_AFFINE_CLAMP_POWI_CONTRACT: &str =
5776    include_str!("../kernel-contracts/cpu/affine-clamp-powi.fkc.md");
5777
5778/// Register the CPU out-of-place scalar-param family (affine/clamp/powi × 4
5779/// dtypes + powi_backward × 4 = 16 bindings) by IMPORTING its FKC kernel
5780/// contract — the second production FKC consumer, mirroring
5781/// [`register_cpu_binary_from_contract`]. FKC is unconditional core
5782/// infrastructure, so this is the ONE registration path for the family: the
5783/// hand-written `table.register(...)` calls it used to carry are DELETED.
5784///
5785/// Each `entry_point` symbol resolves through the production
5786/// [`crate::fkc::CpuLinkRegistry`] (now chaining
5787/// [`crate::fkc::CPU_AFFINE_CLAMP_POWI_ENTRY_POINTS`]) to the exact same wrapper
5788/// fn-pointers the CPU backend exposes. Behavior-preserving vs. the deleted
5789/// hand-written path: identical kernels + caps (contiguous-only); the binding's
5790/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its precision
5791/// the contract's audited bit-stable claim. Cost is preserved because this runs
5792/// BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
5793/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
5794///
5795/// The scalar params (affine mul/add, clamp min/max, powi exp) ride in
5796/// `OpParams`, NOT the dtype-list, so the imported binding keys are `[t, t]` for
5797/// the single-input forward ops and `[t, t, t]` for the two-input
5798/// `powi_backward` — identical to the deleted `&unary(t)` / `&binary(t)` regs.
5799///
5800/// The family declares NO fused ops (the FusedOps::POWI_BACKWARD fused-registry
5801/// registration is a SEPARATE seam, untouched), so `register_into`'s required
5802/// fused argument is a local throwaway that provably stays empty.
5803fn register_cpu_affine_clamp_powi_from_contract(table: &mut KernelBindingTable) {
5804    let provider =
5805        crate::fkc::import_bundle_str(CPU_AFFINE_CLAMP_POWI_CONTRACT, &crate::fkc::CpuLinkRegistry)
5806            .expect(
5807                "authored CPU affine/clamp/powi contract must import \
5808                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5809            );
5810    debug_assert!(
5811        provider.fused.is_empty(),
5812        "affine/clamp/powi contract declares no fused ops",
5813    );
5814    let mut fused = crate::fused::FusedKernelRegistry::new();
5815    provider
5816        .register_into(table, &mut fused)
5817        .expect("CPU affine/clamp/powi contract must register into the binding table");
5818}
5819
5820/// The authored CPU elementwise-unary kernel contract, embedded into the binary
5821/// (the PRODUCTION `include_str!`). `register_cpu_unary_from_contract` parses +
5822/// lowers it and binds the family FROM THE CONTRACT.
5823const CPU_ELEMENTWISE_UNARY_CONTRACT: &str =
5824    include_str!("../kernel-contracts/cpu/elementwise-unary.fkc.md");
5825
5826/// Register the CPU elementwise-unary family (22 ops × 4 dtypes = 88 bindings)
5827/// by IMPORTING its FKC kernel contract — the third production FKC consumer,
5828/// mirroring [`register_cpu_binary_from_contract`] /
5829/// [`register_cpu_affine_clamp_powi_from_contract`]. FKC is unconditional core
5830/// infrastructure, so this is the ONE registration path for the family: the
5831/// hand-written `table.register(...)` calls it used to carry are DELETED.
5832///
5833/// This is the **first** consumer of the §3.4 multi-dtype fan-out: each per-op
5834/// section declares a BASE `entry_point` (e.g. `…::relu`) and enumerates
5835/// `dtypes: [F32, F64, BF16, F16]`; the importer fans it into one binding per
5836/// dtype, resolving `<base>_<dtype>` through the production
5837/// [`crate::fkc::CpuLinkRegistry`] (now chaining
5838/// [`crate::fkc::CPU_UNARY_ENTRY_POINTS`]) to the exact same wrapper fn-pointers
5839/// the CPU backend exposes. Behavior-preserving vs. the deleted hand-written
5840/// path: identical kernels + caps (contiguous-only, `[t, t]` keys); the
5841/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
5842/// precision the contract's bit-stable claim. Cost is preserved because this
5843/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
5844/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
5845///
5846/// `gelu_tanh` (`OpKind::GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
5847/// (`OpKind::GeluElementwise`, base `gelu`) stay DISTINCT — the exact-erf
5848/// GELU must never be confused with the tanh approximation under a Judge epsilon.
5849///
5850/// The family declares NO fused ops, so `register_into`'s required fused argument
5851/// is a local throwaway that provably stays empty.
5852fn register_cpu_unary_from_contract(table: &mut KernelBindingTable) {
5853    let provider =
5854        crate::fkc::import_bundle_str(CPU_ELEMENTWISE_UNARY_CONTRACT, &crate::fkc::CpuLinkRegistry)
5855            .expect(
5856                "authored CPU elementwise-unary contract must import \
5857                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5858            );
5859    debug_assert!(
5860        provider.fused.is_empty(),
5861        "elementwise-unary contract declares no fused ops",
5862    );
5863    let mut fused = crate::fused::FusedKernelRegistry::new();
5864    provider
5865        .register_into(table, &mut fused)
5866        .expect("CPU elementwise-unary contract must register into the binding table");
5867}
5868
5869/// The authored CPU compare + where kernel contract, embedded into the binary
5870/// (the PRODUCTION `include_str!`). `register_cpu_compare_where_from_contract`
5871/// parses + lowers it and binds the family FROM THE CONTRACT.
5872const CPU_COMPARE_WHERE_CONTRACT: &str =
5873    include_str!("../kernel-contracts/cpu/compare-where.fkc.md");
5874
5875/// Register the CPU compare (6 ops × 4 dtypes = 24) + where (1 op × 4 dtypes =
5876/// 4) family — 28 bindings — by IMPORTING its FKC kernel contract, the fourth
5877/// production FKC consumer (mirroring the binary / affine-clamp-powi / unary
5878/// importers). FKC is unconditional core infrastructure, so this is the ONE
5879/// registration path for the family: the hand-written `table.register(...)`
5880/// calls it used to carry are DELETED.
5881///
5882/// Two contract shapes, both resolved through the production
5883/// [`crate::fkc::CpuLinkRegistry`] (now chaining
5884/// [`crate::fkc::CPU_COMPARE_ENTRY_POINTS`] + [`crate::fkc::CPU_WHERE_ENTRY_POINTS`]):
5885///  - the 24 per-(op,dtype) COMPARE thunks are single-dtype sections → each
5886///    resolves its declared `_u8`-suffixed symbol (`eq_f32_u8`, …) AS-IS; the
5887///    binding key is `[T, T, U8]` (output is the `fixed(U8)` mask), identical
5888///    to the deleted `&compare(t)` regs.
5889///  - the single WHERE section rides the §3.4 multi-dtype fan-out — its BASE
5890///    `entry_point` `…::where` expands to `where_{f32,f64,bf16,f16}`, one
5891///    binding per dtype, key `[U8, T, T, T]` (cond U8 + `passthrough(a)` → T),
5892///    identical to the deleted `&where_dts(t)` regs.
5893///
5894/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
5895/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
5896/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
5897/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
5898/// which upgrades the imported entries' `unknown_cost` sentinel to the same
5899/// OpKind cost fn every CPU primitive gets. The `## compare` chassis umbrella is
5900/// `registrable: false` (§3.10) and never registers. The family declares NO
5901/// fused ops, so `register_into`'s required fused argument is a local throwaway
5902/// that provably stays empty.
5903fn register_cpu_compare_where_from_contract(table: &mut KernelBindingTable) {
5904    let provider =
5905        crate::fkc::import_bundle_str(CPU_COMPARE_WHERE_CONTRACT, &crate::fkc::CpuLinkRegistry)
5906            .expect(
5907                "authored CPU compare/where contract must import \
5908                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5909            );
5910    debug_assert!(
5911        provider.fused.is_empty(),
5912        "compare/where contract declares no fused ops",
5913    );
5914    let mut fused = crate::fused::FusedKernelRegistry::new();
5915    provider
5916        .register_into(table, &mut fused)
5917        .expect("CPU compare/where contract must register into the binding table");
5918}
5919
5920/// The authored CPU reduce kernel contract, embedded into the binary (the
5921/// PRODUCTION `include_str!`). `register_cpu_reduce_from_contract` parses +
5922/// lowers it and binds the family FROM THE CONTRACT.
5923const CPU_REDUCE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce.fkc.md");
5924
5925/// Register the CPU per-axis reduce family (Sum/Mean/Max/Min × 4 dtypes = 16
5926/// bindings) by IMPORTING its FKC kernel contract, the fifth production FKC
5927/// consumer (mirroring the binary / affine-clamp-powi / unary / compare-where
5928/// importers). FKC is unconditional core infrastructure, so this is the ONE
5929/// registration path for the family: the hand-written `table.register(...)`
5930/// calls it used to carry are DELETED.
5931///
5932/// Each of the 16 per-(op, dtype) sections (`## sum_reduce_f32`, …) is a SPECIFIC
5933/// single-dtype contract with a concrete `entry_point` (`…::sum_reduce_f32`), so
5934/// none of them fan — the importer resolves each declared symbol AS-IS through
5935/// the production [`crate::fkc::CpuLinkRegistry`] (now chaining
5936/// [`crate::fkc::CPU_REDUCE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
5937/// CPU backend exposes. The binding key is `[T, T]` (input + `passthrough(input)`
5938/// output; the reduce axes + keepdim ride in `OpParams::Reduce`, NOT the
5939/// dtype-list), identical to the deleted `&unary(t)` regs.
5940///
5941/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
5942/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
5943/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
5944/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
5945/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
5946/// fn every CPU primitive gets. The `## reduce` chassis umbrella is
5947/// `registrable: false` (§3.10) and never registers (without it the chassis would
5948/// double-register `SumReduce`/`[F32]` → `DuplicateKernelRef` at init). The
5949/// f32-only `argmax_dim_f32` / `argmin_dim_f32` sections are `registrable: false`
5950/// (DEFERRED — production registers `Arg{Max,Min}Dim` for ALL input dtypes via
5951/// the hand-written `arg{max,min}_dim_u32_cpu_dispatch`, which stays untouched
5952/// below). The family declares NO fused ops, so `register_into`'s required fused
5953/// argument is a local throwaway that provably stays empty.
5954fn register_cpu_reduce_from_contract(table: &mut KernelBindingTable) {
5955    let provider = crate::fkc::import_bundle_str(CPU_REDUCE_CONTRACT, &crate::fkc::CpuLinkRegistry)
5956        .expect(
5957            "authored CPU reduce contract must import \
5958                 (embedded via include_str!, resolved through CpuLinkRegistry)",
5959        );
5960    debug_assert!(
5961        provider.fused.is_empty(),
5962        "reduce contract declares no fused ops",
5963    );
5964    let mut fused = crate::fused::FusedKernelRegistry::new();
5965    provider
5966        .register_into(table, &mut fused)
5967        .expect("CPU reduce contract must register into the binding table");
5968}
5969
5970/// The authored CPU reduce-to kernel contract, embedded into the binary (the
5971/// PRODUCTION `include_str!`). `register_cpu_reduce_to_from_contract` parses +
5972/// lowers it and binds the family FROM THE CONTRACT.
5973const CPU_REDUCE_TO_CONTRACT: &str = include_str!("../kernel-contracts/cpu/reduce-to.fkc.md");
5974
5975/// Register the CPU broadcast-target reduce-to family (ReduceSumTo /
5976/// ReduceMaxTo × 4 dtypes = 8, key `[T, T]`; ReduceMaxToBackward × 4 dtypes = 4,
5977/// key `[T, T, T]` = 12 bindings) by IMPORTING its FKC kernel contract, the
5978/// sixth production FKC consumer (mirroring the binary / affine-clamp-powi /
5979/// unary / compare-where / reduce importers). FKC is unconditional core
5980/// infrastructure, so this is the ONE registration path for the family: the
5981/// hand-written `table.register(...)` calls it used to carry are DELETED.
5982///
5983/// Each of the 12 per-(op, dtype) sections (`## reduce_sum_to_f32`, …) is a
5984/// SPECIFIC single-dtype contract with a concrete `entry_point`
5985/// (`…::reduce_sum_to_f32`), so none of them fan — the importer resolves each
5986/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
5987/// (now chaining [`crate::fkc::CPU_REDUCE_TO_ENTRY_POINTS`]) to the exact
5988/// wrapper fn-pointer the CPU backend exposes. The forward binding key is
5989/// `[T, T]` (input + `passthrough(input)` output — the target
5990/// `input_shape`/`output_shape` ride in `OpParams::ReduceSumTo` /
5991/// `OpParams::ReduceMaxTo`, NOT the dtype-list), identical to the deleted
5992/// `&unary(t)` regs; the backward key is `[T, T, T]` (x, upstream +
5993/// `passthrough(x)` output), identical to the deleted `&binary(t)` regs.
5994///
5995/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
5996/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
5997/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
5998/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`,
5999/// which upgrades the imported entries' `unknown_cost` sentinel to the same
6000/// OpKind cost fn every CPU primitive gets (ReduceMaxToBackward keeps its own
6001/// `cost_reduce_max_to_backward_cpu` fill). The `## reduce_to` chassis umbrella
6002/// is `registrable: false` (§3.10) and never registers (without it the chassis
6003/// would double-register `ReduceSumTo`/`[F32]` → `DuplicateKernelRef` at init).
6004/// The family declares NO fused ops, so `register_into`'s required fused
6005/// argument is a local throwaway that provably stays empty.
6006fn register_cpu_reduce_to_from_contract(table: &mut KernelBindingTable) {
6007    let provider =
6008        crate::fkc::import_bundle_str(CPU_REDUCE_TO_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6009            "authored CPU reduce-to contract must import \
6010                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6011        );
6012    debug_assert!(
6013        provider.fused.is_empty(),
6014        "reduce-to contract declares no fused ops",
6015    );
6016    let mut fused = crate::fused::FusedKernelRegistry::new();
6017    provider
6018        .register_into(table, &mut fused)
6019        .expect("CPU reduce-to contract must register into the binding table");
6020}
6021
6022/// The authored CPU norm (forward) kernel contract, embedded into the binary
6023/// (the PRODUCTION `include_str!`). `register_cpu_norm_from_contract` parses +
6024/// lowers it and binds the family FROM THE CONTRACT.
6025const CPU_NORM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/norm.fkc.md");
6026
6027/// Register the CPU last-dim NORM (forward) family (Softmax / LogSoftmax /
6028/// RmsNorm / LayerNorm × 4 dtypes = 16 bindings, key `[T, T]`) by IMPORTING its
6029/// FKC kernel contract, the seventh production FKC consumer (mirroring the
6030/// binary / affine-clamp-powi / unary / compare-where / reduce / reduce-to
6031/// importers). FKC is unconditional core infrastructure, so this is the ONE
6032/// registration path for the family: the hand-written `table.register(...)`
6033/// calls it used to carry are DELETED.
6034///
6035/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_f32`,
6036/// `## rms_norm_last_dim_f32`, …) is a SPECIFIC single-dtype contract with a
6037/// concrete `entry_point` (`…::softmax_last_dim_f32`), so none of them fan — the
6038/// importer resolves each declared symbol AS-IS through the production
6039/// [`crate::fkc::CpuLinkRegistry`] (now chaining [`crate::fkc::CPU_NORM_ENTRY_POINTS`])
6040/// to the exact wrapper fn-pointer the CPU backend exposes. The binding key is
6041/// `[T, T]` (a SINGLE input + `passthrough(input)` output — the RMS/LayerNorm
6042/// kernels carry NO affine gamma/beta operand; they are the bare normalization,
6043/// and `outer_count` / `last_dim` / `eps` ride in
6044/// `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the dtype-list),
6045/// identical to the deleted `&unary(t)` regs.
6046///
6047/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6048/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6049/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6050/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6051/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6052/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6053/// section, so there is nothing marked `registrable: false` and no double-register
6054/// risk. The forward NORM ops are ALSO registered in the `FusedKernelRegistry`
6055/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,RMS_NORM,LAYER_NORM}_LAST_DIM`)
6056/// — that is a SEPARATE registry seam and stays untouched; this migration only
6057/// moves the `KernelBindingTable` primitive path. The BACKWARD forms live in a
6058/// separate norm-backward contract and their hand-written regs stay authoritative.
6059/// The family declares NO fused ops, so `register_into`'s required fused argument
6060/// is a local throwaway that provably stays empty.
6061fn register_cpu_norm_from_contract(table: &mut KernelBindingTable) {
6062    let provider = crate::fkc::import_bundle_str(CPU_NORM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6063        .expect(
6064            "authored CPU norm contract must import \
6065                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6066        );
6067    debug_assert!(
6068        provider.fused.is_empty(),
6069        "norm forward contract declares no fused ops",
6070    );
6071    let mut fused = crate::fused::FusedKernelRegistry::new();
6072    provider
6073        .register_into(table, &mut fused)
6074        .expect("CPU norm contract must register into the binding table");
6075}
6076
6077/// The authored CPU norm-BACKWARD kernel contract, embedded into the binary
6078/// (the PRODUCTION `include_str!`). `register_cpu_norm_backward_from_contract`
6079/// parses + lowers it and binds the family FROM THE CONTRACT.
6080const CPU_NORM_BACKWARD_CONTRACT: &str =
6081    include_str!("../kernel-contracts/cpu/norm-backward.fkc.md");
6082
6083/// Register the CPU last-dim NORM-BACKWARD family (Softmax / LogSoftmax /
6084/// RmsNorm / LayerNorm backward × 4 dtypes = 16 bindings, key `[T, T, T]`) by
6085/// IMPORTING its FKC kernel contract, the eighth production FKC consumer (the
6086/// BACKWARD sibling of `register_cpu_norm_from_contract`). FKC is unconditional
6087/// core infrastructure, so this is the ONE registration path for the family: the
6088/// hand-written `table.register(...)` calls it used to carry are DELETED.
6089///
6090/// Each of the 16 per-(op, dtype) sections (`## softmax_last_dim_backward_f32`,
6091/// `## rms_norm_last_dim_backward_f32`, …) is a SPECIFIC single-dtype contract
6092/// with a concrete `entry_point` (`…::softmax_last_dim_backward_f32`), so none of
6093/// them fan — the importer resolves each declared symbol AS-IS through the
6094/// production [`crate::fkc::CpuLinkRegistry`] (now chaining
6095/// [`crate::fkc::CPU_NORM_BACKWARD_ENTRY_POINTS`]) to the exact wrapper
6096/// fn-pointer the CPU backend exposes. The binding key is `[T, T, T]` — the BARE
6097/// backward takes TWO inputs (softmax/log-softmax: forward output `y` + upstream
6098/// gradient `g`; layer/rms-norm: forward input `x` + `g`, stats recomputed from
6099/// `x` + `eps`) and writes ONE `passthrough(y|x)` output; outer_count / last_dim /
6100/// eps ride in `OpParams::{SoftmaxLastDim,LogSoftmaxLastDim,NormLastDim}`, NOT the
6101/// dtype-list — identical to the deleted `&binary(t)` regs.
6102///
6103/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6104/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6105/// `"portable-cpu"` tag and its precision the contract's audited bit-stable
6106/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`, which
6107/// upgrades the imported entries' `unknown_cost` sentinel to the same OpKind cost
6108/// fn every CPU primitive gets. This contract has NO `##` chassis umbrella
6109/// section, so there is nothing marked `registrable: false` and no double-register
6110/// risk. The backward NORM ops are ALSO registered in the `FusedKernelRegistry`
6111/// (`register_default_fused_kernels`, `FusedOps::{SOFTMAX,LAYER_NORM,RMS_NORM}_
6112/// LAST_DIM_BACKWARD`) — that is a SEPARATE registry seam and stays untouched;
6113/// this migration only moves the `KernelBindingTable` primitive path. The family
6114/// declares NO fused ops, so `register_into`'s required fused argument is a local
6115/// throwaway that provably stays empty.
6116fn register_cpu_norm_backward_from_contract(table: &mut KernelBindingTable) {
6117    let provider =
6118        crate::fkc::import_bundle_str(CPU_NORM_BACKWARD_CONTRACT, &crate::fkc::CpuLinkRegistry)
6119            .expect(
6120                "authored CPU norm-backward contract must import \
6121                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6122            );
6123    debug_assert!(
6124        provider.fused.is_empty(),
6125        "norm backward contract declares no fused ops",
6126    );
6127    let mut fused = crate::fused::FusedKernelRegistry::new();
6128    provider
6129        .register_into(table, &mut fused)
6130        .expect("CPU norm-backward contract must register into the binding table");
6131}
6132
6133/// The authored CPU RoPE kernel contract, embedded into the binary (the
6134/// PRODUCTION `include_str!`). `register_cpu_rope_from_contract` parses +
6135/// lowers it and binds the family FROM THE CONTRACT.
6136const CPU_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/cpu/rope.fkc.md");
6137
6138/// Register the CPU RoPE family (rotary position embedding; 1 op × 4 dtypes =
6139/// 4 bindings, key `[T, T, T, T]`) by IMPORTING its FKC kernel contract, the
6140/// ninth production FKC consumer. FKC is unconditional core infrastructure, so
6141/// this is the ONE registration path for the family: the hand-written
6142/// `table.register(Rope, ...)` calls it used to carry are DELETED.
6143///
6144/// Each of the 4 per-dtype sections (`## rope_f32`, `## rope_f64`,
6145/// `## rope_bf16`, `## rope_f16`) is a SPECIFIC single-dtype contract with a
6146/// concrete `entry_point` (`…::rope_f32`), so none of them fan — the importer
6147/// resolves each declared symbol AS-IS through the production
6148/// [`crate::fkc::CpuLinkRegistry`] (now chaining
6149/// [`crate::fkc::CPU_ROPE_ENTRY_POINTS`]) to the exact wrapper fn-pointer the
6150/// CPU backend exposes. The binding key is `[T, T, T, T]` — RoPE takes THREE
6151/// inputs (`x` + the precomputed `cos`/`sin` tables of shape `[seq, head_dim]`,
6152/// all one dtype; the tables broadcast over the `outer_count` axis by the
6153/// kernel re-indexing them per outer, NOT a stride-0 view) and writes ONE
6154/// `passthrough(x)` output; outer_count / seq / head_dim ride in
6155/// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
6156/// `rope_dts(t)` regs.
6157///
6158/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6159/// caps (contiguous-only, even `head_dim`); the binding's `kernel_source`
6160/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6161/// bit-stable claim. Cost is preserved because this runs BEFORE
6162/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6163/// sentinel to the same OpKind cost fn every CPU primitive gets. This contract
6164/// has NO `##` chassis umbrella section, so there is nothing marked
6165/// `registrable: false` and no double-register risk. RoPE is ALSO registered in
6166/// the `FusedKernelRegistry` (`register_default_fused_kernels`,
6167/// `FusedOps::ROPE`) — that is a SEPARATE registry seam and stays untouched;
6168/// this migration only moves the `KernelBindingTable` primitive path. The
6169/// family declares NO fused ops, so `register_into`'s required fused argument is
6170/// a local throwaway that provably stays empty.
6171fn register_cpu_rope_from_contract(table: &mut KernelBindingTable) {
6172    let provider = crate::fkc::import_bundle_str(CPU_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
6173        .expect(
6174            "authored CPU rope contract must import \
6175                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6176        );
6177    debug_assert!(
6178        provider.fused.is_empty(),
6179        "rope contract declares no fused ops",
6180    );
6181    let mut fused = crate::fused::FusedKernelRegistry::new();
6182    provider
6183        .register_into(table, &mut fused)
6184        .expect("CPU rope contract must register into the binding table");
6185}
6186
6187/// The authored CPU SSM / Mamba kernel contract, embedded into the binary (the
6188/// PRODUCTION `include_str!`). `register_cpu_ssm_from_contract` parses + lowers
6189/// it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6190const CPU_SSM_CONTRACT: &str = include_str!("../kernel-contracts/cpu/ssm.fkc.md");
6191
6192/// Register the ENTIRE CPU SSM / Mamba family —
6193/// FusedSoftmaxCrossEntropy (key `[T, I64, F32]`) + CausalConv1d (key
6194/// `[T, T, T, T]`) + SelectiveScan + SsdChunkScan (key `[T; 6]`), 4 ops ×
6195/// 4 dtypes = 16 bindings — by IMPORTING its FKC kernel contract, the tenth
6196/// production FKC consumer. FKC is unconditional core infrastructure, so this is
6197/// the ONE registration path for the whole family: every hand-written
6198/// `table.register(...)` call is DELETED.
6199///
6200/// Each per-(op, dtype) section (`## fused_softmax_cross_entropy_f32`,
6201/// `## selective_scan_f32`, …) is a SPECIFIC single-dtype contract with a
6202/// concrete `entry_point` (`…::selective_scan_f32`), so none of them fan — the
6203/// importer resolves each declared symbol AS-IS through the production
6204/// [`crate::fkc::CpuLinkRegistry`] (chaining [`crate::fkc::CPU_SSM_ENTRY_POINTS`])
6205/// to the exact wrapper fn-pointer the CPU backend exposes. FSCE takes TWO inputs
6206/// (logits T + I64 targets) → ONE `fixed(F32)` output; CausalConv1d takes THREE
6207/// inputs (x, weight, bias) → ONE `passthrough(x)` output; every geometry/knob
6208/// rides in `OpParams`, NOT the dtype-list — identical keys to the deleted
6209/// hand-written regs.
6210///
6211/// **The two SCAN ops (SelectiveScan / SsdChunkScan) return a `return.bundle`**
6212/// multi-output (Option C: one packed buffer `[y ; last_state]`). The importer's
6213/// key-builder (`fkc/lower.rs` `assemble_dtype_variants`) appends the bundle's
6214/// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key tail,
6215/// so a 5-input scan section keys `[T; 6]` (5 inputs + the one bundled output
6216/// slot) — byte-for-byte the deleted hand-written
6217/// `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)` regs. All four
6218/// ops are now `registrable: true` (the default), so `lower_file` imports the
6219/// whole family.
6220///
6221/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6222/// caps (contiguous-only); the binding's
6223/// `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6224/// precision the contract's bit-stable claim. Cost is preserved because this
6225/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6226/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6227/// The family declares NO fused ops (the "fused" in FusedSoftmaxCrossEntropy is
6228/// an intra-op softmax+NLL fusion, not a graph `FusedOpId`), so `register_into`'s
6229/// required fused argument is a local throwaway that provably stays empty.
6230fn register_cpu_ssm_from_contract(table: &mut KernelBindingTable) {
6231    let provider = crate::fkc::import_bundle_str(CPU_SSM_CONTRACT, &crate::fkc::CpuLinkRegistry)
6232        .expect(
6233            "authored CPU ssm contract must import \
6234                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6235        );
6236    debug_assert!(
6237        provider.fused.is_empty(),
6238        "ssm contract declares no fused ops",
6239    );
6240    let mut fused = crate::fused::FusedKernelRegistry::new();
6241    provider
6242        .register_into(table, &mut fused)
6243        .expect("CPU ssm contract must register into the binding table");
6244}
6245
6246/// The authored CPU 2D-convolution kernel contract, embedded into the binary
6247/// (the PRODUCTION `include_str!`). `register_cpu_conv_from_contract` parses +
6248/// lowers it and binds the MIGRATED (with-bias) subset of the family FROM THE
6249/// CONTRACT.
6250const CPU_CONV_CONTRACT: &str = include_str!("../kernel-contracts/cpu/conv.fkc.md");
6251
6252/// Register the CPU 2D-convolution family FULLY — Conv2D + ConvTranspose2D at
6253/// BOTH the no-bias key `[T, T, T]` (x, weight + out) and the with-bias key
6254/// `[T, T, T, T]` (x, weight, bias + passthrough(x) output), 2 ops × 4 dtypes ×
6255/// 2 operand-counts = 16 bindings — by IMPORTING its FKC kernel contract, the
6256/// eleventh production FKC consumer. FKC is unconditional core infrastructure,
6257/// so this is the ONE registration path for the whole family: every hand-written
6258/// `table.register(...)` conv call is DELETED.
6259///
6260/// Each per-(op, dtype) section (`## conv2d_f32`, `## conv_transpose2d_f32`, …)
6261/// is a SPECIFIC single-dtype contract with a concrete `entry_point`
6262/// (`…::conv2d_f32`), so none of them dtype-fan — the importer resolves each
6263/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6264/// (now chaining [`crate::fkc::CPU_CONV_ENTRY_POINTS`]) to the exact wrapper
6265/// fn-pointer the CPU backend exposes. Conv2D's weight is `[Cout, Cin/groups,
6266/// Kh, Kw]`; ConvTranspose2D's is the transposed `[Cin, Cout/groups, Kh, Kw]`
6267/// and it carries an extra `output_padding` op-param — but both are the same
6268/// (x, weight, optional bias) → one-output (passthrough(x)) accept shape, and
6269/// every geometry knob rides in `OpParams::{Conv2D, ConvTranspose2D}`, NOT the
6270/// dtype-list.
6271///
6272/// **The NO-BIAS key is now CONTRACT-SOURCED.** The conv contract declares
6273/// `bias` as `optional: true`, and the FKC importer's key-builder
6274/// (`fkc/lower.rs` `assemble_dtype_variants`) now supports optional operands: an
6275/// optional LAST input fans each section into TWO keys — one OMITTING `bias`
6276/// (`[T, T, T]`) and one INCLUDING it (`[T, T, T, T]`) — BOTH resolving the SAME
6277/// `entry_point`/wrapper (the same CPU wrapper handles 2 or 3 inputs). The
6278/// former no-bias deferral (hand-written `table.register(Conv2D /
6279/// ConvTranspose2D, &[dt; 3], ...)` regs) is closed and those regs deleted.
6280///
6281/// Behavior-preserving vs. the deleted hand-written path (for both operand-count
6282/// keys): identical kernels + caps (contiguous-only NCHW); the
6283/// binding's `kernel_source` becomes the contract's `"portable-cpu"` tag and its
6284/// precision the contract's bit-stable claim. Cost is preserved because this
6285/// runs BEFORE `fill_unset_cpu_cost`, which upgrades the imported entries'
6286/// `unknown_cost` sentinel to the same OpKind cost fn every CPU primitive gets.
6287/// The family declares NO fused ops (the SEPARATE FusedKernelRegistry
6288/// `FusedOps::{CONV2D, CONV_TRANSPOSE2D}` seam is hand-written, in
6289/// `register_default_fused_kernels`, and stays untouched), so `register_into`'s
6290/// required fused argument is a local throwaway that provably stays empty.
6291fn register_cpu_conv_from_contract(table: &mut KernelBindingTable) {
6292    let provider = crate::fkc::import_bundle_str(CPU_CONV_CONTRACT, &crate::fkc::CpuLinkRegistry)
6293        .expect(
6294            "authored CPU conv contract must import \
6295                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6296        );
6297    debug_assert!(
6298        provider.fused.is_empty(),
6299        "conv contract declares no fused ops",
6300    );
6301    let mut fused = crate::fused::FusedKernelRegistry::new();
6302    provider
6303        .register_into(table, &mut fused)
6304        .expect("CPU conv contract must register into the binding table");
6305}
6306
6307/// The authored CPU **padding** kernel contract, embedded into the binary (the
6308/// PRODUCTION `include_str!`). `register_cpu_padding_from_contract` parses +
6309/// lowers it and binds the FULL family (mode-unified forward `Pad` +
6310/// `PadBackward`) FROM THE CONTRACT.
6311const CPU_PADDING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/padding.fkc.md");
6312
6313/// Register the FULL CPU padding family — mode-unified forward `Pad` × 6 dtypes
6314/// = 6 + `PadBackward` × 4 dtypes = 4 bindings (all key `[T, T]`) — by IMPORTING
6315/// its FKC kernel contract, the twelfth production FKC consumer.
6316///
6317/// - **Forward `Pad`** — the ONE mode-unified `## pad` section declares a BASE
6318///   `entry_point` (`…::pad_cpu`, a synthetic umbrella — the three real mode
6319///   byte-kernels are `pad_{const,reflect,replicate}_cpu`) + the 6 production
6320///   dtypes (`U8/U32/BF16/F16/F32/F64`), so the importer's §3.4 fan-out resolves
6321///   `pad_cpu_<dtype>` — every dtype variant mapping to the ONE mode-dispatching
6322///   `pad_cpu_wrapper` (which selects Constant/Reflect/Replicate at runtime via
6323///   `mode_tag`, incl. the reflect `before/after <= n-1` validation) through the
6324///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6325///   [`crate::fkc::CPU_PADDING_ENTRY_POINTS`]). Key `[T, T]` (input +
6326///   `passthrough(input)` output; the in_shape/out_shape/padding/mode_tag/
6327///   fill_bytes ride in `OpParams::Pad`, NOT the dtype-list) — byte-for-byte the
6328///   deleted hand-written `table.register(Pad, &unary(t), …)` regs. The three
6329///   per-mode sections (`pad_const_cpu` / `pad_reflect_cpu` / `pad_replicate_cpu`)
6330///   and the `pad_walk_cpu` helper are `registrable: false` (§3.10 describe-only
6331///   mode documentation) and never resolve.
6332/// - **`PadBackward`** — each per-dtype section (`## pad_backward_f32`, …) carries
6333///   a SPECIFIC single-dtype `entry_point` (`…::pad_backward_f32`) resolved AS-IS
6334///   (no fan), key `[T, T]` (grad_out + `passthrough(grad_out)` grad_in; the
6335///   in_shape/out_shape/padding/mode_tag ride in `OpParams::PadBackward`) —
6336///   byte-for-byte the deleted `table.register(PadBackward, &unary(t), …)` regs.
6337///   `PadBackward` is per-dtype (unlike the dtype-agnostic forward `Pad`) because
6338///   gradient accumulation is typed (bf16/f16/f32 widen the scratch accumulator
6339///   to f64).
6340///
6341/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6342/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6343/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6344/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6345/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6346/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6347/// required fused argument is a local throwaway that provably stays empty.
6348fn register_cpu_padding_from_contract(table: &mut KernelBindingTable) {
6349    let provider =
6350        crate::fkc::import_bundle_str(CPU_PADDING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6351            "authored CPU padding contract must import \
6352                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6353        );
6354    debug_assert!(
6355        provider.fused.is_empty(),
6356        "padding contract declares no fused ops",
6357    );
6358    let mut fused = crate::fused::FusedKernelRegistry::new();
6359    provider
6360        .register_into(table, &mut fused)
6361        .expect("CPU padding contract must register into the binding table");
6362}
6363
6364/// The authored CPU **shape-ops** kernel contract, embedded into the binary (the
6365/// PRODUCTION `include_str!`). `register_cpu_shape_ops_from_contract` parses +
6366/// lowers it and binds the MIGRATED subset of the family FROM THE CONTRACT.
6367const CPU_SHAPE_OPS_CONTRACT: &str = include_str!("../kernel-contracts/cpu/shape-ops.fkc.md");
6368
6369/// Register the MIGRATED CPU shape-ops subset — Flip + Roll + Concat +
6370/// MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels,
6371/// fanned per production dtype) and the four per-dtype CumSum kernels — by
6372/// IMPORTING its FKC kernel contract, the thirteenth production FKC consumer.
6373///
6374/// - **Flip** / **Roll** (key `[T, T]`, 6 dtypes each) and **Concat** (key
6375///   `[T, T]`, 9 dtypes) and **MaskedFill** (key `[T, U8, T]`, 6 dtypes) and
6376///   **WriteSlice** / **WriteSliceRotating** (key `[T, T]`, 6 dtypes each) are
6377///   ONE dtype-agnostic wrapper each. Their sections declare a BASE `entry_point`
6378///   (`…::flip_cpu`, …) + an enumerated `dtypes` list trimmed to the wired set,
6379///   so the §3.4 fan-out resolves `<base>_<dtype>` (`flip_cpu_f32`, …) — a
6380///   fabricated per-dtype symbol that every variant maps to the SAME wrapper via
6381///   [`crate::fkc::CPU_SHAPE_OPS_ENTRY_POINTS`]. MaskedFill's `input` is the sole
6382///   varying operand; `mask` stays the fixed U8 slot and `out: passthrough(input)`,
6383///   so the fan emits `[T, U8, T]` — byte-for-byte the deleted
6384///   `table.register(MaskedFill, &masked_dtypes(t), …)` regs. **WriteSlice /
6385///   WriteSliceRotating** model `dest` as the in-place OUTPUT slot (not a key
6386///   input) and — for the rotating op — the U32 `position` as a NON-KEY runtime
6387///   operand (both handled by the executor's dedicated `Op::WriteSlice{,Rotating}`
6388///   arms), so a source-only + `out: passthrough(source)` section keys
6389///   `[T_source, T_out]` = `[T, T]` — byte-for-byte the deleted
6390///   `table.register(WriteSlice{,Rotating}, &unary(t), …)` regs and matching
6391///   `build_lookup_dtypes`' canonicalization exactly.
6392/// - **CumSum** (key `[T, T]`, 4 dtypes) is per-dtype typed accumulation, so each
6393///   `cumsum_<dt>` section carries a SPECIFIC single-dtype `entry_point` resolved
6394///   AS-IS (no fan) to its OWN typed wrapper.
6395///
6396/// **DEFERRED (describe-only, NOT imported).** `contiguize` and `triangular` are
6397/// `registrable: false` chassis/describe-only sections (no `OpKind::Contiguize` —
6398/// it is an executor materialize pass; `triangular` is the umbrella backing the
6399/// two hand-written `Triu`/`Tril` OpKinds with distinct wrappers, not a keyable
6400/// section). Those hand-written `Triu`/`Tril` regs stay authoritative.
6401///
6402/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6403/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6404/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6405/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6406/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6407/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6408/// required fused argument is a local throwaway that provably stays empty.
6409fn register_cpu_shape_ops_from_contract(table: &mut KernelBindingTable) {
6410    let provider =
6411        crate::fkc::import_bundle_str(CPU_SHAPE_OPS_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6412            "authored CPU shape-ops contract must import \
6413                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6414        );
6415    debug_assert!(
6416        provider.fused.is_empty(),
6417        "shape-ops contract declares no fused ops",
6418    );
6419    let mut fused = crate::fused::FusedKernelRegistry::new();
6420    provider
6421        .register_into(table, &mut fused)
6422        .expect("CPU shape-ops contract must register into the binding table");
6423}
6424
6425/// The authored CPU **matmul** kernel contract, embedded into the binary (the
6426/// PRODUCTION `include_str!`). `register_cpu_matmul_from_contract` parses +
6427/// lowers it and binds the FULL portable family FROM THE CONTRACT.
6428const CPU_MATMUL_CONTRACT: &str = include_str!("../kernel-contracts/cpu/matmul.fkc.md");
6429
6430/// Register the CPU **matmul** family FULLY — bare batched `MatMul` (6 dtypes,
6431/// key `[T, T, T]`) + fused `FusedLinear` (matmul + bias-add, 4 dtypes, key
6432/// `[T, T, T, T]`) = 10 bindings — by IMPORTING its FKC kernel contract, the
6433/// fourteenth production FKC consumer. FKC is unconditional core infrastructure,
6434/// so this is the ONE registration path for the PORTABLE kernels: every
6435/// hand-written `table.register(MatMul / FusedLinear, …)` portable-CPU call is
6436/// DELETED.
6437///
6438/// Each per-(op, dtype) section (`## matmul_f32`, `## fused_linear_f32`, …) is a
6439/// SPECIFIC single-dtype contract with a concrete `entry_point`
6440/// (`…::matmul_f32`), so none of them dtype-fan — the importer resolves each
6441/// declared symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`]
6442/// (now chaining [`crate::fkc::CPU_MATMUL_ENTRY_POINTS`]) to the exact wrapper
6443/// fn-pointer the CPU backend exposes. MatMul is 2-input (lhs, rhs) →
6444/// `passthrough(lhs)` output; FusedLinear is 3-input (a, b, bias) →
6445/// `passthrough(a)` output with `bias` a REQUIRED 1-D `[N]` operand (NOT
6446/// `optional`, so a single 4-slot key per dtype — no optional {absent, present}
6447/// fan). Both reuse `OpParams::Matmul` for shape, so every batch-geometry knob
6448/// (lhs_batch_dims/rhs_batch_dims/m/n/k) rides in `OpParams`, NOT the dtype-list.
6449/// The float variants (F32/F64/BF16/F16) accumulate in f32/native; the integer
6450/// MatMul variants (I8/U8) accumulate in i32 and SATURATE on store.
6451///
6452/// **Alternatives at the same key.** The binding table supports MULTIPLE ranked
6453/// kernels per `(op, dtypes, backend)` key. This importer registers ONLY the
6454/// portable (`kernel_source: "portable-cpu"`) kernels the contract covers; the
6455/// MKL / AOCL BLAS siblings live in SEPARATE external backend crates
6456/// (`fuel-mkl-cpu-backend` / `fuel-aocl-cpu-backend`), register through the
6457/// exported dispatch helpers with their own `"mkl"`/`"aocl"` `kernel_source`
6458/// tags as ranked alternatives at these SAME keys, and are out of scope here
6459/// (untouched — never registered in this crate's default build).
6460///
6461/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6462/// caps (contiguous-only, GQA-divisible batch); the binding's `kernel_source`
6463/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6464/// bit-stable claim. Cost is preserved because this runs BEFORE
6465/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6466/// sentinel to the same OpKind cost fn every CPU primitive gets. The family
6467/// declares NO fused ops (the SEPARATE `FusedKernelRegistry`
6468/// `FusedOps::FUSED_LINEAR` seam is hand-written, in
6469/// `register_default_fused_kernels`, and stays untouched — "fused" in
6470/// `FusedLinear` names an intra-op matmul+bias fusion, NOT a graph `FusedOpId`),
6471/// so `register_into`'s required fused argument is a local throwaway that
6472/// provably stays empty. The quant `QMatMul` / `Nf4Matmul` OpKinds have their
6473/// own contracts and stay hand-written.
6474fn register_cpu_matmul_from_contract(table: &mut KernelBindingTable) {
6475    let provider = crate::fkc::import_bundle_str(CPU_MATMUL_CONTRACT, &crate::fkc::CpuLinkRegistry)
6476        .expect(
6477            "authored CPU matmul contract must import \
6478                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6479        );
6480    debug_assert!(
6481        provider.fused.is_empty(),
6482        "matmul contract declares no fused ops",
6483    );
6484    let mut fused = crate::fused::FusedKernelRegistry::new();
6485    provider
6486        .register_into(table, &mut fused)
6487        .expect("CPU matmul contract must register into the binding table");
6488}
6489
6490/// The authored CPU **attention** kernel contract, embedded into the binary (the
6491/// PRODUCTION `include_str!`). `register_cpu_attention_from_contract` parses +
6492/// lowers it and binds the MIGRATED (`KernelBindingTable`) subset FROM THE
6493/// CONTRACT.
6494const CPU_ATTENTION_CONTRACT: &str = include_str!("../kernel-contracts/cpu/attention.fkc.md");
6495
6496/// Register the CPU **attention** family's `KernelBindingTable` path FROM its FKC
6497/// kernel contract, the fifteenth production FKC consumer: forward `FlashAttn`
6498/// (4 dtypes) + `FlashAttnBackward{Q,K,V}` (3 selectors × 4 dtypes), each
6499/// `alibi_slopes`-optional section fanning into BOTH the no-alibi and with-alibi
6500/// keys = 4 × 4 × 2 = 32 bindings. FKC is unconditional core infrastructure, so
6501/// this is the ONE registration path for the migrated subset: the hand-written
6502/// `table.register(FlashAttn / FlashAttnBackward{Q,K,V}, …)` regs (both alibi
6503/// keys) are DELETED.
6504///
6505/// Each per-(op, dtype) section (`## flash_attn_f32`,
6506/// `## flash_attn_backward_q_f32`, …) declares a SPECIFIC single-dtype
6507/// `entry_point`, so none of them dtype-fan — the importer resolves each declared
6508/// symbol AS-IS through the production [`crate::fkc::CpuLinkRegistry`] (now
6509/// chaining [`crate::fkc::CPU_ATTENTION_ENTRY_POINTS`]) to the exact wrapper
6510/// fn-pointer. Because the contract marks `alibi_slopes` as `optional: true` (the
6511/// LAST input), the importer's key-builder (`fkc/lower.rs`
6512/// `assemble_dtype_variants`) fans each section into BOTH the no-alibi key
6513/// (`[q,k,v,out]` forward / `[q,k,v,do,out]` backward) and the with-alibi key
6514/// (`+alibi`) — both resolving the SAME `entry_point`/wrapper (the CPU wrapper
6515/// handles the presence/absence of the alibi operand). Forward FlashAttn AND the
6516/// three backward selectors share the single `OpParams::FlashAttn` carrier (there
6517/// is NO dedicated backward `OpParams` variant), so every softmax/mask geometry
6518/// knob rides in `OpParams`, NOT the dtype-list.
6519///
6520/// **PagedAttn is REGISTRABLE (`registrable: true`) and contract-sourced too.**
6521/// Its paged KV pool carries an `fdx.gather: paged_blocks` operand (§3.9.1), but
6522/// that block is import METADATA describing what an FDX view of the pool will
6523/// someday carry (FDX §6.9: "Description only: no cost, no decision"), NOT a
6524/// registration dependency: the as-built ABI passes `block_table` /
6525/// `context_lens` as ordinary U32 graph inputs + the geometry in
6526/// `OpParams::PagedAttn`, and the kernel reads them directly. So the importer
6527/// validates the gather block for COHERENCE (kind / requires_ext /
6528/// symbolic_extent / real block_table+context_lens roles) and registers the four
6529/// paged sections onto the `KernelBindingTable` at `(OpKind::PagedAttn,
6530/// [T,T,T,U32,U32,T](+[T]), Cpu)` — the optional-operand fan builds both alibi
6531/// keys, byte-for-byte the deleted hand-written `paged_attn_{no,with}_alibi`
6532/// regs. What remains [consumer-ahead] is only the FDX VIEW/materialize seam
6533/// (`view_with_gather` + `Capability::DlpackExtGather`), which has no consumer
6534/// yet. (The SEPARATE `FusedKernelRegistry` `PAGED_ATTN` seam stays hand-written,
6535/// exactly like `FLASH_ATTN`.)
6536///
6537/// Behavior-preserving vs. the deleted hand-written path (both alibi keys):
6538/// identical kernels + caps (contiguous-only); the binding's `kernel_source`
6539/// becomes the contract's `"portable-cpu"` tag and its precision the contract's
6540/// bit-stable claim. Cost is preserved because this runs BEFORE
6541/// `fill_unset_cpu_cost`, which upgrades the imported entries' `unknown_cost`
6542/// sentinel to the same OpKind cost fn every CPU primitive gets (the CPU cost
6543/// dispatcher has `FlashAttn`/`PagedAttn` arms; the backward selectors keep
6544/// `unknown_cost`, exactly as under the deleted hand-written regs — they are not
6545/// on the cost-coverage lint's enumerated set). The family declares NO fused ops
6546/// (all sections are `op_kind:`, incl. the now-registrable PagedAttn), so
6547/// `register_into`'s required fused argument is a local throwaway that provably
6548/// stays empty. The
6549/// SEPARATE `FusedKernelRegistry` FLASH_ATTN* / PAGED_ATTN seam
6550/// (`register_default_fused_kernels`) is hand-written and stays untouched.
6551fn register_cpu_attention_from_contract(table: &mut KernelBindingTable) {
6552    let provider =
6553        crate::fkc::import_bundle_str(CPU_ATTENTION_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6554            "authored CPU attention contract must import \
6555                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6556        );
6557    debug_assert!(
6558        provider.fused.is_empty(),
6559        "attention contract declares no fused ops (all op_kind, incl. PagedAttn)",
6560    );
6561    let mut fused = crate::fused::FusedKernelRegistry::new();
6562    provider
6563        .register_into(table, &mut fused)
6564        .expect("CPU attention contract must register into the binding table");
6565}
6566
6567/// The authored CPU **in-place scalar-param** kernel contract, embedded into the
6568/// binary (the PRODUCTION `include_str!`). `register_cpu_inplace_from_contract`
6569/// parses + lowers it and binds the WHOLE family FROM THE CONTRACT.
6570const CPU_INPLACE_CONTRACT: &str =
6571    include_str!("../kernel-contracts/cpu/inplace-unary-affine.fkc.md");
6572
6573/// Register the CPU **in-place scalar-param** family's `KernelBindingTable` path
6574/// FROM its FKC kernel contract, the sixteenth production FKC consumer: 21
6575/// in-place unary ops (`<Op>Inplace`, each per-op section fanning `[F32,F64,
6576/// BF16,F16]` = 84 bindings) + `InplaceAffine` / `ClampInplace` / `PowIInplace`
6577/// (per-dtype single sections, 4 each = 12) = 96 bindings. FKC is unconditional
6578/// core infrastructure, so this is the ONE registration path for the whole
6579/// family: the hand-written `table.register(<Op>Inplace / InplaceAffine /
6580/// ClampInplace / PowIInplace, &unary(dt), …)` regs are DELETED.
6581///
6582/// Each per-op unary section (`## relu_inplace`, …) declares a BASE `entry_point`
6583/// (`…::relu_inplace`) + enumerates `dtypes: [F32,F64,BF16,F16]`, so the
6584/// importer's §3.4 multi-dtype fan-out resolves `<base>_<dtype>`
6585/// (`relu_inplace_f32`) through the production [`crate::fkc::CpuLinkRegistry`]
6586/// (now chaining [`crate::fkc::CPU_INPLACE_ENTRY_POINTS`]) to the exact wrapper
6587/// fn-pointer. The affine / clamp / powi sections are per-dtype SINGLE sections,
6588/// so they do NOT fan — their specific `<op>_inplace_<dt>` symbol resolves AS-IS
6589/// (the affine rows carry the three-way naming skew: symbol `affine_inplace_<dt>`
6590/// → wrapper `inplace_affine_<dt>_cpu_wrapper`, words swapped). Every binding
6591/// keys `[T, T]` (the single `out` operand + its `passthrough(out)` mirror; the
6592/// executor's `WorkItemKind::InplaceKernel` arm passes the target as
6593/// `outputs[0]`), byte-for-byte the deleted `&unary(dt)` regs. Scalar params
6594/// (affine `mul`/`add`, clamp `min`/`max`, powi `exp`) ride in
6595/// `OpParams::{Affine, Clamp, PowI}`, NOT the dtype-list.
6596///
6597/// The `## unary_inplace` chassis umbrella is `registrable: false` (§3.10
6598/// describe-only) — it binds no OpKind (each named op pins its own distinct
6599/// `<Op>Inplace`), so it never lowers/resolves and is excluded from
6600/// registration.
6601///
6602/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6603/// caps (contiguous-only, empty caps); the binding's `kernel_source` becomes the
6604/// contract's `"portable-cpu"` tag and its precision the contract's bit-stable
6605/// claim. Cost is preserved because this runs BEFORE `fill_unset_cpu_cost`: the
6606/// in-place OpKinds are NOT on the CPU cost-coverage lint's enumerated set and
6607/// have no arm in `default_cost_for_op_kind`, so they keep the `unknown_cost`
6608/// sentinel exactly as under the deleted hand-written regs. The family declares
6609/// NO fused ops (all sections are `op_kind:` or the describe-only umbrella), so
6610/// `register_into`'s required fused argument is a local throwaway that provably
6611/// stays empty.
6612fn register_cpu_inplace_from_contract(table: &mut KernelBindingTable) {
6613    let provider =
6614        crate::fkc::import_bundle_str(CPU_INPLACE_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6615            "authored CPU in-place contract must import \
6616                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6617        );
6618    debug_assert!(
6619        provider.fused.is_empty(),
6620        "in-place contract declares no fused ops (all op_kind or describe-only umbrella)",
6621    );
6622    let mut fused = crate::fused::FusedKernelRegistry::new();
6623    provider
6624        .register_into(table, &mut fused)
6625        .expect("CPU in-place contract must register into the binding table");
6626}
6627
6628/// The authored CPU **cast** kernel contract, embedded into the binary (the
6629/// PRODUCTION `include_str!`). `register_cpu_cast_from_contract` parses + lowers
6630/// it and binds the FULL directed-pair matrix FROM THE CONTRACT.
6631const CPU_CAST_CONTRACT: &str = include_str!("../kernel-contracts/cpu/cast.fkc.md");
6632
6633/// Register the CPU **cast** family FULLY — the COMPLETE directed-pair matrix,
6634/// every ordered pair of the 11 real numeric dtypes
6635/// {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with identity excluded =
6636/// 11 × 10 = 110 bindings (all key `[SRC, DST]`) — by IMPORTING its FKC kernel
6637/// contract.
6638///
6639/// Each per-pair section (`## cast_f64_to_f32`, …) declares a SPECIFIC
6640/// single-dtype `src` input + a `fixed(DST)` output, so none of them dtype-fan —
6641/// the importer's key-builder emits `[SRC, DST]` (the src input dtype + the
6642/// `fixed(DST)` output dtype, byte-for-byte the deleted hand-written
6643/// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the section's
6644/// SPECIFIC `cast_<src>_to_<dst>` byte-kernel `entry_point` AS-IS through the
6645/// production [`crate::fkc::CpuLinkRegistry`] (chaining
6646/// [`crate::fkc::CPU_CAST_ENTRY_POINTS`]). Because the binding lookup is keyed on
6647/// the TARGET dtype, all 10 of a target's source pairs bind the SAME per-target
6648/// `cast_to_<dst>_cpu_wrapper` (which `match`es on the source dtype internally) —
6649/// 10 distinct real byte-kernel entry_points → 1 wrapper (the synthetic-umbrella
6650/// precedent). This is the SOLE registration path for the whole family; every
6651/// hand-written `table.register(Cast, …)` reg is DELETED. Identity pairs
6652/// (`[T, T]`) are never registered — the optimizer elides identity `Cast` before
6653/// dispatch, and the per-target wrappers carry no identity arm.
6654///
6655/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6656/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6657/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6658/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6659/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6660/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6661/// required fused argument is a local throwaway that provably stays empty.
6662fn register_cpu_cast_from_contract(table: &mut KernelBindingTable) {
6663    let provider = crate::fkc::import_bundle_str(CPU_CAST_CONTRACT, &crate::fkc::CpuLinkRegistry)
6664        .expect(
6665            "authored CPU cast contract must import \
6666                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6667        );
6668    debug_assert!(
6669        provider.fused.is_empty(),
6670        "cast contract declares no fused ops",
6671    );
6672    let mut fused = crate::fused::FusedKernelRegistry::new();
6673    provider
6674        .register_into(table, &mut fused)
6675        .expect("CPU cast contract must register into the binding table");
6676}
6677
6678/// The authored CPU **indexing / gather / scatter** kernel contract, embedded
6679/// into the binary (the PRODUCTION `include_str!`).
6680/// `register_cpu_indexing_from_contract` parses + lowers it and binds the FULL
6681/// family (IndexSelect + Gather + IndexAdd + ScatterAdd) FROM THE CONTRACT.
6682const CPU_INDEXING_CONTRACT: &str = include_str!("../kernel-contracts/cpu/indexing.fkc.md");
6683
6684/// Register the FULL CPU indexing family — IndexSelect (9 dtypes, key
6685/// `[T, U32, T]`) + Gather (9 dtypes, key `[T, U32, T]`) + IndexAdd (4 dtypes,
6686/// key `[T, U32, T, T]`) + ScatterAdd (4 dtypes, key `[T, U32, T, T]`) = 26
6687/// bindings — by IMPORTING its FKC kernel contract, the eighteenth production
6688/// FKC consumer.
6689///
6690/// - **IndexSelect** / **Gather** — the ONE section each declares a BASE
6691///   `entry_point` (`…::index_select_cpu` / `…::gather_cpu`, a dtype-agnostic
6692///   byte copy) + an enumerated `dtypes` list, so the importer's §3.4 fan-out
6693///   resolves `<base>_<dtype>` — every dtype variant mapping to the ONE
6694///   dtype-agnostic `index_select_cpu_wrapper` / `gather_cpu_wrapper` through the
6695///   production [`crate::fkc::CpuLinkRegistry`] (chaining
6696///   [`crate::fkc::cpu_link::CPU_INDEXING_ENTRY_POINTS`]). The `indices` operand
6697///   is the FIXED U32 slot and `out: passthrough(source)`, so the fan emits key
6698///   `[T, U32, T]` — byte-for-byte the deleted hand-written
6699///   `table.register(IndexSelect/Gather, &index_select(dt)/&gather_dts(dt), …)`
6700///   regs. The contract's dtype list was trimmed to production's 9 wired dtypes
6701///   (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is describable (byte-agnostic) but
6702///   NOT wired in production, so it is dropped from the contract.
6703/// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
6704///   native, bf16/f16 widen to an f32 accumulator; out seeded from `base` then
6705///   `+= src`), so each `index_add_<dt>` / `scatter_add_<dt>` section carries a
6706///   SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan), key
6707///   `[T, U32, T, T]` (`base`, U32 `indices`, `src`, `passthrough(base)` output)
6708///   — byte-for-byte the deleted `table.register(IndexAdd/ScatterAdd, …)` regs.
6709///
6710/// The `indices` slot being a FIXED single-dtype (U32) in every section means
6711/// there is NO independent index-dtype axis and no multi-axis
6712/// `FanoutDtypeMismatch` deferral — the whole family migrates (unlike the metal
6713/// indexing situation).
6714///
6715/// Behavior-preserving vs. the deleted hand-written path: identical kernels +
6716/// caps (contiguous-only); the binding's `kernel_source` becomes the contract's
6717/// `"portable-cpu"` tag and its precision the contract's bit-stable claim. Cost
6718/// is preserved because this runs BEFORE `fill_unset_cpu_cost`, which upgrades
6719/// the imported entries' `unknown_cost` sentinel to the same OpKind cost fn every
6720/// CPU primitive gets. The family declares NO fused ops, so `register_into`'s
6721/// required fused argument is a local throwaway that provably stays empty.
6722fn register_cpu_indexing_from_contract(table: &mut KernelBindingTable) {
6723    let provider =
6724        crate::fkc::import_bundle_str(CPU_INDEXING_CONTRACT, &crate::fkc::CpuLinkRegistry).expect(
6725            "authored CPU indexing contract must import \
6726                 (embedded via include_str!, resolved through CpuLinkRegistry)",
6727        );
6728    debug_assert!(
6729        provider.fused.is_empty(),
6730        "indexing 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 indexing contract must register into the binding table");
6736}
6737
6738/// Register CPU dispatch wrappers in the binding table. Call once
6739/// at process startup or on first table creation. The CPU backend
6740/// is the universal fallback; its bindings cover every standard
6741/// (op, dtype) combination after Phase C migration. Today's set
6742/// covers the elementwise binary + unary `f32` families.
6743pub fn register_cpu_kernels(table: &mut KernelBindingTable) {
6744    use OpKind::*;
6745    let cpu = BackendId::Cpu;
6746    let f32_dt = DType::F32;
6747    let f64_dt = DType::F64;
6748    let bf16_dt = DType::BF16;
6749    let f16_dt = DType::F16;
6750    let u32_dt = DType::U32;
6751
6752    // Per-operand dtype-list shape helpers. The list captures all
6753    // operands the kernel sees — inputs in order, then outputs.
6754    // Variadic Concat uses the `unary` shape as a canonical
6755    // shorthand for "uniform-dtype across N inputs + output."
6756    let unary = |t: DType| [t, t]; // (in, out)
6757    // (MatMul's (lhs, rhs, out) key shape is now built by the FKC importer from
6758    // fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
6759    // register_cpu_matmul_from_contract; the hand-written `binary` closure was
6760    // removed with its regs.)
6761    let u8_dt = DType::U8;
6762    // (Rope's (x, cos, sin, out) key shape is now built by the FKC importer
6763    // from fuel-dispatch/kernel-contracts/cpu/rope.fkc.md — see
6764    // register_cpu_rope_from_contract; the hand-written `rope_dts` closure was
6765    // removed with its regs.)
6766    // (Conv2D/ConvTranspose2D are now FULLY built by the FKC importer from
6767    // fuel-dispatch/kernel-contracts/cpu/conv.fkc.md — see register_cpu_conv_from_contract.
6768    // The contract marks `bias` as `optional: true`, so the importer's key-builder
6769    // now emits BOTH the no-bias (x, w, out) and with-bias (x, w, bias, out) keys
6770    // per (op, dtype); the hand-written `conv2d_with_bias` / `conv2d_no_bias`
6771    // closures + their regs were all removed.)
6772    // (FusedLinear's (lhs, rhs, bias, out) key shape is now built by the FKC
6773    // importer from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md — see
6774    // register_cpu_matmul_from_contract; the hand-written `fused_linear` closure
6775    // was removed with its regs.)
6776    // FlashAttn / FlashAttnBackward{Q,K,V} / PagedAttn key-shape closures were
6777    // DELETED with the migration to FKC-contract registration (the importer's
6778    // optional-operand fan builds both alibi keys from the contract).
6779    // (IndexSelect/Gather's (data, indices, out) = [T, U32, T] and IndexAdd/
6780    // ScatterAdd's (base, indices, src, out) = [T, U32, T, T] key shapes are now
6781    // built by the FKC importer from fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md —
6782    // see register_cpu_indexing_from_contract; the hand-written `index_select` /
6783    // `gather_dts` / `index_add_dts` / `scatter_add` closures were removed with
6784    // their regs.)
6785
6786    // Elementwise binary family (8 ops × 4 dtypes = 32 bindings:
6787    // Add/Sub/Mul/Div/Maximum/Minimum/Pow/Rem × F32/F64/BF16/F16).
6788    //
6789    // This family is the FIRST production FKC-contract consumer: it is
6790    // IMPORTED from its kernel contract
6791    // (fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md), resolving every
6792    // `entry_point` symbol through the production `CpuLinkRegistry` to the
6793    // exact same wrapper fn-pointers the CPU backend exposes. The hand-written
6794    // `table.register(...)` calls this family used to carry are DELETED — FKC
6795    // is unconditional core infrastructure, so this is the sole registration
6796    // path (no build config, no fallback). Placed here — BEFORE the
6797    // `fill_unset_cpu_*` passes — so the imported entries pick up the same CPU
6798    // cost fill every other CPU primitive gets.
6799    register_cpu_binary_from_contract(table);
6800
6801    // Out-of-place scalar-param family (affine/clamp/powi × 4 dtypes +
6802    // powi_backward × 4 = 16 bindings). Second production FKC-contract
6803    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md
6804    // via the same `CpuLinkRegistry`. The hand-written `table.register(...)`
6805    // calls (Affine / ClampElementwise / PowIElementwise / PowIElementwiseBackward)
6806    // are DELETED — this is the sole registration path. Placed BEFORE the
6807    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
6808    // fill. (The in-place InplaceAffine/ClampInplace/PowIInplace family and the
6809    // FusedOps::POWI_BACKWARD fused-registry seam are separate and untouched.)
6810    register_cpu_affine_clamp_powi_from_contract(table);
6811
6812    // Elementwise unary (22 ops × 4 dtypes = 88 bindings: relu/neg/sqr/sqrt/
6813    // recip/abs/tanh/exp/log/sin/cos/sigmoid/silu/step/gelu_tanh/floor/ceil/round/
6814    // sign/erf/gelu/rsqrt × F32/F64/BF16/F16). Third production FKC-contract
6815    // consumer and the FIRST user of the §3.4 multi-dtype fan-out: IMPORTED from
6816    // fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md via the same
6817    // `CpuLinkRegistry`. Each per-op section declares a BASE entry_point that the
6818    // importer expands to `<base>_<dtype>`. The hand-written `table.register(...)`
6819    // calls (the F32/F64/BF16/F16 unary blocks + the rounding/sign/erf/gelu/
6820    // rsqrt block) are DELETED — this is the sole registration path. Placed
6821    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
6822    // cost fill. gelu_tanh (GeluTanhElementwise) and gelu (GeluElementwise)
6823    // stay DISTINCT.
6824    register_cpu_unary_from_contract(table);
6825
6826    // Compare (6 ops × 4 dtypes = 24, key [T, T, U8]) + where (1 op × 4 dtypes
6827    // = 4, key [U8, T, T, T]) = 28 bindings. Fourth production FKC-contract
6828    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md via
6829    // the same `CpuLinkRegistry`. The 24 compare thunks resolve their declared
6830    // `_u8`-suffixed symbols AS-IS; the single `where_kernel` section rides the
6831    // §3.4 multi-dtype fan-out (BASE `…::where` → `where_{f32,f64,bf16,f16}`)
6832    // and the `passthrough(a)` output rule. The hand-written `table.register(...)`
6833    // calls (the compare block + the `where_dts` block) are DELETED — this is the
6834    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
6835    // imported entries pick up the CPU cost fill.
6836    register_cpu_compare_where_from_contract(table);
6837
6838    // Per-axis reduce (Sum/Mean/Max/Min × 4 dtypes = 16 bindings, key [T, T]).
6839    // Fifth production FKC-contract consumer: IMPORTED from
6840    // fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md via the same `CpuLinkRegistry`.
6841    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
6842    // (`sum_reduce_f32`, …) resolved AS-IS (no fan-out). The hand-written
6843    // `table.register(...)` calls (the F32/F64 + BF16/F16 reduce blocks) are
6844    // DELETED — this is the sole registration path. Placed BEFORE the
6845    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
6846    // fill. The `## reduce` chassis is `registrable: false` (§3.10) and the
6847    // f32-only argmax/argmin sections are deferred (registrable: false); the
6848    // hand-written Arg{Max,Min}Dim regs below stay authoritative.
6849    register_cpu_reduce_from_contract(table);
6850
6851    // Broadcast-target reduce-to (ReduceSumTo / ReduceMaxTo × 4 dtypes, key
6852    // [T, T]; ReduceMaxToBackward × 4 dtypes, key [T, T, T] = 12 bindings).
6853    // Sixth production FKC-contract consumer: IMPORTED from
6854    // fuel-dispatch/kernel-contracts/cpu/reduce-to.fkc.md via the same `CpuLinkRegistry`.
6855    // Each per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
6856    // (`reduce_sum_to_f32`, …) resolved AS-IS (no fan-out). The hand-written
6857    // `table.register(...)` calls (the ReduceSumTo/ReduceMaxTo forward block +
6858    // the ReduceMaxToBackward block) are DELETED — this is the sole registration
6859    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
6860    // pick up the CPU cost fill. The `## reduce_to` chassis is
6861    // `registrable: false` (§3.10) and never registers.
6862    register_cpu_reduce_to_from_contract(table);
6863
6864    // Last-dim NORM forward (Softmax / LogSoftmax / RmsNorm / LayerNorm × 4
6865    // dtypes = 16 bindings, key [T, T]). Seventh production FKC-contract
6866    // consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm.fkc.md via the same
6867    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
6868    // single-dtype entry_point (`softmax_last_dim_f32`, `rms_norm_last_dim_f32`,
6869    // …) resolved AS-IS (no fan-out). The RMS/LayerNorm kernels are the BARE
6870    // normalization (no affine gamma/beta operand); outer_count/last_dim/eps ride
6871    // in OpParams, so the key stays [T, T]. The hand-written `table.register(...)`
6872    // calls (the LogSoftmaxLastDim block above + the SoftmaxLastDim / RmsNormLastDim
6873    // / LayerNormLastDim block below) are DELETED — this is the sole registration
6874    // path. Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries
6875    // pick up the CPU cost fill. The norm ops' SEPARATE FusedKernelRegistry seam
6876    // (register_default_fused_kernels) and the norm-BACKWARD hand-written regs stay
6877    // untouched.
6878    register_cpu_norm_from_contract(table);
6879
6880    // Last-dim NORM BACKWARD (Softmax / LogSoftmax / RmsNorm / LayerNorm backward
6881    // × 4 dtypes = 16 bindings, key [T, T, T]). Eighth production FKC-contract
6882    // consumer and the BACKWARD sibling of the norm-forward importer above:
6883    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/norm-backward.fkc.md via the same
6884    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
6885    // single-dtype entry_point (`softmax_last_dim_backward_f32`,
6886    // `rms_norm_last_dim_backward_f32`, …) resolved AS-IS (no fan-out). The BARE
6887    // backward takes TWO inputs (y/x + upstream gradient g) → ONE passthrough
6888    // output, so the key is [T, T, T]; outer_count/last_dim/eps ride in OpParams.
6889    // The hand-written `table.register(...)` calls (the LogSoftmaxLastDimBackward
6890    // block + the SoftmaxLastDimBackward / LayerNormLastDimBackward /
6891    // RmsNormLastDimBackward block below) are DELETED — this is the sole
6892    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
6893    // imported entries pick up the CPU cost fill. The norm-backward ops' SEPARATE
6894    // FusedKernelRegistry seam (register_default_fused_kernels) stays untouched.
6895    register_cpu_norm_backward_from_contract(table);
6896
6897    // RoPE (rotary position embedding; 1 op × 4 dtypes = 4 bindings, key
6898    // [T, T, T, T]). Ninth production FKC-contract consumer: IMPORTED from
6899    // fuel-dispatch/kernel-contracts/cpu/rope.fkc.md via the same `CpuLinkRegistry`.
6900    // Each per-dtype section carries a SPECIFIC single-dtype entry_point
6901    // (`rope_f32`, …) resolved AS-IS (no fan-out). RoPE takes THREE inputs
6902    // (x + the precomputed cos/sin tables, all one dtype) → ONE passthrough(x)
6903    // output, so the key is [T, T, T, T]; outer_count/seq/head_dim ride in
6904    // OpParams::Rope. The hand-written `table.register(Rope, ...)` calls (the
6905    // rope_dts block below) are DELETED — this is the sole registration path.
6906    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick
6907    // up the CPU cost fill. RoPE's SEPARATE FusedKernelRegistry seam
6908    // (register_default_fused_kernels, FusedOps::ROPE) stays untouched.
6909    register_cpu_rope_from_contract(table);
6910
6911    // CPU SSM / Mamba family — the FULL family: FusedSoftmaxCrossEntropy
6912    // (key [T, I64, F32]) + CausalConv1d (key [T, T, T, T]) + SelectiveScan +
6913    // SsdChunkScan (key [T; 6]), 4 ops × 4 dtypes = 16 bindings. Tenth
6914    // production FKC-contract consumer: IMPORTED from
6915    // fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md via the same `CpuLinkRegistry`. Each
6916    // per-(op,dtype) section carries a SPECIFIC single-dtype entry_point
6917    // (`fused_softmax_cross_entropy_f32`, `selective_scan_f32`, …) resolved AS-IS
6918    // (no fan-out). The two SCAN ops return a `return.bundle` multi-output
6919    // (Option C, one buffer [y ; last_state]); the importer now appends the
6920    // bundle's primary-slot dtype to the key tail, so they key [T; 6]
6921    // byte-for-byte the deleted hand-written regs. Every hand-written
6922    // `table.register(...)` call for the whole family is DELETED — this is its
6923    // sole registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
6924    // imported entries pick up the CPU cost fill.
6925    register_cpu_ssm_from_contract(table);
6926
6927    // NonZeroIndices — the keystone primitive for data-dependent dynamic
6928    // shapes (SSM decode / MoE sparsity / MLA KV compression). One input
6929    // `x` → one bundled output `[indices [capacity] U32 ; count [1] U32]`;
6930    // the binding key is `[input_dtype, U32]` (input + primary output-slot
6931    // dtype). Registered DIRECTLY (not yet FKC-contract-sourced): the
6932    // op's U32 output slot is a *constant* dtype, not a `passthrough` of a
6933    // T input, which the current contract key-builder does not express —
6934    // so this bring-up primitive registers by hand and is a candidate to
6935    // migrate once a data-dependent-ops contract family grows. Placed
6936    // BEFORE the `fill_unset_cpu_*` passes so the entries pick up the CPU
6937    // precision + cost fill (UNAUDITED → PRIMITIVE_DETERMINISTIC_CPU,
6938    // unknown_cost → the OpKind cost fn).
6939    table.register(
6940        NonZeroIndices,
6941        &[f32_dt, u32_dt],
6942        cpu,
6943        nonzero_indices_f32_cpu_wrapper,
6944    );
6945    table.register(
6946        NonZeroIndices,
6947        &[u32_dt, u32_dt],
6948        cpu,
6949        nonzero_indices_u32_cpu_wrapper,
6950    );
6951
6952    // CPU 2D-convolution family — FULLY contract-sourced: Conv2D +
6953    // ConvTranspose2D at BOTH the no-bias key [T, T, T] (x, weight, out) AND the
6954    // with-bias key [T, T, T, T] (x, weight, bias + passthrough(x) output), 2 ops
6955    // × 4 dtypes × 2 operand-counts = 16 bindings. Eleventh production
6956    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/conv.fkc.md
6957    // via the same `CpuLinkRegistry`. Each per-(op,dtype) section carries a
6958    // SPECIFIC single-dtype entry_point (`conv2d_f32`, `conv_transpose2d_f32`, …)
6959    // resolved AS-IS (no dtype fan-out); every geometry knob rides in
6960    // OpParams::{Conv2D, ConvTranspose2D}. The contract marks `bias` as
6961    // `optional: true`, so the importer's optional-operand key-builder fans each
6962    // section into both the no-bias and with-bias keys (same wrapper handles 2 or
6963    // 3 inputs) — ALL hand-written conv `table.register(...)` calls are DELETED,
6964    // this is the sole registration path for the whole family. Placed BEFORE the
6965    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost fill.
6966    // The conv ops' SEPARATE FusedKernelRegistry seam
6967    // (register_default_fused_kernels, FusedOps::{CONV2D, CONV_TRANSPOSE2D}) stays
6968    // untouched.
6969    register_cpu_conv_from_contract(table);
6970
6971    // CPU padding family (FULL) — mode-unified forward Pad × 6 dtypes = 6 +
6972    // PadBackward × 4 dtypes = 4 bindings (all key [T, T]). Twelfth production
6973    // FKC-contract consumer: IMPORTED from fuel-dispatch/kernel-contracts/cpu/padding.fkc.md
6974    // via the same `CpuLinkRegistry`. The ONE mode-unified `## pad` forward section
6975    // declares a BASE entry_point (`pad_cpu`) + the 6 wired dtypes (U8/U32/BF16/
6976    // F16/F32/F64), so the fan resolves `pad_cpu_<dtype>` (all → the one
6977    // mode-dispatching `pad_cpu_wrapper`, which selects Constant/Reflect/Replicate
6978    // at runtime via mode_tag); each per-dtype backward section carries a SPECIFIC
6979    // single-dtype entry_point (`pad_backward_f32`, …) resolved AS-IS (no fan).
6980    // in_shape/out_shape/padding/mode_tag/fill_bytes ride in OpParams::{Pad,
6981    // PadBackward}. The three per-mode forward sections + the pad_walk_cpu helper
6982    // are `registrable: false` describe-only. ALL hand-written forward + backward
6983    // `table.register(Pad/PadBackward, …)` regs are DELETED — this is their sole
6984    // registration path. Placed BEFORE the `fill_unset_cpu_*` passes so the
6985    // imported entries pick up the CPU cost fill.
6986    register_cpu_padding_from_contract(table);
6987
6988    // CPU shape-ops family (migratable subset) — Flip + Roll + Concat +
6989    // MaskedFill + WriteSlice + WriteSliceRotating (dtype-agnostic byte kernels
6990    // fanned per production dtype: Flip/Roll/MaskedFill/WriteSlice/
6991    // WriteSliceRotating 6 dtypes, Concat 9) + the four per-dtype CumSum kernels.
6992    // Thirteenth production FKC-contract consumer: IMPORTED from
6993    // fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md via the same `CpuLinkRegistry`.
6994    // Flip/Roll/Concat/MaskedFill/WriteSlice/WriteSliceRotating sections declare a
6995    // BASE entry_point + a dtypes list trimmed to the wired set, so the fan
6996    // resolves `<base>_<dtype>` (all → the one dtype-agnostic wrapper); CumSum's
6997    // per-dtype sections resolve their SPECIFIC `cumsum_<dt>` symbol AS-IS. Keys:
6998    // Flip/Roll/Concat/CumSum/WriteSlice/WriteSliceRotating [T, T], MaskedFill
6999    // [T, U8, T]. WriteSlice/WriteSliceRotating model `dest` as the in-place
7000    // OUTPUT slot (and rotating's `position` as a non-key runtime operand), so the
7001    // imported key matches build_lookup_dtypes' canonicalized [T_src, T_out]. The
7002    // migrated hand-written regs are DELETED — this is their sole registration
7003    // path. DEFERRED (hand-written kept): Triu/Tril (the contract carries only the
7004    // `triangular` describe-only chassis) + Contiguize (no OpKind — an executor
7005    // materialize pass). Placed BEFORE the `fill_unset_cpu_*` passes so the
7006    // imported entries pick up the CPU cost fill.
7007    register_cpu_shape_ops_from_contract(table);
7008
7009    // CPU matmul family — FULLY contract-sourced (PORTABLE kernels): bare
7010    // batched MatMul (6 dtypes F32/F64/BF16/F16/I8/U8, key [T, T, T]) + fused
7011    // FusedLinear (matmul + bias-add, 4 dtypes F32/F64/BF16/F16, key
7012    // [T, T, T, T]) = 10 bindings. Fourteenth production FKC-contract consumer:
7013    // IMPORTED from fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md via the same
7014    // `CpuLinkRegistry`. Each per-(op,dtype) section carries a SPECIFIC
7015    // single-dtype entry_point (`matmul_f32`, `fused_linear_f32`, …) resolved
7016    // AS-IS (no fan-out); the batch geometry (lhs_batch_dims/rhs_batch_dims/
7017    // m/n/k) rides in OpParams::Matmul (FusedLinear reuses it). Integer MatMul
7018    // (I8/U8) accumulates in i32 and saturates on store. Every hand-written
7019    // portable `table.register(MatMul / FusedLinear, …)` call is DELETED — this
7020    // is the sole registration path for the portable family. Placed BEFORE the
7021    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU cost
7022    // fill. ALTERNATIVES-AT-KEY: the MKL/AOCL BLAS siblings register at these
7023    // SAME keys from SEPARATE external crates with their own `"mkl"`/`"aocl"`
7024    // kernel_source tags — SEPARATE and untouched (not registered in this build).
7025    // The SEPARATE FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7026    // (register_default_fused_kernels) is hand-written and stays untouched; the
7027    // quant QMatMul/Nf4Matmul OpKinds have their own contracts and stay
7028    // hand-written below.
7029    register_cpu_matmul_from_contract(table);
7030
7031    // The CPU ATTENTION family's KernelBindingTable path — forward FlashAttn (4
7032    // dtypes) + FlashAttnBackward{Q,K,V} (3 selectors × 4 dtypes) + PagedAttn (4
7033    // dtypes), each alibi-optional section fanning into BOTH the no-alibi and
7034    // with-alibi keys = 40 bindings — is now registered FROM
7035    // fuel-dispatch/kernel-contracts/cpu/attention.fkc.md by
7036    // register_cpu_attention_from_contract. The contract marks `alibi_slopes`
7037    // as `optional: true`, so the importer's key-builder fans each (op, dtype)
7038    // section into both operand-count keys; FKC is the SOLE path for the migrated
7039    // family. All hand-written FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn
7040    // regs (both alibi keys) were DELETED. PagedAttn's fdx.gather pool is import
7041    // METADATA (§3.9.1: it dispatches via ordinary U32 block_table/context_lens
7042    // operands + OpParams::PagedAttn), so it registers here too; only the FDX VIEW
7043    // seam stays [consumer-ahead]. The SEPARATE FusedKernelRegistry
7044    // FLASH_ATTN*/PAGED_ATTN seam (register_default_fused_kernels) is untouched.
7045    // Placed BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up
7046    // the CPU cost fill.
7047    register_cpu_attention_from_contract(table);
7048
7049    // The CPU IN-PLACE scalar-param family's KernelBindingTable path — 21 in-place
7050    // unary ops (each per-op section fanning [F32,F64,BF16,F16] = 84) +
7051    // InplaceAffine / ClampInplace / PowIInplace (per-dtype single sections, 4 each
7052    // = 12) = 96 bindings, all keyed [T, T] — is now registered FROM
7053    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7054    // register_cpu_inplace_from_contract. FKC is the SOLE path for the whole
7055    // family; all hand-written <Op>Inplace / InplaceAffine / ClampInplace /
7056    // PowIInplace regs were DELETED. The `unary_inplace` chassis section is
7057    // describe-only (registrable: false). Placed BEFORE the `fill_unset_cpu_*`
7058    // passes; the in-place OpKinds keep the `unknown_cost` sentinel (no arm in
7059    // default_cost_for_op_kind, not on the cost-coverage lint set) — identical to
7060    // the deleted hand-written regs.
7061    register_cpu_inplace_from_contract(table);
7062
7063    // (bf16 + f16 reductions are now registered from the reduce contract above,
7064    // alongside the f32/f64 variants — accumulate in f32 for stability.)
7065
7066    // Cast — the COMPLETE directed-pair matrix: every ordered pair of the 11
7067    // real numeric dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64} with
7068    // identity excluded = 11 × 10 = 110 bindings (all key `[SRC, DST]`) — is now
7069    // registered FROM fuel-dispatch/kernel-contracts/cpu/cast.fkc.md by
7070    // register_cpu_cast_from_contract. Each per-pair section declares a
7071    // single-dtype `src` input + a `fixed(DST)` output (no dtype fan), so the
7072    // importer keys `[SRC, DST]` and resolves the SPECIFIC `cast_<src>_to_<dst>`
7073    // byte-kernel entry_point AS-IS; because the lookup is keyed on the TARGET
7074    // dtype, all 10 of a target's source pairs bind the SAME per-target
7075    // `cast_to_<dst>_cpu_wrapper` (10 real entry_points → 1 wrapper). FKC is the
7076    // SOLE path for the whole family; all hand-written `table.register(Cast, …)`
7077    // regs were DELETED. Identity pairs are never registered — the optimizer
7078    // elides identity Cast before dispatch. The MX dummy dtypes
7079    // (F6E2M3,F6E3M2,F4,F8E8M0) have no Rust scalar type and are excluded. Placed
7080    // BEFORE the `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7081    // cost/precision fill.
7082    register_cpu_cast_from_contract(table);
7083
7084    // CPU indexing / gather / scatter family — IndexSelect + Gather
7085    // (dtype-agnostic byte copies fanned per dtype: 9 dtypes each, key
7086    // [T, U32, T], the fabricated `<base>_<dt>` symbol resolving to the ONE
7087    // wrapper) + IndexAdd + ScatterAdd (per-dtype typed accumulation: 4 dtypes
7088    // each, key [T, U32, T, T], `<op>_<dt>` resolved AS-IS). Eighteenth
7089    // production FKC consumer: IMPORTED from
7090    // fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md via the same `CpuLinkRegistry`.
7091    // The `indices` slot is a FIXED U32 operand in every section (no independent
7092    // index-dtype axis), so there is no multi-axis fan-out deferral — the whole
7093    // family migrates. The contract's index_select/gather dtype list is trimmed
7094    // to production's 9 wired dtypes (I8 describable but NOT wired). ALL
7095    // hand-written `table.register(IndexSelect/Gather/IndexAdd/ScatterAdd, …)`
7096    // regs are DELETED — this is their sole registration path. Placed BEFORE the
7097    // `fill_unset_cpu_*` passes so the imported entries pick up the CPU
7098    // cost/precision fill.
7099    register_cpu_indexing_from_contract(table);
7100
7101    // Conv2D / ConvTranspose2D — BOTH the no-bias key [T, T, T] (x, weight, out)
7102    // AND the with-bias key [T, T, T, T] (x, weight, bias, out) are now registered
7103    // FROM the conv FKC contract (`register_cpu_conv_from_contract`, above). The
7104    // contract marks `bias` as `optional: true`, so the importer's key-builder
7105    // fans each (op, dtype) section into both operand-count keys — FKC is the SOLE
7106    // path for the whole conv family (16 bindings). All hand-written conv regs were
7107    // DELETED (the no-bias deferral is closed).
7108
7109    // ReduceSumTo / ReduceMaxTo (× 4 dtypes, key [T, T]) are now registered
7110    // FROM the reduce-to FKC contract (`register_cpu_reduce_to_from_contract`,
7111    // above) — the hand-written regs were DELETED (FKC is the sole path). The
7112    // ReduceMaxToBackward regs (key [T, T, T]) below were likewise deleted.
7113
7114    // FusedLinear (3 inputs lhs, rhs, bias → out; key [T, T, T, T]) is now
7115    // registered FROM the matmul FKC contract
7116    // (`register_cpu_matmul_from_contract`, above) — the hand-written regs were
7117    // DELETED (FKC is the sole path for the portable family). The SEPARATE
7118    // FusedKernelRegistry FusedOps::FUSED_LINEAR seam
7119    // (`register_default_fused_kernels`) is hand-written and stays untouched.
7120
7121    // FlashAttn (forward) + FlashAttnBackward{Q,K,V} + PagedAttn — both the
7122    // no-alibi and with-alibi keys per dtype — are now registered FROM the
7123    // attention FKC contract (`register_cpu_attention_from_contract`, near the top
7124    // of this fn). The contract marks `alibi_slopes` as `optional: true`, so the
7125    // importer's key-builder fans each (op, dtype) section into both operand-count
7126    // keys — FKC is the SOLE path for the migrated attention family (40 bindings:
7127    // FlashAttn 8 + FlashAttnBackward{Q,K,V} 24 + PagedAttn 8). All hand-written
7128    // FlashAttn + FlashAttnBackward{Q,K,V} + PagedAttn regs (both alibi keys) were
7129    // DELETED. PagedAttn's `fdx.gather: paged_blocks` pool is import METADATA
7130    // (§3.9.1): block_table/context_lens ride as ordinary U32 operands +
7131    // OpParams::PagedAttn, so registration does not depend on the FDX gather VIEW
7132    // (that stays [consumer-ahead]).
7133
7134    // (Affine F32 is now registered from the affine-clamp-powi contract above.)
7135
7136    // The in-place scalar-param family — InplaceAffine / ClampInplace /
7137    // PowIInplace (each key [T, T], scalars in OpParams::{Affine, Clamp, PowI}) —
7138    // is now registered FROM fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md
7139    // by register_cpu_inplace_from_contract near the top of this fn (alongside the
7140    // 21 in-place unary ops). The affine sections' op_kind was corrected from the
7141    // out-of-place `Affine` to `InplaceAffine`; all hand-written in-place scalar
7142    // regs were DELETED with the migration.
7143
7144    // The ENTIRE CPU SSM / Mamba family — FusedSoftmaxCrossEntropy (key
7145    // [T, I64, F32]), CausalConv1d (key [T, T, T, T]), and the two SCAN ops
7146    // SelectiveScan / SsdChunkScan (key [T; 6] — 5 inputs + the ONE bundled
7147    // output slot) — is now registered from fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md
7148    // by register_cpu_ssm_from_contract near the top of this fn. The scans'
7149    // `return.bundle` multi-output is now key-buildable by the importer (it
7150    // appends the bundle's primary-slot dtype to the key tail), so their
7151    // hand-written `table.register(SelectiveScan/SsdChunkScan, &[dt; 6], ...)`
7152    // loops that used to live here were DELETED with the migration.
7153
7154    // Nf4Matmul: 3 inputs (activations T, w_packed U8, absmax F32) + 1
7155    // output T, where T ∈ {F32, F16, BF16}. The binding-table key
7156    // shape is [T, U8, F32, T].
7157    table.register(
7158        Nf4Matmul,
7159        &[DType::F32, DType::U8, DType::F32, DType::F32],
7160        cpu,
7161        nf4_matmul_f32_cpu_wrapper,
7162    );
7163    table.register(
7164        Nf4Matmul,
7165        &[DType::F16, DType::U8, DType::F32, DType::F16],
7166        cpu,
7167        nf4_matmul_f16_cpu_wrapper,
7168    );
7169    table.register(
7170        Nf4Matmul,
7171        &[DType::BF16, DType::U8, DType::F32, DType::BF16],
7172        cpu,
7173        nf4_matmul_bf16_cpu_wrapper,
7174    );
7175
7176    // The 21 in-place unary activations (Relu/Silu/GeluTanh/Tanh/Sigmoid/Neg/Abs/
7177    // Sqr/Sqrt/Rsqrt/Recip/Exp/Log/Sin/Cos/Sign/Floor/Ceil/Round/Erf/Gelu ×
7178    // F32/F64/BF16/F16 = 84 bindings, each key [T, T]) are now registered FROM
7179    // fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md by
7180    // register_cpu_inplace_from_contract near the top of this fn: each per-op
7181    // section declares a BASE entry_point `<op>_inplace` + enumerates
7182    // [F32,F64,BF16,F16], so the importer's §3.4 dtype fan resolves
7183    // `<op>_inplace_<dt>` to the exact wrapper. All hand-written in-place unary
7184    // regs (the 5-op starter set + the 16-op expansion loop) were DELETED with
7185    // the migration; the shared `unary_inplace` chassis section is describe-only.
7186
7187    // (ClampElementwise / PowIElementwise F32 are now registered from the
7188    // affine-clamp-powi contract above.)
7189
7190    // Comparison (6 ops × 4 dtypes, key [T, T, U8]) + ternary select `where`
7191    // (4 dtypes, key [U8, T, T, T]) are now registered FROM the compare-where
7192    // FKC contract via register_cpu_compare_where_from_contract (near the top of
7193    // this fn) — the hand-written regs (and the `compare` / `where_dts`
7194    // dtype-list closures) are DELETED.
7195
7196    // Rounding / sign / transcendental unary ops (floor/ceil/round/sign/erf/
7197    // gelu/rsqrt × F32/F64/BF16/F16) are registered from the elementwise-unary
7198    // FKC contract via register_cpu_unary_from_contract (near the top of this fn).
7199
7200    // (Flip / Roll × 6 dtypes [T, T] and CumSum × 4 dtypes [T, T] are now
7201    // registered FROM the shape-ops FKC contract via
7202    // register_cpu_shape_ops_from_contract near the top of this fn — Flip/Roll are
7203    // one dtype-agnostic wrapper fanned per dtype; CumSum's per-dtype typed
7204    // sections resolve AS-IS. The hand-written regs were DELETED — FKC is the sole
7205    // path.)
7206
7207    // (WriteSlice + WriteSliceRotating × 6 dtypes, key [T, T], are now registered
7208    // FROM the shape-ops FKC contract via register_cpu_shape_ops_from_contract
7209    // near the top of this fn — one dtype-agnostic wrapper each, fanned per dtype.
7210    // Both model `dest` as the in-place OUTPUT slot (and rotating's `position` as a
7211    // non-key runtime operand), so the imported key matches build_lookup_dtypes'
7212    // canonicalized `[T_src, T_out]`. The hand-written regs were DELETED — FKC is
7213    // the sole path.)
7214
7215    // Triu / Tril share one byte-level kernel (dtype-agnostic).
7216    table.register(Triu, &unary(f32_dt), cpu, triu_cpu_wrapper);
7217    table.register(Triu, &unary(f64_dt), cpu, triu_cpu_wrapper);
7218    table.register(Triu, &unary(bf16_dt), cpu, triu_cpu_wrapper);
7219    table.register(Triu, &unary(f16_dt), cpu, triu_cpu_wrapper);
7220    table.register(Triu, &unary(u32_dt), cpu, triu_cpu_wrapper);
7221    table.register(Triu, &unary(u8_dt), cpu, triu_cpu_wrapper);
7222    table.register(Tril, &unary(f32_dt), cpu, tril_cpu_wrapper);
7223    table.register(Tril, &unary(f64_dt), cpu, tril_cpu_wrapper);
7224    table.register(Tril, &unary(bf16_dt), cpu, tril_cpu_wrapper);
7225    table.register(Tril, &unary(f16_dt), cpu, tril_cpu_wrapper);
7226    table.register(Tril, &unary(u32_dt), cpu, tril_cpu_wrapper);
7227    table.register(Tril, &unary(u8_dt), cpu, tril_cpu_wrapper);
7228
7229    // (LogSoftmaxLastDim × 4 dtypes is now registered FROM the norm FKC contract
7230    // via register_cpu_norm_from_contract near the top of this fn, alongside
7231    // Softmax / RmsNorm / LayerNorm forward.)
7232
7233    // (SoftmaxLastDimBackward / LogSoftmaxLastDimBackward / LayerNormLastDimBackward
7234    // / RmsNormLastDimBackward × 4 dtypes = 16 bindings, key [T, T, T]) are now
7235    // registered FROM the norm-backward FKC contract via
7236    // register_cpu_norm_backward_from_contract near the top of this fn — the BARE
7237    // backward (two inputs y/x + upstream gradient g → one passthrough output;
7238    // outer_count/last_dim/eps in OpParams). Their SEPARATE FusedKernelRegistry
7239    // seam (register_default_fused_kernels) stays untouched.
7240    // ReduceMaxToBackward (× 4 dtypes, key [T, T, T]) is now registered FROM the
7241    // reduce-to FKC contract (`register_cpu_reduce_to_from_contract`); the
7242    // hand-written regs were DELETED (FKC is the sole path).
7243
7244    // (MaskedFill × 6 dtypes, key [T, U8, T] — x dtype, mask U8, output == x — is
7245    // now registered FROM the shape-ops FKC contract via
7246    // register_cpu_shape_ops_from_contract near the top of this fn: `input` is the
7247    // sole varying operand that drives the fan, `mask` is the fixed U8 slot, and
7248    // `out: passthrough(input)`. The hand-written regs + the `masked_dtypes`
7249    // closure were DELETED — FKC is the sole path.)
7250
7251    // (Pad forward (Constant/Reflect/Replicate) × 6 dtypes — key [T, T], one
7252    // dtype-agnostic `pad_cpu_wrapper` dispatching all three modes at runtime via
7253    // `mode_tag` — is now registered FROM the padding FKC contract via
7254    // register_cpu_padding_from_contract near the top of this fn. The contract's
7255    // ONE mode-unified `## pad` section fans its 6 wired dtypes (U8/U32/BF16/F16/
7256    // F32/F64), ALL resolving `pad_cpu_wrapper`; the three per-mode sections +
7257    // the pad_walk_cpu helper are `registrable: false` describe-only. The
7258    // hand-written regs were DELETED — FKC is the sole path for the forward half.)
7259
7260    // (PadBackward × 4 dtypes — key [T, T], typed accumulation — is likewise
7261    // registered FROM the padding FKC contract via
7262    // register_cpu_padding_from_contract near the top of this fn; the
7263    // hand-written regs were DELETED — FKC is the sole path for the backward
7264    // half.)
7265
7266    // (Elementwise unary BF16 + F16 — like F32/F64 — are registered from the
7267    // elementwise-unary FKC contract via register_cpu_unary_from_contract near
7268    // the top of this fn; the importer fans each per-op section over all four
7269    // dtypes. The binary bf16/f16 ops likewise come from the elementwise-binary
7270    // contract.)
7271
7272    // (Concat — a variadic uniform-dtype op (N inputs, all the same dtype, plus
7273    // output) — is now registered FROM the shape-ops FKC contract via
7274    // register_cpu_shape_ops_from_contract near the top of this fn: the importer
7275    // treats the variadic list as ONE representative input, so the fan builds the
7276    // canonical `[T, T]` shorthand key per supported dtype (9 dtypes; the lookup
7277    // site collapses the actual N+1 dtype list to this same shorthand). The
7278    // hand-written loop was DELETED — FKC is the sole path.)
7279
7280    // (SoftmaxLastDim / RmsNormLastDim / LayerNormLastDim × 4 dtypes are now
7281    // registered FROM the norm FKC contract via register_cpu_norm_from_contract
7282    // near the top of this fn — key [T, T], bare normalization, no affine operand.
7283    // Their SEPARATE FusedKernelRegistry seam and the norm-backward regs stay
7284    // hand-written.)
7285
7286    // (IndexSelect / Gather × 9 dtypes (key [T, U32, T]) are now registered FROM
7287    // the indexing FKC contract via register_cpu_indexing_from_contract above —
7288    // one dtype-agnostic wrapper each, fanned per dtype from a BASE entry_point.
7289    // The hand-written loop was DELETED — FKC is the sole path.)
7290
7291    // (Rope × 4 dtypes is now registered FROM the rope FKC contract via
7292    // register_cpu_rope_from_contract near the top of this fn — key
7293    // [T, T, T, T] (x, cos, sin + passthrough output), geometry in
7294    // OpParams::Rope. Its SEPARATE FusedKernelRegistry seam
7295    // (register_default_fused_kernels, FusedOps::ROPE) stays hand-written.)
7296
7297    // QMatMul: F32 activations, U32 weight blocks, F32 output.
7298    table.register(
7299        QMatMul,
7300        &[f32_dt, u32_dt, f32_dt],
7301        cpu,
7302        qmatmul_f32_cpu_wrapper,
7303    );
7304
7305    // (IndexAdd / ScatterAdd × 4 dtypes (key [T, U32, T, T]) are now registered
7306    // FROM the indexing FKC contract via register_cpu_indexing_from_contract
7307    // above — each per-dtype `<op>_<dt>` entry_point resolved AS-IS to its OWN
7308    // typed wrapper. The hand-written regs were DELETED — FKC is the sole path.)
7309
7310    // ArgMax/ArgMin: input dtype varies, output is U32. The dispatch
7311    // wrapper still does its internal input-dtype match (preserves
7312    // current behavior). Register `[input_dt, U32]` once per input
7313    // dtype the dispatcher handles so the binding table can also
7314    // route directly when we collapse the wrapper later.
7315    for dt in [f32_dt, f64_dt, bf16_dt, f16_dt] {
7316        table.register(ArgMaxDim, &[dt, u32_dt], cpu, argmax_dim_u32_cpu_dispatch);
7317        table.register(ArgMinDim, &[dt, u32_dt], cpu, argmin_dim_u32_cpu_dispatch);
7318    }
7319
7320    // (Affine F64/BF16/F16 are now registered from the affine-clamp-powi
7321    // contract above.)
7322
7323    // Op::Copy — D2H / SameDevice byte-level transfer. The CPU
7324    // registration here is the CPU→CPU memcpy noop; per-source-
7325    // backend registrations live in their dispatch crates
7326    // (`register_cuda_kernels`, `vulkan_dispatch::register_vulkan_kernels`).
7327    // Bridge-retirement Phase 2 (post-9c): every realize root that
7328    // isn't on CPU gets an `Op::Copy { target: Cpu }` spliced in
7329    // before realize; the kernel dispatch resolves on the *source*
7330    // backend's BackendId. CPU→CPU is registered for uniformity (the
7331    // splice doesn't fire when device == Cpu, but kernels registered
7332    // here let direct executor tests round-trip through OpKind::Copy
7333    // on the universal fallback).
7334    let copy_dtypes = [
7335        f32_dt,
7336        f64_dt,
7337        bf16_dt,
7338        f16_dt,
7339        u32_dt,
7340        u8_dt,
7341        DType::I16,
7342        DType::I32,
7343        DType::I64,
7344        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7345        // Op::Copy to materialize a result to host.
7346        DType::Bool,
7347    ];
7348    for dt in copy_dtypes {
7349        table.register(Copy, &[dt, dt], cpu, copy_from_cpu_wrapper);
7350    }
7351    // (ClampElementwise / PowIElementwise F64/BF16/F16 and the two-input
7352    // PowIElementwiseBackward × 4 dtypes are now registered from the
7353    // affine-clamp-powi contract above. The FusedOps::POWI_BACKWARD
7354    // fused-registry seam remains separate and untouched.)
7355
7356    // Phase 7.6 step 7b — populate `PrecisionGuarantee` for every
7357    // CPU primitive registration. Every `table.register(...)` call
7358    // above defaulted to `PrecisionGuarantee::UNAUDITED`; this fill
7359    // pass upgrades them to `PRIMITIVE_DETERMINISTIC_CPU` (bit-stable
7360    // per hardware, deterministic iteration order, F32 accumulator
7361    // for half-precision). Sites that need a weaker claim should
7362    // call `table.register_with_precision(...)` explicitly *before*
7363    // this point — those won't be overwritten because the fill only
7364    // touches UNAUDITED entries.
7365    //
7366    // The architecture-target shape is precision-per-call-site,
7367    // but the 335+ CPU primitive registrations all share the same
7368    // deterministic property; bulk-applying the claim here keeps
7369    // the call sites concise while still ensuring every entry
7370    // carries an explicit, non-UNAUDITED PrecisionGuarantee that the
7371    // step-7b coverage lint can enforce.
7372    table.fill_unset_cpu_precision(crate::fused::PrecisionGuarantee::PRIMITIVE_DETERMINISTIC_CPU);
7373
7374    // Phase 7.6 step 8 — populate cost functions for every CPU
7375    // primitive registration. Every `table.register(...)` call
7376    // above defaulted to `unknown_cost`; this fill pass dispatches
7377    // each entry to its OpKind-appropriate cost-family function
7378    // (per `crate::cost::default_cost_for_op_kind`). Sites that
7379    // need a non-default cost claim should call
7380    // `table.register_full(...)` with their own `CostFn` *before*
7381    // this point — those won't be overwritten because the fill
7382    // only touches entries still bound to `unknown_cost`.
7383    //
7384    // Architecturally this is the same shape as the precision fill
7385    // above: bulk-apply the family-default at the end so the 335
7386    // CPU registration call sites stay concise, while the lint
7387    // (`precision_guarantee_lint_bit_stable_cpu_coverage_primitives`
7388    // companion: `cost_lint_per_op_kind_cpu_coverage`) enforces
7389    // that every OpKind ends up with a non-default cost function.
7390    table.fill_unset_cpu_cost(crate::cost::default_cost_for_op_kind);
7391}
7392
7393// =============================================================================
7394// Phase 7.5 — CUDA dispatch wrappers + registration
7395// =============================================================================
7396//
7397// First CUDA op through the unified binding table. Mirrors the CPU
7398// extractor + wrapper pattern but operates on `CudaStorageBytes`.
7399// Only `(AddElementwise, F32, Cuda)` is registered today; this is the
7400// "smallest possible first commit" that proves the CUDA migration
7401// pattern. Subsequent commits fan out to the rest of the op surface
7402// using the same wrapper-macro shape.
7403
7404/// Helper: extract `&CudaStorageBytes` from `&Storage`. Returns
7405/// Err if the variant isn't `BackendStorage::Cuda`.
7406#[cfg(feature = "cuda")]
7407pub(crate) fn cuda_input(s: &Storage) -> Result<&fuel_cuda_backend::CudaStorageBytes> {
7408    match &s.inner {
7409        BackendStorage::Cuda(c) => Ok(c),
7410        #[allow(unreachable_patterns)]
7411        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA input".to_string()).bt()),
7412    }
7413}
7414
7415/// Helper: extract `&mut CudaStorageBytes` from `&mut Storage`.
7416#[cfg(feature = "cuda")]
7417pub(crate) fn cuda_output(s: &mut Storage) -> Result<&mut fuel_cuda_backend::CudaStorageBytes> {
7418    match &mut s.inner {
7419        BackendStorage::Cuda(c) => Ok(c),
7420        #[allow(unreachable_patterns)]
7421        _ => Err(Error::Msg("cuda kernel wrapper called with non-CUDA output".to_string()).bt()),
7422    }
7423}
7424
7425/// Dispatch wrapper for `(OpKind::Copy, [T, T], Cuda)` — copy FROM a
7426/// CUDA source storage. The key is the SOURCE backend; the
7427/// destination is whatever the executor pre-allocated the output as
7428/// (see [`crate::pipelined::WorkItemKind::Copy`]), so the wrapper
7429/// routes on the output's variant:
7430///
7431/// - **CPU output** → D2H via `CudaStorageBytes::to_cpu_bytes`
7432///   (the realize-root path; the original sole behavior).
7433/// - **CUDA output** → device-to-device via
7434///   `CudaStorageBytes::slot_copy_to_new` (one `memcpy_dtod`).
7435///   Same-device copies are emitted by `insert_safety_copies` for
7436///   destructive ops on GPU-placed tensors and by the residency
7437///   machinery — before this routing existed, any such Copy errored
7438///   with "cpu kernel wrapper called with non-CPU output"
7439///   (residency_eviction_live caught it).
7440///
7441/// Dtype-agnostic at the byte level — one wrapper covers every dtype
7442/// registered at this key.
7443///
7444/// Phase 2 of the bridge-retirement trajectory (post-9c). Replaces
7445/// the CUDA branch of `BackendStorage::read_to_cpu_bytes` (deleted
7446/// alongside).
7447#[cfg(feature = "cuda")]
7448fn copy_from_cuda_wrapper(
7449    inputs: &[Arc<RwLock<Storage>>],
7450    outputs: &mut [Arc<RwLock<Storage>>],
7451    _layouts: &[Layout],
7452    _params: &OpParams,
7453) -> Result<()> {
7454    if inputs.len() != 1 || outputs.len() != 1 {
7455        return Err(Error::Msg(format!(
7456            "copy_from_cuda_wrapper: expected 1 input + 1 output, got {} + {}",
7457            inputs.len(),
7458            outputs.len(),
7459        ))
7460        .bt());
7461    }
7462    let in_guard = read_storage(&inputs[0])?;
7463    let cuda_src = cuda_input(&in_guard)?;
7464    let mut out_guard = write_storage(&outputs[0])?;
7465    match &mut out_guard.inner {
7466        BackendStorage::Cpu(_) => {
7467            // Step E A4b-3: the FINER cross-device D2H. The executor waited the
7468            // source node's CompletionHandle before dispatching this Copy/Move
7469            // (`pipelined::wait_producer_handle`), so the producer is done; use
7470            // `to_cpu_bytes_finer` (no whole-device `synchronize`) so the OTHER
7471            // sub-DAG's independent in-flight CUDA work is NOT force-drained.
7472            // `cuMemcpyDtoH_v2` is itself host-synchronous + legacy-stream-ordered
7473            // (see `CudaStorageBytes::to_cpu_bytes_finer`), so the read stays
7474            // byte-exact. This wrapper is reached ONLY via the executor's
7475            // Copy/Move WorkItem (it is the kernel registered at
7476            // `(OpKind::Copy, [dt,dt], Cuda)`), never standalone — so the finer
7477            // contract always holds here.
7478            let bytes = cuda_src.to_cpu_bytes_finer()?;
7479            let dst = cpu_output(&mut out_guard)?;
7480            let n = bytes.len().min(dst.len_bytes());
7481            dst.bytes_mut()[..n].copy_from_slice(&bytes[..n]);
7482            Ok(())
7483        }
7484        BackendStorage::Cuda(_) => {
7485            // Device-to-device, write-into (CapturedRun build-out, 4b-ζ):
7486            // overwrite the executor-provided output's bytes in place via
7487            // `CudaStorageBytes::copy_from_device` — no allocation, so this
7488            // branch is capture-safe (mirrors the Affine/Concat/Contiguize
7489            // conversions from 4b-α/γ) AND a strict improvement for ordinary
7490            // (non-capture) realize: the executor already hands this wrapper
7491            // a validly-sized pre-allocated output, so writing into it
7492            // produces byte-identical results with one fewer allocation.
7493            let dst = cuda_output(&mut out_guard)?;
7494            dst.copy_from_device(cuda_src)?;
7495            Ok(())
7496        }
7497        #[allow(unreachable_patterns)]
7498        other => Err(Error::Msg(format!(
7499            "copy_from_cuda_wrapper: unsupported output substrate {:?} \
7500             (CUDA sources copy to CPU or CUDA outputs only; cross-vendor \
7501             GPU transfer goes through host staging as two Copy hops)",
7502            std::mem::discriminant(other),
7503        ))
7504        .bt()),
7505    }
7506}
7507
7508/// Phase 7.5 CUDA registration — now `Op::Copy` D2H only.
7509///
7510/// **Scope (post-alpha.67, 2026-06-10):** every compute kernel has
7511/// migrated to `register_baracuda_cuda_kernels` — baracuda is the
7512/// single CUDA kernel home. The final migrations (answering
7513/// `docs/baracuda-ask-fp-gemm-reduce-to-2026-06-10.md`):
7514///
7515/// - **MatMul** (f32/f64/f16/bf16) → Phase 74 `gemm_dense` facade;
7516///   the local cuBLAS f32 path and CUTLASS bf16/f16 byte paths
7517///   retired with `byte_kernels`.
7518/// - **ReduceSumTo / ReduceMaxTo** (4 dtypes) → baracuda's
7519///   `reduce_{sum,max}_to_*` (sys symbols shipped since alpha.46).
7520/// - **CausalConv1d** → registration moved (was always
7521///   baracuda-backed via the Fuel-prepad bridge).
7522///
7523/// What stays: **Op::Copy** — D2H byte-buffer transfer, a
7524/// Fuel-specific cross-device path that lives at this layer rather
7525/// than in any kernel crate.
7526#[cfg(feature = "cuda")]
7527pub fn register_cuda_kernels(table: &mut KernelBindingTable) {
7528    use OpKind::*;
7529    let cuda = BackendId::Cuda;
7530
7531    // Op::Copy D2H — register at `(OpKind::Copy, [dt, dt], Cuda)` for
7532    // every dtype the byte-storage substrate supports. Source-backend
7533    // key (= Cuda); the wrapper produces a CPU output, copying through
7534    // `CudaStorageBytes::to_cpu_bytes`. Bridge-retirement Phase 2.
7535    let copy_dtypes = [
7536        DType::F32,
7537        DType::BF16,
7538        DType::F16,
7539        DType::U32,
7540        DType::F64,
7541        DType::U8,
7542        DType::I16,
7543        DType::I32,
7544        DType::I64,
7545        // GAP-168(c): Bool (a comparison mask) must be copyable — realize splices
7546        // `Op::Copy { target: Cpu }` to materialize a device result to host, so
7547        // WITHOUT this every realized CUDA comparison fails to dispatch. This is a
7548        // byte-level transfer via `to_cpu_bytes`, so no new kernel is required —
7549        // only the registration. Mirrors the CPU list above, which already has it.
7550        DType::Bool,
7551    ];
7552    for dt in copy_dtypes {
7553        table.register(Copy, &[dt, dt], cuda, copy_from_cuda_wrapper);
7554    }
7555}
7556
7557// =============================================================================
7558// Phase 7.5 B5+ — process-wide singleton (CapabilityRegistry + KernelBindingTable)
7559// =============================================================================
7560
7561/// Process-wide [`CapabilityRegistry`]. Initialized on first access
7562/// via [`global_registry`]; the CPU backend is auto-registered
7563/// always (universal fallback). Other backends register themselves
7564/// during their initialization or app startup.
7565///
7566/// Tests that need a private registry should construct one
7567/// directly with `CapabilityRegistry::new()` rather than touch the
7568/// global.
7569static GLOBAL_REGISTRY: OnceLock<RwLock<CapabilityRegistry>> = OnceLock::new();
7570
7571/// Process-wide topology generation counter. Bumped whenever the
7572/// set of registered backends / loaded kernels changes — so a
7573/// [`crate::topology::SystemTopology`] snapshot built at
7574/// generation N self-invalidates the next time a consumer asks for
7575/// a fresh view and the counter is N+1 or greater. See the
7576/// system-topology session prompt for the contract.
7577///
7578/// The two existing global-registry mutation sites
7579/// ([`register_backend_capabilities`] and [`extend_global_bindings`])
7580/// bump this counter unconditionally. Tests and a future device-loss
7581/// detector hook in via [`bump_topology_generation`].
7582static TOPOLOGY_GENERATION: AtomicU64 = AtomicU64::new(0);
7583
7584/// Read the current topology generation. Used by SystemTopology's
7585/// `current()` to decide whether its cached snapshot is still valid.
7586pub fn topology_generation() -> u64 {
7587    TOPOLOGY_GENERATION.load(Ordering::Acquire)
7588}
7589
7590/// Bump the topology generation counter. Every component that can
7591/// change the visible set of backends or devices should call this
7592/// after the mutation lands so consumers see a self-healing
7593/// `SystemTopology::current()` next call. Cheap (one atomic add);
7594/// `Release` ordering pairs with the `Acquire` load in
7595/// `topology_generation`.
7596pub fn bump_topology_generation() {
7597    TOPOLOGY_GENERATION.fetch_add(1, Ordering::Release);
7598}
7599
7600// =============================================================================
7601// Step E Phase C / B1 — per-device in-flight async-op counter (the load signal)
7602// =============================================================================
7603
7604/// Process-wide per-[`DeviceLocation`] in-flight async-op counter — the
7605/// "queue depth / slot utilization" load signal `06-runtime` names. The
7606/// same idiom as [`TOPOLOGY_GENERATION`]: a lazily-initialized
7607/// process-wide table the executor mutates and a runtime selector reads.
7608///
7609/// **What it counts.** The number of GPU operations the executor has
7610/// SUBMITTED but not yet observed completed, per device. It is a
7611/// *fuel-internal* count derived from the A4b async-completion handle
7612/// lifecycle ([`compiled::execute_compiled`]'s CUDA event +
7613/// `pipelined`'s eager-submitted Vulkan batches), NOT a driver query
7614/// (`cuStreamQuery` is a busy/idle bool, not a depth). One `+1` per
7615/// async submit ([`inflight_inc`]), one `-1` per completion-handle
7616/// retirement ([`inflight_dec`], fired from the handle's `Drop`).
7617///
7618/// **Narrowed by "event only where waited" (A4b open question #4).** A CUDA
7619/// node the `pipelined` executor's `WaitSet` pre-scan elides never builds a
7620/// `CudaCompletion` at all (`produce_pending` returns `Ready` directly, no
7621/// `Event`, no `inc`/`dec`) — see `compiled::execute_compiled_with_wait_hint`.
7622/// So on `OrderSource::Default`/`Optimized` realizes this counter now tracks
7623/// only WAITED CUDA work (cross-device `Copy`/`Move` producers, plus whatever
7624/// handles are still alive when sampled) rather than literally every enqueued
7625/// op — same-device-only kernels never touch it, elided or not, on the theory
7626/// that they were never individually observable before this change either
7627/// (only swept up in the old per-node drain). `OrderSource::Streaming` — the
7628/// ONLY order source the production load-aware picker
7629/// (`ranker::DeviceLoadSelector` / `ChainedSelector`'s `load_tier` leg)
7630/// actually reads THIS counter through — never elides (falls back to
7631/// event-every-node), so the picker's own live-load signal is unaffected;
7632/// the narrowing only bites a caller reading `inflight_count` for a
7633/// *different*, concurrently-running `Default`/`Optimized` realize on the
7634/// same device, which would now under-report that realize's true same-device
7635/// backlog. No production caller does this today.
7636///
7637/// **Honesty / correctness.** This is a SCHEDULING HINT, never a
7638/// correctness gate — correctness rests entirely on the A4b waits (which for
7639/// elided nodes now come from `pipelined::sync_active_cuda_devices`'s
7640/// realize-end blanket stream sync instead of a per-node `Event`). So
7641/// the atomics are [`Ordering::Relaxed`] (no memory to synchronize) and
7642/// [`inflight_dec`] is underflow-saturating: a hint that briefly
7643/// mis-reads costs at most a sub-optimal route, never a wrong result.
7644///
7645/// **CPU.** Keyed uniformly by `DeviceLocation`, but the CPU dispatch
7646/// path is synchronous and never builds an async completion handle, so
7647/// `inflight_count(DeviceLocation::Cpu)` is always 0 — no special-case
7648/// needed. A `BackendStreams` impl reports CPU as `None` (no queue
7649/// concept) regardless (see `fuel-tensor::pipelined_bridge`).
7650static DEVICE_INFLIGHT: OnceLock<RwLock<HashMap<DeviceLocation, AtomicU32>>> = OnceLock::new();
7651
7652fn device_inflight_table() -> &'static RwLock<HashMap<DeviceLocation, AtomicU32>> {
7653    DEVICE_INFLIGHT.get_or_init(|| RwLock::new(HashMap::new()))
7654}
7655
7656/// Increment the in-flight async-op count for `loc` — called when the
7657/// executor SUBMITS an async op (the same site that builds an A4b
7658/// completion handle). Cheap: a single relaxed `fetch_add` once the
7659/// per-device slot exists (the slot is created once, under a brief write
7660/// lock, on the first submit to a device). A poisoned lock is swallowed
7661/// (the counter is a hint; a poisoned table just stops tracking — never
7662/// a panic on a production path).
7663pub fn inflight_inc(loc: DeviceLocation) {
7664    let table = device_inflight_table();
7665    // Fast path: slot already exists — read lock + relaxed add, no map mutation.
7666    if let Ok(guard) = table.read()
7667        && let Some(slot) = guard.get(&loc)
7668    {
7669        slot.fetch_add(1, Ordering::Relaxed);
7670        return;
7671    }
7672    // Slow path: create the slot. `entry().or_insert` is idempotent under the
7673    // write lock, so a racing inc that took the same slow path is harmless —
7674    // whichever lands second sees the slot and adds to it.
7675    if let Ok(mut guard) = table.write() {
7676        guard
7677            .entry(loc)
7678            .or_insert_with(|| AtomicU32::new(0))
7679            .fetch_add(1, Ordering::Relaxed);
7680    }
7681}
7682
7683/// Decrement the in-flight async-op count for `loc` — called when an A4b
7684/// completion handle RETIRES (its `Drop`). Underflow-saturating: if the
7685/// slot is missing or already 0 this is a no-op, so an unexpected extra
7686/// dec can never wrap the count to `u32::MAX` and poison future
7687/// scheduling. (Under the balance invariant — every `inc` is matched by
7688/// exactly one `dec` via the handle's `Drop` — this saturation never
7689/// actually fires; it is pure defense.)
7690pub fn inflight_dec(loc: DeviceLocation) {
7691    let table = device_inflight_table();
7692    if let Ok(guard) = table.read()
7693        && let Some(slot) = guard.get(&loc)
7694    {
7695        // saturating: never wrap below 0.
7696        let _ = slot.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
7697            Some(v.saturating_sub(1))
7698        });
7699    }
7700}
7701
7702/// Read the current in-flight async-op count for `loc`. The signal a
7703/// load-aware selector consults (Step E Phase C / C2, via
7704/// `BackendStreams::pending_work_count`). 0 for a device that has never
7705/// submitted async work (including CPU, which never submits any).
7706pub fn inflight_count(loc: DeviceLocation) -> u32 {
7707    let table = device_inflight_table();
7708    table
7709        .read()
7710        .ok()
7711        .and_then(|guard| guard.get(&loc).map(|slot| slot.load(Ordering::Relaxed)))
7712        .unwrap_or(0)
7713}
7714
7715/// Process-wide [`KernelBindingTable`]. Initialized on first access
7716/// with the CPU dispatch wrappers from [`register_cpu_kernels`].
7717/// Other backends extend it when they register.
7718///
7719/// **Copy-on-write (GAP-015).** The lock guards an `Arc` *pointer*, not the
7720/// table. [`global_bindings`] clones the `Arc` and drops the read guard
7721/// before returning, so no read guard ever escapes the accessor and a
7722/// caller cannot hold one across a re-entrant region. That is what makes
7723/// the deadlock unrepresentable rather than merely unlikely: std's
7724/// `RwLock` blocks new readers once a writer queues (anti-writer-
7725/// starvation), so under the old `RwLock<KernelBindingTable>` a thread
7726/// holding a read guard that requested a *second* read waited on a lock
7727/// its own guard was blocking. Writers clone-mutate-swap.
7728static GLOBAL_BINDINGS: OnceLock<RwLock<Arc<KernelBindingTable>>> = OnceLock::new();
7729
7730/// Serializes *writers* to [`GLOBAL_BINDINGS`], and it is required for
7731/// correctness, not just tidiness.
7732///
7733/// A bare clone-mutate-swap would lose updates: two writers could clone the
7734/// same base concurrently and the second swap would silently discard the
7735/// first one's registrations. Worse, it would break
7736/// [`crate::runtime_fused_kernels::adopt_runtime_fused`], whose contract
7737/// requires its check-then-bind ("is this exact `KernelRef` already bound?"
7738/// then register) to be **atomic with respect to other writers** — two
7739/// threads racing to adopt the same region+kernel would both observe "not
7740/// bound" and both register, producing the duplicate-`KernelRef` that
7741/// `finalize` rejects.
7742///
7743/// This is deliberately a separate lock from the `RwLock` above so that the
7744/// caller-supplied extender and `finalize` run *outside* the `RwLock`; the
7745/// write guard is taken only for the pointer swap. Two consequences: a
7746/// panic in `finalize` can no longer poison the read path (the second
7747/// incident on this lock — see `runtime_fused_kernels.rs`), and an extender
7748/// that happens to call [`global_bindings`] reads a snapshot instead of
7749/// self-deadlocking. Poisoning is tolerated on both locks via
7750/// `unwrap_or_else(PoisonError::into_inner)`: a panicked writer leaves the
7751/// published table untouched, so the state a later caller observes is the
7752/// last good one, not a torn one.
7753static BINDINGS_WRITER: Mutex<()> = Mutex::new(());
7754
7755/// Initialize-once accessor for the binding-table cell. Both
7756/// [`global_bindings`] and [`extend_global_bindings`] route through this so
7757/// the init body exists exactly once.
7758fn bindings_cell() -> &'static RwLock<Arc<KernelBindingTable>> {
7759    GLOBAL_BINDINGS.get_or_init(|| {
7760        lock_trace("  BINDINGS init: begin");
7761        let mut t = KernelBindingTable::new();
7762        register_cpu_kernels(&mut t);
7763        lock_trace("  BINDINGS init: cpu done, entering optional backends");
7764        register_optional_backends(&mut t);
7765        lock_trace("  BINDINGS init: optional backends done");
7766        // Single init-boundary fail-fast: a duplicate `KernelRef` in the
7767        // hand-written static tables is a programmer error, surfaced once
7768        // here after all backends register — the never-panic replacement
7769        // for the former inline registration panic (the dynamic FKC
7770        // importer will call `finalize()?`).
7771        t.finalize()
7772            .expect("KernelBindingTable: duplicate kernel registration at init");
7773        RwLock::new(Arc::new(t))
7774    })
7775}
7776
7777fn default_cpu_caps() -> BackendCapabilities {
7778    use OpKind::*;
7779    use std::collections::HashSet;
7780    let mut op_dtype_support = HashSet::new();
7781    // The CPU coverage set must stay in lockstep with
7782    // `register_cpu_kernels`: each (op, dtype) pair registered there
7783    // is advertised here so capability-driven dispatch picks it.
7784    let f32_dt = DType::F32;
7785    for op in [
7786        AddElementwise,
7787        SubElementwise,
7788        MulElementwise,
7789        DivElementwise,
7790        ReluElementwise,
7791        NegElementwise,
7792        SqrElementwise,
7793        SqrtElementwise,
7794        RecipElementwise,
7795        AbsElementwise,
7796        TanhElementwise,
7797        ExpElementwise,
7798        LogElementwise,
7799        SinElementwise,
7800        CosElementwise,
7801        SigmoidElementwise,
7802        SiluElementwise,
7803        GeluElementwise,
7804        StepElementwise,
7805        SumReduce,
7806        MaxReduce,
7807        MinReduce,
7808        MeanReduce,
7809        MatMul,
7810        Conv2D,
7811        ConvTranspose2D,
7812        ReduceSumTo,
7813        ReduceMaxTo,
7814        FusedLinear,
7815        FlashAttn,
7816        PagedAttn,
7817        Affine,
7818        ClampElementwise,
7819        PowIElementwise,
7820        MaximumElementwise,
7821        MinimumElementwise,
7822        Concat,
7823        SoftmaxLastDim,
7824        RmsNormLastDim,
7825        LayerNormLastDim,
7826        IndexSelect,
7827        Gather,
7828        Rope,
7829        IndexAdd,
7830        ScatterAdd,
7831        QMatMul,
7832        Copy,
7833    ] {
7834        op_dtype_support.insert((op, f32_dt));
7835    }
7836    // f64 elementwise families. Reductions, matmul, conv, composed
7837    // ops, indexing, and view ops will join the f64 set as their
7838    // kernels migrate.
7839    for op in [
7840        AddElementwise,
7841        SubElementwise,
7842        MulElementwise,
7843        DivElementwise,
7844        ReluElementwise,
7845        NegElementwise,
7846        SqrElementwise,
7847        SqrtElementwise,
7848        RecipElementwise,
7849        AbsElementwise,
7850        TanhElementwise,
7851        ExpElementwise,
7852        LogElementwise,
7853        SinElementwise,
7854        CosElementwise,
7855        SigmoidElementwise,
7856        SiluElementwise,
7857        GeluElementwise,
7858        StepElementwise,
7859        MaximumElementwise,
7860        MinimumElementwise,
7861        SumReduce,
7862        MaxReduce,
7863        MinReduce,
7864        MeanReduce,
7865        MatMul,
7866        Conv2D,
7867        ConvTranspose2D,
7868        ReduceSumTo,
7869        ReduceMaxTo,
7870        FusedLinear,
7871        FlashAttn,
7872        PagedAttn,
7873    ] {
7874        op_dtype_support.insert((op, DType::F64));
7875    }
7876    // bf16 and f16 elementwise families. Reductions/matmul/conv/
7877    // composed/indexing/Rope/scalar follow as kernels migrate.
7878    let half_elementwise_ops = [
7879        AddElementwise,
7880        SubElementwise,
7881        MulElementwise,
7882        DivElementwise,
7883        MaximumElementwise,
7884        MinimumElementwise,
7885        ReluElementwise,
7886        NegElementwise,
7887        SqrElementwise,
7888        SqrtElementwise,
7889        RecipElementwise,
7890        AbsElementwise,
7891        TanhElementwise,
7892        ExpElementwise,
7893        LogElementwise,
7894        SinElementwise,
7895        CosElementwise,
7896        SigmoidElementwise,
7897        SiluElementwise,
7898        GeluElementwise,
7899        StepElementwise,
7900    ];
7901    for op in half_elementwise_ops {
7902        op_dtype_support.insert((op, DType::BF16));
7903        op_dtype_support.insert((op, DType::F16));
7904    }
7905    // bf16/f16 reductions + matmul (kernels accumulate in f32).
7906    for op in [SumReduce, MaxReduce, MinReduce, MeanReduce, MatMul] {
7907        op_dtype_support.insert((op, DType::BF16));
7908        op_dtype_support.insert((op, DType::F16));
7909    }
7910    // bf16/f16 composed/fused ops (Softmax, RmsNorm, LayerNorm,
7911    // Rope, Conv2D, ConvTranspose2D, ReduceSumTo, ReduceMaxTo,
7912    // FusedLinear, FlashAttn, PagedAttn) — all use the f32-accumulator
7913    // pattern.
7914    for op in [
7915        SoftmaxLastDim,
7916        RmsNormLastDim,
7917        LayerNormLastDim,
7918        Rope,
7919        Conv2D,
7920        ConvTranspose2D,
7921        ReduceSumTo,
7922        ReduceMaxTo,
7923        FusedLinear,
7924        FlashAttn,
7925        PagedAttn,
7926    ] {
7927        op_dtype_support.insert((op, DType::BF16));
7928        op_dtype_support.insert((op, DType::F16));
7929    }
7930    // Concat / IndexSelect / Gather are dtype-agnostic at the
7931    // byte level — advertised across the universal float/int set.
7932    for dt in [
7933        DType::F64,
7934        DType::BF16,
7935        DType::F16,
7936        DType::U32,
7937        DType::U8,
7938        DType::I16,
7939        DType::I32,
7940        DType::I64,
7941    ] {
7942        op_dtype_support.insert((Concat, dt));
7943        op_dtype_support.insert((IndexSelect, dt));
7944        op_dtype_support.insert((Gather, dt));
7945    }
7946    // IndexAdd / ScatterAdd / Affine / Clamp / PowI for f64/bf16/f16.
7947    for dt in [DType::F64, DType::BF16, DType::F16] {
7948        op_dtype_support.insert((IndexAdd, dt));
7949        op_dtype_support.insert((ScatterAdd, dt));
7950        op_dtype_support.insert((Affine, dt));
7951        op_dtype_support.insert((ClampElementwise, dt));
7952        op_dtype_support.insert((PowIElementwise, dt));
7953    }
7954    // F64 composed/fused ops (Softmax, RmsNorm, LayerNorm, Rope).
7955    for op in [SoftmaxLastDim, RmsNormLastDim, LayerNormLastDim, Rope] {
7956        op_dtype_support.insert((op, DType::F64));
7957    }
7958    // Argmax/argmin always produce U32 indices.
7959    for op in [ArgMaxDim, ArgMinDim] {
7960        op_dtype_support.insert((op, DType::U32));
7961    }
7962    // Cast advertises every target dtype that has a wrapper
7963    // registered. The capability matrix says "this backend can
7964    // produce an F64 output via Cast"; the source-side coverage
7965    // is managed inside each wrapper's match arms.
7966    for target in [DType::F32, DType::F64, DType::BF16, DType::F16] {
7967        op_dtype_support.insert((Cast, target));
7968    }
7969    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
7970        crate::ranker::default_backend_rates(BackendId::Cpu);
7971    BackendCapabilities {
7972        backend_id: BackendId::Cpu,
7973        device_location: DeviceLocation::Cpu,
7974        op_dtype_support,
7975        required_alignment: 64,
7976        access_granularity_bits: 8,
7977        transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
7978        storage_substrate: SubstrateClass::HostBytes,
7979        compute_throughput_flops_per_ns,
7980        mem_bandwidth_bytes_per_ns,
7981    }
7982}
7983
7984/// Default storage substrate for a backend, matching the storage type
7985/// each backend actually produces. Mirrors `topology::default_substrate_for`
7986/// (kept in lockstep; that one is private to `topology.rs`).
7987fn substrate_for_backend(backend: BackendId) -> SubstrateClass {
7988    match backend {
7989        BackendId::Cpu => SubstrateClass::HostBytes,
7990        BackendId::Cuda => SubstrateClass::CudaUntyped,
7991        BackendId::Vulkan => SubstrateClass::VulkanBuffer,
7992        BackendId::Metal => SubstrateClass::MetalBuffer,
7993        // `BackendId` is `#[non_exhaustive]`; a downstream variant
7994        // defaults to host bytes until it declares its own substrate.
7995        _ => SubstrateClass::HostBytes,
7996    }
7997}
7998
7999/// FKC cost unification — Part A.
8000///
8001/// Derive a [`BackendCapabilities`] for `backend` (at `device_location`)
8002/// from the kernel binding `table`. This is the general (any-backend)
8003/// analogue of `default_cpu_caps`: instead of a hand-maintained list,
8004/// it reads the backend's REGISTERED KERNELS out of the binding table
8005/// and advertises exactly the `(OpKind, DType)` pairs those kernels
8006/// cover.
8007///
8008/// The `(op, dtype)` derivation mirrors
8009/// [`crate::topology::SystemTopology`]'s `binding_op_coverage`: each
8010/// binding key carries per-operand dtypes (inputs then outputs); the
8011/// classic `(op, dtype)` shape takes the OUTPUT dtype — the last entry
8012/// in the key's dtype list. Single-dtype keys (most elementwise ops)
8013/// are unambiguous; multi-dtype keys (e.g. QMatMul `[F32, U32, F32]`)
8014/// still produce the consumer-relevant output-dtype entry.
8015///
8016/// **Why this fixes the placement cost model.** The placement cost
8017/// composer (`ranker::cost::compute_static_costs`) skips any candidate
8018/// whose backend has no `BackendCapabilities` in the registry —
8019/// leaving its `static_cost` at the default ZERO, so an uncapped GPU
8020/// candidate prices as free and can spuriously out-rank a real CPU
8021/// cost. Registering the caps this function derives makes
8022/// `capabilities_for(gpu)` return `Some`, so the GPU candidate's
8023/// FLOP/byte cost fn actually runs (see also
8024/// [`KernelBindingTable::fill_unset_cost_for_backend`], which ensures
8025/// those kernels carry a non-`unknown_cost` cost fn).
8026///
8027/// Alignment / granularity use conservative device defaults (256-byte
8028/// alignment for GPU buffers — covers CUDA's 256B and Vulkan's typical
8029/// storage-buffer alignment; byte-addressable). Transfer paths
8030/// advertise the universal `HostStaging` link back to the CPU so the
8031/// `TransferMatrix` can price GPU↔CPU crossings; richer paths (P2P,
8032/// shared memory) are a future refinement the backend can declare
8033/// explicitly. Never panics.
8034pub fn derive_backend_caps(
8035    backend: BackendId,
8036    device_location: DeviceLocation,
8037    table: &KernelBindingTable,
8038) -> BackendCapabilities {
8039    use std::collections::HashSet;
8040    let mut op_dtype_support: HashSet<(OpKind, DType)> = HashSet::new();
8041    for (op, dtypes, this_backend) in table.iter_keys() {
8042        if this_backend != backend {
8043            continue;
8044        }
8045        if let Some(&output_dt) = dtypes.last() {
8046            op_dtype_support.insert((op, output_dt));
8047        }
8048    }
8049    // GPU substrate + a universal host-staging path back to CPU so the
8050    // transfer matrix can price GPU↔CPU. CPU keeps its SameDevice self
8051    // edge (this function is general, but CPU has its own hand-tuned
8052    // `default_cpu_caps`; the CPU branch here is just defensive).
8053    let transfer_paths = if device_location == DeviceLocation::Cpu {
8054        vec![(DeviceLocation::Cpu, TransferPath::SameDevice)]
8055    } else {
8056        vec![(DeviceLocation::Cpu, TransferPath::HostStaging)]
8057    };
8058    let (required_alignment, access_granularity_bits) = match backend {
8059        BackendId::Cpu => (64, 8),
8060        // GPU buffer allocations: 256-byte alignment is a safe
8061        // superset (CUDA cudaMalloc is 256B-aligned; Vulkan storage
8062        // buffers meet this). Byte-addressable.
8063        _ => (256, 8),
8064    };
8065    let (compute_throughput_flops_per_ns, mem_bandwidth_bytes_per_ns) =
8066        crate::ranker::default_backend_rates(backend);
8067    BackendCapabilities {
8068        backend_id: backend,
8069        device_location,
8070        op_dtype_support,
8071        required_alignment,
8072        access_granularity_bits,
8073        transfer_paths,
8074        storage_substrate: substrate_for_backend(backend),
8075        compute_throughput_flops_per_ns,
8076        mem_bandwidth_bytes_per_ns,
8077    }
8078}
8079
8080/// FKC cost unification — Part A.
8081///
8082/// Register the [`BackendCapabilities`] for every non-CPU backend that
8083/// has kernels in `table` into the process-wide [`CapabilityRegistry`],
8084/// deriving each backend's caps from its registered kernels via
8085/// [`derive_backend_caps`]. Called once, at the same init boundary that
8086/// populates the global binding table (see [`global_bindings`]), AFTER
8087/// the kernels are registered — so the derivation sees the full kernel
8088/// set.
8089///
8090/// This is the registration half of Part A: it closes the gap where
8091/// only the CPU auto-registered caps, leaving CUDA/Vulkan candidates
8092/// priced at zero in the placement DP. CPU is skipped here because it
8093/// already auto-registers its hand-tuned [`default_cpu_caps`] via
8094/// [`global_registry`].
8095///
8096/// Idempotency: the registry appends and lookups pick the first match,
8097/// so this should run exactly once per backend. The single init
8098/// boundary in [`global_bindings`] guarantees that.
8099fn register_derived_gpu_caps(table: &KernelBindingTable) {
8100    use std::collections::HashSet;
8101    // Which non-CPU backends have at least one kernel registered?
8102    let gpu_backends: HashSet<BackendId> = table
8103        .iter_keys()
8104        .map(|(_, _, backend)| backend)
8105        .filter(|b| *b != BackendId::Cpu)
8106        .collect();
8107    for backend in gpu_backends {
8108        let device_location = match backend {
8109            BackendId::Cuda => DeviceLocation::Cuda { gpu_id: 0 },
8110            BackendId::Vulkan => DeviceLocation::Vulkan { gpu_id: 0 },
8111            BackendId::Metal => DeviceLocation::Metal { gpu_id: 0 },
8112            // Non-exhaustive: an unknown backend with kernels still
8113            // gets caps derived; default its device to CPU (defensive).
8114            _ => DeviceLocation::Cpu,
8115        };
8116        register_backend_capabilities(derive_backend_caps(backend, device_location, table));
8117    }
8118}
8119
8120/// Read-lock the process-wide capability registry. CPU is auto-
8121/// registered on first access; subsequent backends register
8122/// themselves via [`register_backend_capabilities`].
8123/// TEMPORARY GAP-015 DIAGNOSTIC — env-gated (`FUEL_LOCK_TRACE=1`), off by
8124/// default, zero behavior change. Names the thread and the acquisition it is
8125/// ABOUT to attempt versus the one it completed; a thread that logs "want" and
8126/// never logs "got" IS the blocked party, which is what the deadlock's stack we
8127/// cannot capture (no debugger on this box) would otherwise have told us.
8128/// Revert once the opposing lock order is pinned.
8129#[inline]
8130pub(crate) fn lock_trace(what: &str) {
8131    if std::env::var_os("FUEL_LOCK_TRACE").is_some() {
8132        eprintln!("[locktrace] t={:?} {}", std::thread::current().id(), what);
8133    }
8134}
8135
8136pub fn global_registry() -> std::sync::RwLockReadGuard<'static, CapabilityRegistry> {
8137    lock_trace("want REGISTRY.oncelock+read");
8138    let l = GLOBAL_REGISTRY.get_or_init(|| {
8139        lock_trace("  REGISTRY init: begin");
8140        let mut r = CapabilityRegistry::new();
8141        r.register(default_cpu_caps());
8142        lock_trace("  REGISTRY init: end");
8143        RwLock::new(r)
8144    });
8145    let g = l.read().unwrap();
8146    lock_trace("got  REGISTRY.read");
8147    g
8148}
8149
8150/// Add a backend's capabilities to the process-wide registry.
8151/// Typically called by each backend's init / probe path during
8152/// app startup. Idempotent for the same `(backend_id,
8153/// device_location)` is the *caller's* responsibility — the
8154/// registry happily appends duplicates and the lookup picks the
8155/// first-registered match.
8156pub fn register_backend_capabilities(caps: BackendCapabilities) {
8157    lock_trace("want REGISTRY.oncelock+WRITE (from register_backend_capabilities)");
8158    let lock = GLOBAL_REGISTRY.get_or_init(|| {
8159        lock_trace("  REGISTRY init: begin (via register_backend_capabilities)");
8160        let mut r = CapabilityRegistry::new();
8161        r.register(default_cpu_caps());
8162        lock_trace("  REGISTRY init: end");
8163        RwLock::new(r)
8164    });
8165    lock.write().unwrap().register(caps);
8166    lock_trace("got+released REGISTRY.WRITE");
8167    bump_topology_generation();
8168}
8169
8170/// Take a **snapshot** of the process-wide kernel-binding table. CPU
8171/// dispatch wrappers are auto-registered on first access. When built with
8172/// the `cuda` feature, the CUDA PTX path + the baracuda-kernels-sys path
8173/// are also auto-registered — production callers picking up the
8174/// global table see all available backends without manual init.
8175///
8176/// Returns an owned `Arc`, **not** a lock guard (GAP-015). The read guard
8177/// is acquired and released entirely inside this function, so a caller
8178/// cannot hold one across a call that might write the table — the shape
8179/// that deadlocked. Holding the returned `Arc` indefinitely is safe and
8180/// cheap; it keeps that snapshot alive, it does not block anyone.
8181///
8182/// **Snapshot semantics are a correctness property, not just a side
8183/// effect.** A caller sees one point-in-time table for as long as it holds
8184/// the `Arc`, so a kernel adopted concurrently is invisible to a pass
8185/// already in flight. That makes an optimize pass a pure function of
8186/// `(graph, table snapshot)`. Under the old guard, a pass could observe the
8187/// table mutate mid-pass and emit a plan not reproducible from its own
8188/// inputs — which would break the `base_map_hash` recipe-identity property
8189/// that Tier-2 convergence depends on. Adoption exists to affect
8190/// *subsequent* passes, so no known path wants mid-pass visibility.
8191pub fn global_bindings() -> Arc<KernelBindingTable> {
8192    lock_trace("want BINDINGS.oncelock+snapshot");
8193    let cell = bindings_cell();
8194    let snapshot = {
8195        // Poison-tolerant: nothing that can panic runs under this guard
8196        // (it wraps an `Arc::clone` and nothing else), so a poisoned flag
8197        // here can only have come from an unrelated writer that already
8198        // left the published table intact.
8199        let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8200        Arc::clone(&guard)
8201        // guard drops HERE, before returning — this is the whole fix.
8202    };
8203    lock_trace("got  BINDINGS snapshot (guard already released)");
8204    snapshot
8205}
8206
8207/// Auto-register every cargo-feature-gated backend that built. CPU is
8208/// always present (registered above); CUDA and Vulkan paths are
8209/// conditionally added. Future Metal / etc. paths hook in here.
8210fn register_optional_backends(table: &mut KernelBindingTable) {
8211    #[cfg(feature = "cuda")]
8212    {
8213        register_cuda_kernels(table);
8214        crate::baracuda_dispatch::register_baracuda_cuda_kernels(table);
8215        // FKC cost unification — Part A. The CUDA registrations above
8216        // use `table.register(...)`, defaulting cost to `unknown_cost`
8217        // (→ zero cost). Bulk-fill the OpKind-family FLOP/byte cost fn
8218        // for every CUDA entry still on the sentinel — the same pass
8219        // Vulkan already runs at the end of `register_vulkan_kernels`,
8220        // and the same `default_cost_for_op_kind` families the CPU fill
8221        // uses (op FLOPs/bytes are backend-agnostic; per-backend
8222        // throughput is a Layer-2 / Part-C refinement). Without this,
8223        // even a *capped* CUDA candidate would price at zero.
8224        table.fill_unset_cost_for_backend(BackendId::Cuda, crate::cost::default_cost_for_op_kind);
8225    }
8226    #[cfg(feature = "vulkan")]
8227    {
8228        crate::vulkan_dispatch::register_vulkan_kernels(table);
8229    }
8230
8231    // FKC cost unification — Part A. Now that every compiled-in
8232    // backend's kernels are registered (and their cost fns filled),
8233    // derive + register the `BackendCapabilities` for every non-CPU
8234    // backend that has kernels, so the placement cost model's
8235    // `capabilities_for(gpu)` returns `Some` and the GPU candidate's
8236    // cost fn actually runs (instead of being skipped → priced at
8237    // zero). CPU already auto-registers its hand-tuned caps via
8238    // `global_registry`. Touches the separate `GLOBAL_REGISTRY` lock,
8239    // not this table's — no re-entrancy.
8240    register_derived_gpu_caps(table);
8241
8242    let _ = table;
8243}
8244
8245/// Add a backend's dispatch wrappers to the process-wide binding
8246/// table. Each backend exposes a `register_*_kernels(table)`
8247/// function (see [`register_cpu_kernels`]); per-backend init paths
8248/// call this to plug their wrappers into the global table.
8249///
8250/// Copy-on-write (GAP-015): clones the current table, runs `register` on
8251/// the clone, then swaps the published `Arc`. Writers are serialized by
8252/// `BINDINGS_WRITER` rather than by the `RwLock`, which is what keeps
8253/// `adopt_runtime_fused`'s check-then-bind atomic while still leaving
8254/// readers unblocked — see that static's docs for why both properties are
8255/// required. Readers in flight keep the pre-swap snapshot; they see this
8256/// registration on their next call.
8257pub fn extend_global_bindings(register: impl FnOnce(&mut KernelBindingTable)) {
8258    let cell = bindings_cell();
8259    {
8260        // Writer-side serialization. Held across clone → extend → finalize
8261        // → swap so two concurrent writers cannot lose each other's
8262        // updates, and so a check-then-bind extender observes a base no
8263        // other writer is mutating.
8264        lock_trace("want BINDINGS.WRITER (extend_global_bindings)");
8265        let _writer = BINDINGS_WRITER.lock().unwrap_or_else(|e| e.into_inner());
8266        lock_trace("got  BINDINGS.WRITER -- cloning table, extender runs OFF the RwLock");
8267
8268        let mut next = {
8269            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
8270            (**guard).clone()
8271        };
8272        register(&mut next);
8273        lock_trace("  extender returned");
8274        // Re-validate after the extender adds its wrappers (same
8275        // never-panic fail-fast as the init boundary). This runs OUTSIDE
8276        // the `RwLock`, so the panic it can raise no longer poisons the
8277        // read path — and because `next` is thrown away on unwind, the
8278        // published table keeps its last good value instead of a torn one.
8279        next.finalize()
8280            .expect("KernelBindingTable: duplicate kernel registration after extend");
8281
8282        // Publish. The write guard covers a pointer swap and nothing else.
8283        {
8284            let mut guard = cell.write().unwrap_or_else(|e| e.into_inner());
8285            *guard = Arc::new(next);
8286        }
8287        lock_trace("released BINDINGS.WRITE (swap only)");
8288    }
8289    bump_topology_generation();
8290}
8291
8292/// The authored linear / quant-matmul FUSED kernel bundle, embedded into the
8293/// binary (the PRODUCTION `include_str!`). `register_cpu_linear_quant_fused_from_contract`
8294/// parses + lowers it and registers the MIGRATED subset FROM THE CONTRACT.
8295const FUSED_LINEAR_QUANT_CONTRACT: &str =
8296    include_str!("../kernel-contracts/fused/linear-quant.fkc.md");
8297
8298/// Register the linear / quant-matmul FUSED family — `FUSED_LINEAR` (4 dtypes,
8299/// key `[T, T, T, T]`) + `QMATMUL` (1 impl, key `[F32, U32, F32]`) +
8300/// `INPLACE_AFFINE` (4 dtypes, key `[T, T]`) + `FUSED_SOFTMAX_CROSS_ENTROPY`
8301/// (4 dtypes, key `[T, I64, F32]`) = **13 CPU `BackendImpl`s** — into the
8302/// [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true` FKC
8303/// contract (`fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md`), resolved
8304/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8305/// [`crate::fkc::CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`]). FKC is unconditional
8306/// core infrastructure, so this is the ONE registration path for these four
8307/// fused ops — every hand-written `register_fused!(FUSED_LINEAR / QMATMUL /
8308/// INPLACE_AFFINE / FUSED_SOFTMAX_CROSS_ENTROPY, …)` call is DELETED.
8309///
8310/// The bundle's fifth section `nf4_matmul` is `registrable: false` (its
8311/// `fdx.quant.family: AFFINE_BLOCK` is consumer-ahead, §6), so it never
8312/// lowers/registers and NF4's hand-written `FusedOps::NF4_MATMUL` regs (below,
8313/// unchanged) stay authoritative. QMATMUL's contract keys its weight operand the
8314/// LOGICAL dispatch dtype `U32` (the physical GGML block byte-honesty rides the
8315/// `fdx.quant: GGML_BLOCK` block), so the fanned key is `[F32, U32, F32]` —
8316/// byte-for-byte the deleted `QM_F32` reg. FSCE's `logits` fans over
8317/// `{F32,F64,BF16,F16}` (targets I64, output always F32), matching the four
8318/// deleted `FSCE_<dt>` regs exactly.
8319///
8320/// The bundle is fused-only, so `register_into`'s required binding-table
8321/// argument is a local throwaway that provably stays empty. Behavior-preserving
8322/// vs. the deleted hand-written path: identical per-dtype kernels (bound by
8323/// pointer through the link registry), the contract's bit-stable `audited: true`
8324/// precision (same shape as the deleted `*_CPU_PRECISION` consts — no downgrade),
8325/// and the real `compute_revision` hash (hand-written stamped `UNTRACKED`). Cost
8326/// stays the Judge-bootstrapped `fused_unknown_cost` sentinel ([consumer-ahead]:
8327/// the fused cost trampoline is a follow-up slice — the same posture the primitive
8328/// FKC imports take before `fill_unset_cpu_cost`).
8329fn register_cpu_linear_quant_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8330    let provider =
8331        crate::fkc::import_bundle_str(FUSED_LINEAR_QUANT_CONTRACT, &crate::fkc::CpuLinkRegistry)
8332            .expect(
8333                "authored linear-quant fused contract must import \
8334                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8335            );
8336    debug_assert!(
8337        provider.primitives.is_empty(),
8338        "linear-quant bundle declares only fused ops",
8339    );
8340    let mut table = KernelBindingTable::new();
8341    provider
8342        .register_into(&mut table, r)
8343        .expect("linear-quant fused contract must register into the fused registry");
8344}
8345
8346/// The authored norm / softmax FUSED kernel bundle, embedded into the binary
8347/// (the PRODUCTION `include_str!`). `register_cpu_norm_softmax_fused_from_contract`
8348/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8349const FUSED_NORM_SOFTMAX_CONTRACT: &str =
8350    include_str!("../kernel-contracts/fused/norm-softmax.fkc.md");
8351
8352/// Register the norm / softmax FUSED family — all EIGHT `fused_op` sections
8353/// (`SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`, key `[T, T]`;
8354/// `SOFTMAX_LAST_DIM_BACKWARD` / `LAYER_NORM_LAST_DIM_BACKWARD` /
8355/// `RMS_NORM_LAST_DIM_BACKWARD` / `REDUCE_MAX_TO_BACKWARD` / `POWI_BACKWARD`, key
8356/// `[T, T, T]`), each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU
8357/// `BackendImpl`s** — into the [`crate::fused::FusedKernelRegistry`] by IMPORTING
8358/// its `audited: true` FKC contract (`fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md`),
8359/// resolved through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8360/// [`crate::fkc::CPU_FUSED_NORM_ENTRY_POINTS`], the seam-proven 32-row table).
8361/// FKC is unconditional core infrastructure, so this is the ONE registration
8362/// path for these eight fused ops — every hand-written `register_fused!(SOFTMAX /
8363/// RMS_NORM / LAYER_NORM_LAST_DIM (+backward) / REDUCE_MAX_TO_BACKWARD /
8364/// POWI_BACKWARD, …)` call is DELETED.
8365///
8366/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8367/// kernels (bound by pointer through the link registry), the contract's
8368/// bit-stable `audited: true` precision — the **2026-07-03 maintainer flip
8369/// (CireSnave)** that relocates the `NORM_FAMILY_CPU_PRECISION` /
8370/// `REDUCE_MAX_TO_BACKWARD_CPU_PRECISION` / `POWI_BACKWARD_CPU_PRECISION`
8371/// bit-stable claim onto the contract (same author, same guarantee — no
8372/// downgrade), and the real `compute_revision` hash (hand-written stamped
8373/// `UNTRACKED`). Cost stays the Judge-bootstrapped `fused_unknown_cost` sentinel
8374/// (the fused cost trampoline is a follow-up slice).
8375fn register_cpu_norm_softmax_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8376    let provider =
8377        crate::fkc::import_bundle_str(FUSED_NORM_SOFTMAX_CONTRACT, &crate::fkc::CpuLinkRegistry)
8378            .expect(
8379                "authored norm-softmax fused contract must import \
8380                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8381            );
8382    debug_assert!(
8383        provider.primitives.is_empty(),
8384        "norm-softmax bundle declares only fused ops",
8385    );
8386    let mut table = KernelBindingTable::new();
8387    provider
8388        .register_into(&mut table, r)
8389        .expect("norm-softmax fused contract must register into the fused registry");
8390}
8391
8392/// The authored conv / RoPE / SSM FUSED kernel bundle, embedded into the binary
8393/// (the PRODUCTION `include_str!`). `register_cpu_conv_rope_fused_from_contract`
8394/// parses + lowers it and registers the FULL bundle FROM THE CONTRACT.
8395const FUSED_CONV_ROPE_CONTRACT: &str = include_str!("../kernel-contracts/fused/conv-rope.fkc.md");
8396
8397/// Register the conv / RoPE / SSM FUSED family — all SIX `fused_op` sections,
8398/// each dtype-fanned over `{F32, F64, BF16, F16}` = **32 CPU `BackendImpl`s** —
8399/// into the [`crate::fused::FusedKernelRegistry`] by IMPORTING its `audited: true`
8400/// FKC contract (`fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md`), resolved
8401/// through the production [`crate::fkc::CpuLinkRegistry`] (chaining
8402/// [`crate::fkc::CPU_FUSED_CONV_ROPE_ENTRY_POINTS`], 24 rows). FKC is
8403/// unconditional core infrastructure, so this is the ONE registration path for
8404/// these six fused ops — every hand-written `register_fused!(ROPE / CONV2D /
8405/// CONV_TRANSPOSE2D / CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` call
8406/// is DELETED.
8407///
8408/// The 24 symbol rows fan into **32 impls** (ROPE 4 + CONV2D 8 +
8409/// CONV_TRANSPOSE2D 8 + CAUSAL_CONV1D 4 + SELECTIVE_SCAN 4 + SSD_CHUNK_SCAN 4):
8410/// - CONV2D / CONV_TRANSPOSE2D mark `bias` `optional: true`, so the importer's
8411///   key-builder fans EACH per-dtype section into BOTH the no-bias key `[T, T, T]`
8412///   and the with-bias key `[T, T, T, T]` — 4 rows → 8 impls each, byte-for-byte
8413///   the deleted `CV_*_NOB` + `CV_*_BIAS` regs. **CONV_TRANSPOSE2D's contract was
8414///   WIDENED to declare the optional `bias` operand** (it previously described
8415///   only the no-bias form): production registered both tuples and the CPU
8416///   transposed-conv scatter kernel seeds the output with `bias[co]` (or `0`), so
8417///   the widening is truthful and preserves the 8-impl count the
8418///   `default_kernel_registry_step6_coverage` gate asserts.
8419/// - SELECTIVE_SCAN / SSD_CHUNK_SCAN declare a `return.bundle` multi-output
8420///   (Option C, `[y ; last_state]`), so the key-builder appends the bundle's
8421///   primary-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the 5-input
8422///   tail — each keys `[T; 6]` byte-for-byte the deleted `SS_*` / `SCS_*` regs.
8423///
8424/// Behavior-preserving vs. the deleted hand-written path: identical per-dtype
8425/// kernels (bound by pointer), the contract's bit-stable `audited: true`
8426/// precision — the **2026-07-03 maintainer flip (CireSnave)** relocating the
8427/// `ROPE_CPU_PRECISION` / `CONV2D_CPU_PRECISION` / `CONV_TRANSPOSE2D_CPU_PRECISION`
8428/// / `CAUSAL_CONV1D_CPU_PRECISION` / `SELECTIVE_SCAN_CPU_PRECISION` /
8429/// `SSD_CHUNK_SCAN_CPU_PRECISION` bit-stable claims onto the contract (same
8430/// author, same guarantee — no downgrade), and the real `compute_revision` hash
8431/// (hand-written stamped `UNTRACKED`). Cost stays the Judge-bootstrapped
8432/// `fused_unknown_cost` sentinel.
8433fn register_cpu_conv_rope_fused_from_contract(r: &mut crate::fused::FusedKernelRegistry) {
8434    let provider =
8435        crate::fkc::import_bundle_str(FUSED_CONV_ROPE_CONTRACT, &crate::fkc::CpuLinkRegistry)
8436            .expect(
8437                "authored conv-rope fused contract must import \
8438                 (embedded via include_str!, resolved through CpuLinkRegistry)",
8439            );
8440    debug_assert!(
8441        provider.primitives.is_empty(),
8442        "conv-rope bundle declares only fused ops",
8443    );
8444    let mut table = KernelBindingTable::new();
8445    provider
8446        .register_into(&mut table, r)
8447        .expect("conv-rope fused contract must register into the fused registry");
8448}
8449
8450/// Phase 7.6 step 6 — register the always-built fused-op kernels into
8451/// the [`crate::fused::FusedKernelRegistry`]. Called by
8452/// [`crate::fused::default_kernel_registry`]; kept here so the
8453/// crate-private CPU dispatch wrappers stay co-located with their
8454/// registration.
8455///
8456/// Today's coverage. Three `audited: true` FKC contracts are IMPORTED at the top
8457/// (contract-sourced, replacing the deleted hand-written `register_fused!`
8458/// entries); the attention family + deferred NF4 stay hand-written:
8459/// - **linear-quant** (`register_cpu_linear_quant_fused_from_contract`) — 13
8460///   impls: `FUSED_LINEAR` (4) + `QMATMUL` (1) + `INPLACE_AFFINE` (4) +
8461///   `FUSED_SOFTMAX_CROSS_ENTROPY` (4). The 5th section `NF4_MATMUL` is
8462///   `registrable: false` (AFFINE_BLOCK consumer-ahead) → stays hand-written.
8463/// - **norm-softmax** (`register_cpu_norm_softmax_fused_from_contract`) — 32
8464///   impls: `SOFTMAX_LAST_DIM` / `RMS_NORM_LAST_DIM` / `LAYER_NORM_LAST_DIM`
8465///   (+ their `_BACKWARD`) + `REDUCE_MAX_TO_BACKWARD` + `POWI_BACKWARD`
8466///   (8 sections × 4 dtypes).
8467/// - **conv-rope** (`register_cpu_conv_rope_fused_from_contract`) — 32 impls:
8468///   `ROPE` (4) + `CONV2D` (8, no-bias|with-bias) + `CONV_TRANSPOSE2D` (8,
8469///   no-bias|with-bias — bias operand WIDENED into the contract) +
8470///   `CAUSAL_CONV1D` (4) + `SELECTIVE_SCAN` (4, bundle) + `SSD_CHUNK_SCAN`
8471///   (4, bundle).
8472/// - hand-written below: `FLASH_ATTN` (8) + `FLASH_ATTN_BACKWARD_{Q,K,V}` (24) +
8473///   `PAGED_ATTN` (8) + `NF4_MATMUL` (3).
8474///
8475/// Total: 120 CPU BackendImpls registered across **all 24** registered
8476/// fused ops. The architecture v1.0 §05 bit-stable coverage
8477/// commitment is now compiler-enforced for the full fused-op set
8478/// (no `KNOWN_GAPS` allowlist in the step-7 lint).
8479///
8480/// Backend crates (fuel-cuda-backend, fuel-vulkan-backend) extend by
8481/// composing against the registry from their own startup paths or via
8482/// the step-9 binding-table refactor.
8483pub fn register_default_fused_kernels(r: &mut crate::fused::FusedKernelRegistry) {
8484    // NOTE: only the attention family (FLASH_ATTN / FLASH_ATTN_BACKWARD_{Q,K,V} /
8485    // PAGED_ATTN) + the deferred NF4_MATMUL keep hand-written cost fns + precision
8486    // consts here. The norm-softmax, linear-quant, and conv-rope bundles are
8487    // IMPORTED from their `audited: true` FKC contracts (below), so their cost fns
8488    // + `*_CPU_PRECISION` consts are no longer imported into this fn.
8489    use crate::fused::{
8490        ATTN_BACKWARD_CPU_PRECISION, ATTN_CPU_PRECISION, NF4_MATMUL_CPU_PRECISION,
8491        cost_attn_backward_cpu, cost_attn_cpu, cost_nf4_matmul_cpu,
8492    };
8493    use crate::register_fused;
8494    use fuel_graph::registry::FusedOps;
8495
8496    // Dtype tuples mirror the binding-table shape.
8497    // (FusedLinear's `(lhs, rhs, bias, out)` tuples are gone — FUSED_LINEAR is
8498    // now imported from the linear-quant FKC contract. Conv2D/ConvTranspose2D
8499    // `CV_*`, Softmax/RmsNorm/LayerNorm `UNARY_*`, `ROPE_*`, the norm/reduce/powi
8500    // backward `BW_*`, and the SSM `CC1D_*`/`SS_*`/`SCS_*` tuples are ALSO gone —
8501    // CONV2D/CONV_TRANSPOSE2D/ROPE + the norm-softmax bundle + CAUSAL_CONV1D/
8502    // SELECTIVE_SCAN/SSD_CHUNK_SCAN are now imported from the norm-softmax and
8503    // conv-rope FKC contracts, below.)
8504
8505    // FlashAttn: (q, k, v, [alibi], out) — no-alibi 4-tuple,
8506    // with-alibi 5-tuple. Same wrapper handles both.
8507    const FA_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32];
8508    const FA_F32_A: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8509    const FA_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64];
8510    const FA_F64_A: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8511    const FA_BF16_NOA: &[DType] = &[DType::BF16, DType::BF16, DType::BF16, DType::BF16];
8512    const FA_BF16_A: &[DType] = &[
8513        DType::BF16,
8514        DType::BF16,
8515        DType::BF16,
8516        DType::BF16,
8517        DType::BF16,
8518    ];
8519    const FA_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16];
8520    const FA_F16_A: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8521
8522    // FlashAttnBackward{Q,K,V}: (q, k, v, do, [alibi], out) —
8523    // no-alibi 5-tuple, with-alibi 6-tuple. Mirrors the binding-table
8524    // `fa_bw_no_alibi` / `fa_bw_with_alibi` key shapes.
8525    const FAB_F32_NOA: &[DType] = &[DType::F32, DType::F32, DType::F32, DType::F32, DType::F32];
8526    const FAB_F32_A: &[DType] = &[
8527        DType::F32,
8528        DType::F32,
8529        DType::F32,
8530        DType::F32,
8531        DType::F32,
8532        DType::F32,
8533    ];
8534    const FAB_F64_NOA: &[DType] = &[DType::F64, DType::F64, DType::F64, DType::F64, DType::F64];
8535    const FAB_F64_A: &[DType] = &[
8536        DType::F64,
8537        DType::F64,
8538        DType::F64,
8539        DType::F64,
8540        DType::F64,
8541        DType::F64,
8542    ];
8543    const FAB_BF16_NOA: &[DType] = &[
8544        DType::BF16,
8545        DType::BF16,
8546        DType::BF16,
8547        DType::BF16,
8548        DType::BF16,
8549    ];
8550    const FAB_BF16_A: &[DType] = &[
8551        DType::BF16,
8552        DType::BF16,
8553        DType::BF16,
8554        DType::BF16,
8555        DType::BF16,
8556        DType::BF16,
8557    ];
8558    const FAB_F16_NOA: &[DType] = &[DType::F16, DType::F16, DType::F16, DType::F16, DType::F16];
8559    const FAB_F16_A: &[DType] = &[
8560        DType::F16,
8561        DType::F16,
8562        DType::F16,
8563        DType::F16,
8564        DType::F16,
8565        DType::F16,
8566    ];
8567
8568    // PagedAttn: (q, kc, vc, bt:U32, cl:U32, [alibi], out).
8569    const PA_F32_NOA: &[DType] = &[
8570        DType::F32,
8571        DType::F32,
8572        DType::F32,
8573        DType::U32,
8574        DType::U32,
8575        DType::F32,
8576    ];
8577    const PA_F32_A: &[DType] = &[
8578        DType::F32,
8579        DType::F32,
8580        DType::F32,
8581        DType::U32,
8582        DType::U32,
8583        DType::F32,
8584        DType::F32,
8585    ];
8586    const PA_F64_NOA: &[DType] = &[
8587        DType::F64,
8588        DType::F64,
8589        DType::F64,
8590        DType::U32,
8591        DType::U32,
8592        DType::F64,
8593    ];
8594    const PA_F64_A: &[DType] = &[
8595        DType::F64,
8596        DType::F64,
8597        DType::F64,
8598        DType::U32,
8599        DType::U32,
8600        DType::F64,
8601        DType::F64,
8602    ];
8603    const PA_BF16_NOA: &[DType] = &[
8604        DType::BF16,
8605        DType::BF16,
8606        DType::BF16,
8607        DType::U32,
8608        DType::U32,
8609        DType::BF16,
8610    ];
8611    const PA_BF16_A: &[DType] = &[
8612        DType::BF16,
8613        DType::BF16,
8614        DType::BF16,
8615        DType::U32,
8616        DType::U32,
8617        DType::BF16,
8618        DType::BF16,
8619    ];
8620    const PA_F16_NOA: &[DType] = &[
8621        DType::F16,
8622        DType::F16,
8623        DType::F16,
8624        DType::U32,
8625        DType::U32,
8626        DType::F16,
8627    ];
8628    const PA_F16_A: &[DType] = &[
8629        DType::F16,
8630        DType::F16,
8631        DType::F16,
8632        DType::U32,
8633        DType::U32,
8634        DType::F16,
8635        DType::F16,
8636    ];
8637
8638    // (QMatMul's `(a:F32, w_q:U32, out:F32)` tuple is gone — QMATMUL is now
8639    // imported from the linear-quant FKC contract. The `[T, T, T]` backward-helper
8640    // `BW_*` tuples are gone too — SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD +
8641    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD are now imported from the norm-softmax
8642    // FKC contract.)
8643
8644    let cpu = BackendId::Cpu;
8645
8646    // FUSED_LINEAR (4) + QMATMUL (1) + INPLACE_AFFINE (4) +
8647    // FUSED_SOFTMAX_CROSS_ENTROPY (4) = 13 CPU impls are IMPORTED from the
8648    // `audited: true` linear-quant FKC contract (resolved through the production
8649    // CpuLinkRegistry). This REPLACES the deleted hand-written register_fused!
8650    // entries for those four fused ops. The bundle's fifth section, nf4_matmul,
8651    // is `registrable: false` (AFFINE_BLOCK consumer-ahead, §6), so NF4's
8652    // hand-written FusedOps::NF4_MATMUL regs below stay authoritative.
8653    register_cpu_linear_quant_fused_from_contract(r);
8654
8655    // SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM (+ backward) +
8656    // REDUCE_MAX_TO_BACKWARD + POWI_BACKWARD = 32 CPU impls are IMPORTED from the
8657    // `audited: true` norm-softmax FKC contract (8 sections × 4 dtypes), resolved
8658    // through the production CpuLinkRegistry (CPU_FUSED_NORM_ENTRY_POINTS). This
8659    // REPLACES the deleted hand-written register_fused! entries for those eight
8660    // fused ops.
8661    register_cpu_norm_softmax_fused_from_contract(r);
8662
8663    // ROPE + CONV2D + CONV_TRANSPOSE2D + CAUSAL_CONV1D + SELECTIVE_SCAN +
8664    // SSD_CHUNK_SCAN = 32 CPU impls are IMPORTED from the `audited: true`
8665    // conv-rope FKC contract (6 sections; CONV2D/CONV_TRANSPOSE2D fan the optional
8666    // bias into no-bias + with-bias keys → 8 impls each; SELECTIVE_SCAN/
8667    // SSD_CHUNK_SCAN key [T;6] via the return.bundle primary slot), resolved
8668    // through the production CpuLinkRegistry (CPU_FUSED_CONV_ROPE_ENTRY_POINTS).
8669    // This REPLACES the deleted hand-written register_fused! entries for those six
8670    // fused ops.
8671    register_cpu_conv_rope_fused_from_contract(r);
8672
8673    // NOTE (CapturedRun 4b-resume, 2026-07-13): a CUDA `FusedOps::ROPE`
8674    // candidate via baracuda's `rope_apply_<dt>_run` was registered here
8675    // (commit 3be28ab1) and then REVERTED — baracuda's `rope_apply` uses the
8676    // INTERLEAVED pairing `(2k, 2k+1)` (GPT-J) while Fuel's `FusedOps::ROPE`
8677    // (`Tensor::rope_with_tables`) is ROTATE-HALF `(j, j+head_dim/2)`
8678    // (Llama/HF). They compute DIFFERENT functions, so the interleaved kernel
8679    // must NOT be a candidate for the rotate-half op (a GPU numerical test
8680    // caught the divergence: `fuel_cuda_backend::baracuda::attention::
8681    // fused_rope_tests`). CUDA rope therefore runs via the correct rotate-half
8682    // primitive decompose until baracuda ships a rotate-half table-driven
8683    // `rope_apply` variant; the staged (unwired) driver + scratch cache live
8684    // in `fuel-cuda-backend` ready for that kernel.
8685
8686    // FlashAttn × 4 dtypes × {no-alibi, with-alibi}.
8687    register_fused!(
8688        r,
8689        FusedOps::FLASH_ATTN,
8690        cpu,
8691        FA_F32_NOA,
8692        flash_attn_f32_cpu_wrapper,
8693        cost = cost_attn_cpu,
8694        precision = ATTN_CPU_PRECISION
8695    );
8696    register_fused!(
8697        r,
8698        FusedOps::FLASH_ATTN,
8699        cpu,
8700        FA_F32_A,
8701        flash_attn_f32_cpu_wrapper,
8702        cost = cost_attn_cpu,
8703        precision = ATTN_CPU_PRECISION
8704    );
8705    register_fused!(
8706        r,
8707        FusedOps::FLASH_ATTN,
8708        cpu,
8709        FA_F64_NOA,
8710        flash_attn_f64_cpu_wrapper,
8711        cost = cost_attn_cpu,
8712        precision = ATTN_CPU_PRECISION
8713    );
8714    register_fused!(
8715        r,
8716        FusedOps::FLASH_ATTN,
8717        cpu,
8718        FA_F64_A,
8719        flash_attn_f64_cpu_wrapper,
8720        cost = cost_attn_cpu,
8721        precision = ATTN_CPU_PRECISION
8722    );
8723    register_fused!(
8724        r,
8725        FusedOps::FLASH_ATTN,
8726        cpu,
8727        FA_BF16_NOA,
8728        flash_attn_bf16_cpu_wrapper,
8729        cost = cost_attn_cpu,
8730        precision = ATTN_CPU_PRECISION
8731    );
8732    register_fused!(
8733        r,
8734        FusedOps::FLASH_ATTN,
8735        cpu,
8736        FA_BF16_A,
8737        flash_attn_bf16_cpu_wrapper,
8738        cost = cost_attn_cpu,
8739        precision = ATTN_CPU_PRECISION
8740    );
8741    register_fused!(
8742        r,
8743        FusedOps::FLASH_ATTN,
8744        cpu,
8745        FA_F16_NOA,
8746        flash_attn_f16_cpu_wrapper,
8747        cost = cost_attn_cpu,
8748        precision = ATTN_CPU_PRECISION
8749    );
8750    register_fused!(
8751        r,
8752        FusedOps::FLASH_ATTN,
8753        cpu,
8754        FA_F16_A,
8755        flash_attn_f16_cpu_wrapper,
8756        cost = cost_attn_cpu,
8757        precision = ATTN_CPU_PRECISION
8758    );
8759
8760    // FlashAttnBackward{Q,K,V} × 4 dtypes × {no-alibi, with-alibi}.
8761    // Reuses the binding-table dispatch wrappers — the CPU kernel
8762    // computes all three gradients each call and the wrapper persists
8763    // the one matching the OpKind; the cost model accounts for that.
8764    register_fused!(
8765        r,
8766        FusedOps::FLASH_ATTN_BACKWARD_Q,
8767        cpu,
8768        FAB_F32_NOA,
8769        flash_attn_backward_q_f32_cpu_wrapper,
8770        cost = cost_attn_backward_cpu,
8771        precision = ATTN_BACKWARD_CPU_PRECISION
8772    );
8773    register_fused!(
8774        r,
8775        FusedOps::FLASH_ATTN_BACKWARD_Q,
8776        cpu,
8777        FAB_F32_A,
8778        flash_attn_backward_q_f32_cpu_wrapper,
8779        cost = cost_attn_backward_cpu,
8780        precision = ATTN_BACKWARD_CPU_PRECISION
8781    );
8782    register_fused!(
8783        r,
8784        FusedOps::FLASH_ATTN_BACKWARD_Q,
8785        cpu,
8786        FAB_F64_NOA,
8787        flash_attn_backward_q_f64_cpu_wrapper,
8788        cost = cost_attn_backward_cpu,
8789        precision = ATTN_BACKWARD_CPU_PRECISION
8790    );
8791    register_fused!(
8792        r,
8793        FusedOps::FLASH_ATTN_BACKWARD_Q,
8794        cpu,
8795        FAB_F64_A,
8796        flash_attn_backward_q_f64_cpu_wrapper,
8797        cost = cost_attn_backward_cpu,
8798        precision = ATTN_BACKWARD_CPU_PRECISION
8799    );
8800    register_fused!(
8801        r,
8802        FusedOps::FLASH_ATTN_BACKWARD_Q,
8803        cpu,
8804        FAB_BF16_NOA,
8805        flash_attn_backward_q_bf16_cpu_wrapper,
8806        cost = cost_attn_backward_cpu,
8807        precision = ATTN_BACKWARD_CPU_PRECISION
8808    );
8809    register_fused!(
8810        r,
8811        FusedOps::FLASH_ATTN_BACKWARD_Q,
8812        cpu,
8813        FAB_BF16_A,
8814        flash_attn_backward_q_bf16_cpu_wrapper,
8815        cost = cost_attn_backward_cpu,
8816        precision = ATTN_BACKWARD_CPU_PRECISION
8817    );
8818    register_fused!(
8819        r,
8820        FusedOps::FLASH_ATTN_BACKWARD_Q,
8821        cpu,
8822        FAB_F16_NOA,
8823        flash_attn_backward_q_f16_cpu_wrapper,
8824        cost = cost_attn_backward_cpu,
8825        precision = ATTN_BACKWARD_CPU_PRECISION
8826    );
8827    register_fused!(
8828        r,
8829        FusedOps::FLASH_ATTN_BACKWARD_Q,
8830        cpu,
8831        FAB_F16_A,
8832        flash_attn_backward_q_f16_cpu_wrapper,
8833        cost = cost_attn_backward_cpu,
8834        precision = ATTN_BACKWARD_CPU_PRECISION
8835    );
8836
8837    register_fused!(
8838        r,
8839        FusedOps::FLASH_ATTN_BACKWARD_K,
8840        cpu,
8841        FAB_F32_NOA,
8842        flash_attn_backward_k_f32_cpu_wrapper,
8843        cost = cost_attn_backward_cpu,
8844        precision = ATTN_BACKWARD_CPU_PRECISION
8845    );
8846    register_fused!(
8847        r,
8848        FusedOps::FLASH_ATTN_BACKWARD_K,
8849        cpu,
8850        FAB_F32_A,
8851        flash_attn_backward_k_f32_cpu_wrapper,
8852        cost = cost_attn_backward_cpu,
8853        precision = ATTN_BACKWARD_CPU_PRECISION
8854    );
8855    register_fused!(
8856        r,
8857        FusedOps::FLASH_ATTN_BACKWARD_K,
8858        cpu,
8859        FAB_F64_NOA,
8860        flash_attn_backward_k_f64_cpu_wrapper,
8861        cost = cost_attn_backward_cpu,
8862        precision = ATTN_BACKWARD_CPU_PRECISION
8863    );
8864    register_fused!(
8865        r,
8866        FusedOps::FLASH_ATTN_BACKWARD_K,
8867        cpu,
8868        FAB_F64_A,
8869        flash_attn_backward_k_f64_cpu_wrapper,
8870        cost = cost_attn_backward_cpu,
8871        precision = ATTN_BACKWARD_CPU_PRECISION
8872    );
8873    register_fused!(
8874        r,
8875        FusedOps::FLASH_ATTN_BACKWARD_K,
8876        cpu,
8877        FAB_BF16_NOA,
8878        flash_attn_backward_k_bf16_cpu_wrapper,
8879        cost = cost_attn_backward_cpu,
8880        precision = ATTN_BACKWARD_CPU_PRECISION
8881    );
8882    register_fused!(
8883        r,
8884        FusedOps::FLASH_ATTN_BACKWARD_K,
8885        cpu,
8886        FAB_BF16_A,
8887        flash_attn_backward_k_bf16_cpu_wrapper,
8888        cost = cost_attn_backward_cpu,
8889        precision = ATTN_BACKWARD_CPU_PRECISION
8890    );
8891    register_fused!(
8892        r,
8893        FusedOps::FLASH_ATTN_BACKWARD_K,
8894        cpu,
8895        FAB_F16_NOA,
8896        flash_attn_backward_k_f16_cpu_wrapper,
8897        cost = cost_attn_backward_cpu,
8898        precision = ATTN_BACKWARD_CPU_PRECISION
8899    );
8900    register_fused!(
8901        r,
8902        FusedOps::FLASH_ATTN_BACKWARD_K,
8903        cpu,
8904        FAB_F16_A,
8905        flash_attn_backward_k_f16_cpu_wrapper,
8906        cost = cost_attn_backward_cpu,
8907        precision = ATTN_BACKWARD_CPU_PRECISION
8908    );
8909
8910    register_fused!(
8911        r,
8912        FusedOps::FLASH_ATTN_BACKWARD_V,
8913        cpu,
8914        FAB_F32_NOA,
8915        flash_attn_backward_v_f32_cpu_wrapper,
8916        cost = cost_attn_backward_cpu,
8917        precision = ATTN_BACKWARD_CPU_PRECISION
8918    );
8919    register_fused!(
8920        r,
8921        FusedOps::FLASH_ATTN_BACKWARD_V,
8922        cpu,
8923        FAB_F32_A,
8924        flash_attn_backward_v_f32_cpu_wrapper,
8925        cost = cost_attn_backward_cpu,
8926        precision = ATTN_BACKWARD_CPU_PRECISION
8927    );
8928    register_fused!(
8929        r,
8930        FusedOps::FLASH_ATTN_BACKWARD_V,
8931        cpu,
8932        FAB_F64_NOA,
8933        flash_attn_backward_v_f64_cpu_wrapper,
8934        cost = cost_attn_backward_cpu,
8935        precision = ATTN_BACKWARD_CPU_PRECISION
8936    );
8937    register_fused!(
8938        r,
8939        FusedOps::FLASH_ATTN_BACKWARD_V,
8940        cpu,
8941        FAB_F64_A,
8942        flash_attn_backward_v_f64_cpu_wrapper,
8943        cost = cost_attn_backward_cpu,
8944        precision = ATTN_BACKWARD_CPU_PRECISION
8945    );
8946    register_fused!(
8947        r,
8948        FusedOps::FLASH_ATTN_BACKWARD_V,
8949        cpu,
8950        FAB_BF16_NOA,
8951        flash_attn_backward_v_bf16_cpu_wrapper,
8952        cost = cost_attn_backward_cpu,
8953        precision = ATTN_BACKWARD_CPU_PRECISION
8954    );
8955    register_fused!(
8956        r,
8957        FusedOps::FLASH_ATTN_BACKWARD_V,
8958        cpu,
8959        FAB_BF16_A,
8960        flash_attn_backward_v_bf16_cpu_wrapper,
8961        cost = cost_attn_backward_cpu,
8962        precision = ATTN_BACKWARD_CPU_PRECISION
8963    );
8964    register_fused!(
8965        r,
8966        FusedOps::FLASH_ATTN_BACKWARD_V,
8967        cpu,
8968        FAB_F16_NOA,
8969        flash_attn_backward_v_f16_cpu_wrapper,
8970        cost = cost_attn_backward_cpu,
8971        precision = ATTN_BACKWARD_CPU_PRECISION
8972    );
8973    register_fused!(
8974        r,
8975        FusedOps::FLASH_ATTN_BACKWARD_V,
8976        cpu,
8977        FAB_F16_A,
8978        flash_attn_backward_v_f16_cpu_wrapper,
8979        cost = cost_attn_backward_cpu,
8980        precision = ATTN_BACKWARD_CPU_PRECISION
8981    );
8982
8983    // PagedAttn × 4 dtypes × {no-alibi, with-alibi}.
8984    register_fused!(
8985        r,
8986        FusedOps::PAGED_ATTN,
8987        cpu,
8988        PA_F32_NOA,
8989        paged_attn_f32_cpu_wrapper,
8990        cost = cost_attn_cpu,
8991        precision = ATTN_CPU_PRECISION
8992    );
8993    register_fused!(
8994        r,
8995        FusedOps::PAGED_ATTN,
8996        cpu,
8997        PA_F32_A,
8998        paged_attn_f32_cpu_wrapper,
8999        cost = cost_attn_cpu,
9000        precision = ATTN_CPU_PRECISION
9001    );
9002    register_fused!(
9003        r,
9004        FusedOps::PAGED_ATTN,
9005        cpu,
9006        PA_F64_NOA,
9007        paged_attn_f64_cpu_wrapper,
9008        cost = cost_attn_cpu,
9009        precision = ATTN_CPU_PRECISION
9010    );
9011    register_fused!(
9012        r,
9013        FusedOps::PAGED_ATTN,
9014        cpu,
9015        PA_F64_A,
9016        paged_attn_f64_cpu_wrapper,
9017        cost = cost_attn_cpu,
9018        precision = ATTN_CPU_PRECISION
9019    );
9020    register_fused!(
9021        r,
9022        FusedOps::PAGED_ATTN,
9023        cpu,
9024        PA_BF16_NOA,
9025        paged_attn_bf16_cpu_wrapper,
9026        cost = cost_attn_cpu,
9027        precision = ATTN_CPU_PRECISION
9028    );
9029    register_fused!(
9030        r,
9031        FusedOps::PAGED_ATTN,
9032        cpu,
9033        PA_BF16_A,
9034        paged_attn_bf16_cpu_wrapper,
9035        cost = cost_attn_cpu,
9036        precision = ATTN_CPU_PRECISION
9037    );
9038    register_fused!(
9039        r,
9040        FusedOps::PAGED_ATTN,
9041        cpu,
9042        PA_F16_NOA,
9043        paged_attn_f16_cpu_wrapper,
9044        cost = cost_attn_cpu,
9045        precision = ATTN_CPU_PRECISION
9046    );
9047    register_fused!(
9048        r,
9049        FusedOps::PAGED_ATTN,
9050        cpu,
9051        PA_F16_A,
9052        paged_attn_f16_cpu_wrapper,
9053        cost = cost_attn_cpu,
9054        precision = ATTN_CPU_PRECISION
9055    );
9056
9057    // (QMATMUL × F32 activations × U32 weights — 1 impl — is now IMPORTED from
9058    // the linear-quant FKC contract, above. The `[T, T, T]` backward helpers
9059    // SOFTMAX/LAYER/RMS_NORM_LAST_DIM_BACKWARD + REDUCE_MAX_TO_BACKWARD +
9060    // POWI_BACKWARD are IMPORTED from the norm-softmax FKC contract, and
9061    // CAUSAL_CONV1D + SELECTIVE_SCAN + SSD_CHUNK_SCAN (with INPLACE_AFFINE +
9062    // FUSED_SOFTMAX_CROSS_ENTROPY) are IMPORTED from the conv-rope / linear-quant
9063    // FKC contracts — all above.)
9064
9065    // NF4_MATMUL — four-tuple (activations T, w_packed U8, absmax
9066    // F32, out T), 3 dtype variants (T ∈ {F32, F16, BF16}).
9067    const NF4_F32: &[DType] = &[DType::F32, DType::U8, DType::F32, DType::F32];
9068    const NF4_F16: &[DType] = &[DType::F16, DType::U8, DType::F32, DType::F16];
9069    const NF4_BF16: &[DType] = &[DType::BF16, DType::U8, DType::F32, DType::BF16];
9070    register_fused!(
9071        r,
9072        FusedOps::NF4_MATMUL,
9073        cpu,
9074        NF4_F32,
9075        nf4_matmul_f32_cpu_wrapper,
9076        cost = cost_nf4_matmul_cpu,
9077        precision = NF4_MATMUL_CPU_PRECISION
9078    );
9079    register_fused!(
9080        r,
9081        FusedOps::NF4_MATMUL,
9082        cpu,
9083        NF4_F16,
9084        nf4_matmul_f16_cpu_wrapper,
9085        cost = cost_nf4_matmul_cpu,
9086        precision = NF4_MATMUL_CPU_PRECISION
9087    );
9088    register_fused!(
9089        r,
9090        FusedOps::NF4_MATMUL,
9091        cpu,
9092        NF4_BF16,
9093        nf4_matmul_bf16_cpu_wrapper,
9094        cost = cost_nf4_matmul_cpu,
9095        precision = NF4_MATMUL_CPU_PRECISION
9096    );
9097}
9098
9099#[cfg(test)]
9100mod tests {
9101    use super::*;
9102
9103    /// BORN-RED → GREEN: the `audited: true` linear-quant FUSED bundle is
9104    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9105    ///
9106    /// `register_default_fused_kernels` now imports
9107    /// `fuel-dispatch/kernel-contracts/fused/linear-quant.fkc.md` through the production
9108    /// `CpuLinkRegistry` (chaining `CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS`) INSTEAD
9109    /// of the hand-written `register_fused!(FUSED_LINEAR / QMATMUL / INPLACE_AFFINE
9110    /// / FUSED_SOFTMAX_CROSS_ENTROPY, …)` entries (deleted). Each migrated
9111    /// `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype production
9112    /// wrapper (pointer identity) AND carries the contract's REAL revision hash.
9113    ///
9114    /// **Discriminator = `revision != UNTRACKED`.** Both the deleted hand-written
9115    /// regs and the imported impls bind the SAME wrapper fn-pointer, so pointer
9116    /// identity holds in BOTH states — it is not the red discriminator. The
9117    /// hand-written `register_fused!` path stamps `KernelRevisionHash::UNTRACKED`
9118    /// (the macro default); only the FKC import path stamps the contract's real
9119    /// `compute_revision` hash. RED (before the import wired + hand-written still
9120    /// present): `lookup_by_dtypes` returns the first-registered (hand-written)
9121    /// impl → `revision == UNTRACKED` → `assert_ne!` fails. GREEN (hand-written
9122    /// deleted, import wired): the imported impl is the sole source → real
9123    /// revision → passes.
9124    ///
9125    /// Guards: the unmigrated `FLASH_ATTN` still resolves its hand-written impl
9126    /// (UNTRACKED, unchanged); the DEFERRED `NF4_MATMUL` (contract section
9127    /// `registrable: false`, `AFFINE_BLOCK` consumer-ahead) also stays
9128    /// hand-written (UNTRACKED) — proving the migration is scoped to exactly the
9129    /// four registrable sections.
9130    #[test]
9131    fn linear_quant_fused_family_migrated_to_fkc_contract() {
9132        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9133        use fuel_graph::registry::FusedOps;
9134
9135        let mut r = FusedKernelRegistry::new();
9136        register_default_fused_kernels(&mut r);
9137
9138        // --- FUSED_LINEAR: 4 dtypes, key [T, T, T, T] ---
9139        for (dt, expected) in [
9140            (
9141                DType::F32,
9142                fused_linear_f32_cpu_wrapper as *const () as usize,
9143            ),
9144            (
9145                DType::F64,
9146                fused_linear_f64_cpu_wrapper as *const () as usize,
9147            ),
9148            (
9149                DType::BF16,
9150                fused_linear_bf16_cpu_wrapper as *const () as usize,
9151            ),
9152            (
9153                DType::F16,
9154                fused_linear_f16_cpu_wrapper as *const () as usize,
9155            ),
9156        ] {
9157            let got = r
9158                .lookup_by_dtypes(FusedOps::FUSED_LINEAR, BackendId::Cpu, &[dt, dt, dt, dt])
9159                .unwrap_or_else(|| panic!("FUSED_LINEAR {dt:?} migrated impl present"));
9160            assert_eq!(
9161                got.kernel as usize, expected,
9162                "FUSED_LINEAR {dt:?} binds its exact per-dtype production wrapper",
9163            );
9164            assert_ne!(
9165                got.revision,
9166                KernelRevisionHash::UNTRACKED,
9167                "FKC-imported FUSED_LINEAR {dt:?} carries the contract's real revision \
9168                 (hand-written register_fused! stamps UNTRACKED)",
9169            );
9170        }
9171
9172        // --- QMATMUL: 1 impl, key [F32, U32, F32] (logical dispatch dtype U32) ---
9173        let qm = r
9174            .lookup_by_dtypes(
9175                FusedOps::QMATMUL,
9176                BackendId::Cpu,
9177                &[DType::F32, DType::U32, DType::F32],
9178            )
9179            .expect("QMATMUL migrated impl present at [F32, U32, F32]");
9180        assert_eq!(
9181            qm.kernel as usize,
9182            qmatmul_f32_cpu_wrapper as *const () as usize
9183        );
9184        assert_ne!(qm.revision, KernelRevisionHash::UNTRACKED);
9185
9186        // --- INPLACE_AFFINE: 4 dtypes, key [T, T] ---
9187        for (dt, expected) in [
9188            (
9189                DType::F32,
9190                inplace_affine_f32_cpu_wrapper as *const () as usize,
9191            ),
9192            (
9193                DType::F64,
9194                inplace_affine_f64_cpu_wrapper as *const () as usize,
9195            ),
9196            (
9197                DType::BF16,
9198                inplace_affine_bf16_cpu_wrapper as *const () as usize,
9199            ),
9200            (
9201                DType::F16,
9202                inplace_affine_f16_cpu_wrapper as *const () as usize,
9203            ),
9204        ] {
9205            let got = r
9206                .lookup_by_dtypes(FusedOps::INPLACE_AFFINE, BackendId::Cpu, &[dt, dt])
9207                .unwrap_or_else(|| panic!("INPLACE_AFFINE {dt:?} migrated impl present"));
9208            assert_eq!(got.kernel as usize, expected);
9209            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9210        }
9211
9212        // --- FUSED_SOFTMAX_CROSS_ENTROPY: 4 dtypes, key [T, I64, F32] ---
9213        for (dt, expected) in [
9214            (
9215                DType::F32,
9216                fused_softmax_cross_entropy_f32_cpu_wrapper as *const () as usize,
9217            ),
9218            (
9219                DType::F64,
9220                fused_softmax_cross_entropy_f64_cpu_wrapper as *const () as usize,
9221            ),
9222            (
9223                DType::BF16,
9224                fused_softmax_cross_entropy_bf16_cpu_wrapper as *const () as usize,
9225            ),
9226            (
9227                DType::F16,
9228                fused_softmax_cross_entropy_f16_cpu_wrapper as *const () as usize,
9229            ),
9230        ] {
9231            let got = r
9232                .lookup_by_dtypes(
9233                    FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
9234                    BackendId::Cpu,
9235                    &[dt, DType::I64, DType::F32],
9236                )
9237                .unwrap_or_else(|| panic!("FSCE {dt:?} migrated impl present"));
9238            assert_eq!(got.kernel as usize, expected);
9239            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9240        }
9241
9242        // --- GUARD: unmigrated FLASH_ATTN still resolves its hand-written impl ---
9243        let fa = r
9244            .lookup_by_dtypes(
9245                FusedOps::FLASH_ATTN,
9246                BackendId::Cpu,
9247                &[DType::F32, DType::F32, DType::F32, DType::F32],
9248            )
9249            .expect("FLASH_ATTN hand-written impl present");
9250        assert_eq!(
9251            fa.kernel as usize,
9252            flash_attn_f32_cpu_wrapper as *const () as usize
9253        );
9254        assert_eq!(
9255            fa.revision,
9256            KernelRevisionHash::UNTRACKED,
9257            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9258        );
9259
9260        // --- GUARD: DEFERRED NF4_MATMUL stays hand-written (registrable: false) ---
9261        let nf4 = r
9262            .lookup_by_dtypes(
9263                FusedOps::NF4_MATMUL,
9264                BackendId::Cpu,
9265                &[DType::F32, DType::U8, DType::F32, DType::F32],
9266            )
9267            .expect("NF4_MATMUL hand-written impl present (AFFINE_BLOCK deferred)");
9268        assert_eq!(
9269            nf4.kernel as usize,
9270            nf4_matmul_f32_cpu_wrapper as *const () as usize
9271        );
9272        assert_eq!(
9273            nf4.revision,
9274            KernelRevisionHash::UNTRACKED,
9275            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9276        );
9277    }
9278
9279    /// BORN-RED → GREEN: the `audited: true` norm/softmax FUSED bundle is
9280    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9281    ///
9282    /// `register_default_fused_kernels` now imports
9283    /// `fuel-dispatch/kernel-contracts/fused/norm-softmax.fkc.md` through the production
9284    /// `CpuLinkRegistry` (chaining `CPU_FUSED_NORM_ENTRY_POINTS`) INSTEAD of the
9285    /// hand-written `register_fused!(SOFTMAX / RMS_NORM / LAYER_NORM_LAST_DIM
9286    /// (+backward) / REDUCE_MAX_TO_BACKWARD / POWI_BACKWARD, …)` entries (deleted).
9287    /// Each migrated `(FusedOpId, Cpu, dtypes)` resolves to the EXACT per-dtype
9288    /// production wrapper (pointer identity) AND carries the contract's REAL
9289    /// revision hash.
9290    ///
9291    /// **Discriminator = `revision != UNTRACKED`.** Both paths bind the SAME
9292    /// wrapper fn-pointer, so pointer identity holds in BOTH states — it is not
9293    /// the red discriminator. The hand-written `register_fused!` path stamps
9294    /// `KernelRevisionHash::UNTRACKED`; only the FKC import path stamps the
9295    /// contract's real `compute_revision`. RED (before wired + hand-written still
9296    /// present): `lookup_by_dtypes` returns the hand-written impl → `UNTRACKED` →
9297    /// `assert_ne!` fails. GREEN (deleted + imported): real revision → passes.
9298    ///
9299    /// Also asserts the **2026-07-03 maintainer flip rode through**: the imported
9300    /// precision is bit-stable (`bit_stable_on_same_hardware == true`), NOT the
9301    /// `UNAUDITED` an `audited: false` contract would have lowered to — the whole
9302    /// point of the flip.
9303    #[test]
9304    fn norm_softmax_fused_family_migrated_to_fkc_contract() {
9305        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9306        use fuel_graph::registry::FusedOps;
9307
9308        let mut r = FusedKernelRegistry::new();
9309        register_default_fused_kernels(&mut r);
9310
9311        // FORWARD (key [T, T]) — Softmax / RmsNorm / LayerNorm last-dim.
9312        let forward = [
9313            (
9314                FusedOps::SOFTMAX_LAST_DIM,
9315                [
9316                    softmax_last_dim_f32_cpu_wrapper as *const () as usize,
9317                    softmax_last_dim_f64_cpu_wrapper as *const () as usize,
9318                    softmax_last_dim_bf16_cpu_wrapper as *const () as usize,
9319                    softmax_last_dim_f16_cpu_wrapper as *const () as usize,
9320                ],
9321            ),
9322            (
9323                FusedOps::RMS_NORM_LAST_DIM,
9324                [
9325                    rms_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9326                    rms_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9327                    rms_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9328                    rms_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9329                ],
9330            ),
9331            (
9332                FusedOps::LAYER_NORM_LAST_DIM,
9333                [
9334                    layer_norm_last_dim_f32_cpu_wrapper as *const () as usize,
9335                    layer_norm_last_dim_f64_cpu_wrapper as *const () as usize,
9336                    layer_norm_last_dim_bf16_cpu_wrapper as *const () as usize,
9337                    layer_norm_last_dim_f16_cpu_wrapper as *const () as usize,
9338                ],
9339            ),
9340        ];
9341        for (id, wrappers) in forward {
9342            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9343                .iter()
9344                .zip(wrappers)
9345            {
9346                let got = r
9347                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt])
9348                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9349                assert_eq!(
9350                    got.kernel as usize, expected,
9351                    "{id:?} {dt:?} binds its exact per-dtype production wrapper",
9352                );
9353                assert_ne!(
9354                    got.revision,
9355                    KernelRevisionHash::UNTRACKED,
9356                    "FKC-imported {id:?} {dt:?} carries the contract's real revision \
9357                     (hand-written register_fused! stamps UNTRACKED)",
9358                );
9359                assert!(
9360                    got.precision.bit_stable_on_same_hardware,
9361                    "the 2026-07-03 audited:true flip rode through as bit-stable for {id:?} {dt:?} \
9362                     (NOT the UNAUDITED an audited:false contract would have lowered to)",
9363                );
9364            }
9365        }
9366
9367        // BACKWARD (key [T, T, T]) — Softmax / Layer / Rms backward +
9368        // ReduceMaxTo / PowI backward (backward-of-primitive helpers).
9369        let backward = [
9370            (
9371                FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
9372                [
9373                    softmax_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9374                    softmax_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9375                    softmax_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9376                    softmax_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9377                ],
9378            ),
9379            (
9380                FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
9381                [
9382                    layer_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9383                    layer_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9384                    layer_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9385                    layer_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9386                ],
9387            ),
9388            (
9389                FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
9390                [
9391                    rms_norm_last_dim_backward_f32_cpu_wrapper as *const () as usize,
9392                    rms_norm_last_dim_backward_f64_cpu_wrapper as *const () as usize,
9393                    rms_norm_last_dim_backward_bf16_cpu_wrapper as *const () as usize,
9394                    rms_norm_last_dim_backward_f16_cpu_wrapper as *const () as usize,
9395                ],
9396            ),
9397            (
9398                FusedOps::REDUCE_MAX_TO_BACKWARD,
9399                [
9400                    reduce_max_to_backward_f32_cpu_wrapper as *const () as usize,
9401                    reduce_max_to_backward_f64_cpu_wrapper as *const () as usize,
9402                    reduce_max_to_backward_bf16_cpu_wrapper as *const () as usize,
9403                    reduce_max_to_backward_f16_cpu_wrapper as *const () as usize,
9404                ],
9405            ),
9406            (
9407                FusedOps::POWI_BACKWARD,
9408                [
9409                    powi_backward_f32_cpu_wrapper as *const () as usize,
9410                    powi_backward_f64_cpu_wrapper as *const () as usize,
9411                    powi_backward_bf16_cpu_wrapper as *const () as usize,
9412                    powi_backward_f16_cpu_wrapper as *const () as usize,
9413                ],
9414            ),
9415        ];
9416        for (id, wrappers) in backward {
9417            for (dt, expected) in [DType::F32, DType::F64, DType::BF16, DType::F16]
9418                .iter()
9419                .zip(wrappers)
9420            {
9421                let got = r
9422                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt, *dt, *dt])
9423                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9424                assert_eq!(got.kernel as usize, expected);
9425                assert_ne!(
9426                    got.revision,
9427                    KernelRevisionHash::UNTRACKED,
9428                    "FKC-imported {id:?} {dt:?} carries the contract's real revision",
9429                );
9430                assert!(
9431                    got.precision.bit_stable_on_same_hardware,
9432                    "the audited:true flip rode through as bit-stable for {id:?} {dt:?}",
9433                );
9434            }
9435        }
9436
9437        // GUARD: an UNMIGRATED fused op (FLASH_ATTN) still resolves its
9438        // hand-written impl at UNTRACKED — proves the migration is scoped.
9439        let fa = r
9440            .lookup_by_dtypes(
9441                FusedOps::FLASH_ATTN,
9442                BackendId::Cpu,
9443                &[DType::F32, DType::F32, DType::F32, DType::F32],
9444            )
9445            .expect("FLASH_ATTN hand-written impl present");
9446        assert_eq!(
9447            fa.revision,
9448            KernelRevisionHash::UNTRACKED,
9449            "unmigrated FLASH_ATTN keeps its hand-written UNTRACKED revision",
9450        );
9451    }
9452
9453    /// BORN-RED → GREEN: the `audited: true` conv / RoPE / SSM FUSED bundle is
9454    /// PRODUCTION-migrated into the `FusedKernelRegistry` FROM its FKC contract.
9455    ///
9456    /// `register_default_fused_kernels` now imports
9457    /// `fuel-dispatch/kernel-contracts/fused/conv-rope.fkc.md` through the production
9458    /// `CpuLinkRegistry` (chaining `CPU_FUSED_CONV_ROPE_ENTRY_POINTS`) INSTEAD of
9459    /// the hand-written `register_fused!(ROPE / CONV2D / CONV_TRANSPOSE2D /
9460    /// CAUSAL_CONV1D / SELECTIVE_SCAN / SSD_CHUNK_SCAN, …)` entries (deleted). Each
9461    /// migrated impl binds the EXACT per-dtype wrapper (pointer identity) AND
9462    /// carries the contract's REAL revision (hand-written stamps UNTRACKED — the
9463    /// red discriminator). Covers the two multi-key cases:
9464    /// - CONV2D / CONV_TRANSPOSE2D fan the optional bias into BOTH the no-bias
9465    ///   key `[T, T, T]` and the with-bias key `[T, T, T, T]` (8 impls each);
9466    /// - SELECTIVE_SCAN / SSD_CHUNK_SCAN key `[T; 6]` (5 inputs + the bundle's
9467    ///   primary output slot).
9468    ///
9469    /// Also asserts the **2026-07-03 maintainer flip rode through** as bit-stable
9470    /// (NOT `UNAUDITED`).
9471    #[test]
9472    fn conv_rope_fused_family_migrated_to_fkc_contract() {
9473        use crate::fused::{FusedKernelRegistry, KernelRevisionHash};
9474        use fuel_graph::registry::FusedOps;
9475
9476        let mut r = FusedKernelRegistry::new();
9477        register_default_fused_kernels(&mut r);
9478
9479        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
9480
9481        // ROPE — key [T, T, T, T] (x, cos, sin + out).
9482        let rope_w = [
9483            rope_f32_cpu_wrapper as *const () as usize,
9484            rope_f64_cpu_wrapper as *const () as usize,
9485            rope_bf16_cpu_wrapper as *const () as usize,
9486            rope_f16_cpu_wrapper as *const () as usize,
9487        ];
9488        for (dt, expected) in dts.iter().zip(rope_w) {
9489            let got = r
9490                .lookup_by_dtypes(FusedOps::ROPE, BackendId::Cpu, &[*dt, *dt, *dt, *dt])
9491                .unwrap_or_else(|| panic!("ROPE {dt:?} migrated impl present"));
9492            assert_eq!(got.kernel as usize, expected);
9493            assert_ne!(
9494                got.revision,
9495                KernelRevisionHash::UNTRACKED,
9496                "ROPE {dt:?} real revision"
9497            );
9498            assert!(
9499                got.precision.bit_stable_on_same_hardware,
9500                "audited:true rode through bit-stable for ROPE {dt:?}",
9501            );
9502        }
9503
9504        // CONV2D / CONV_TRANSPOSE2D — optional bias ⇒ BOTH no-bias [T,T,T] and
9505        // with-bias [T,T,T,T] resolve the SAME per-dtype wrapper (8 impls each).
9506        let conv = [
9507            (
9508                FusedOps::CONV2D,
9509                [
9510                    conv2d_f32_cpu_wrapper as *const () as usize,
9511                    conv2d_f64_cpu_wrapper as *const () as usize,
9512                    conv2d_bf16_cpu_wrapper as *const () as usize,
9513                    conv2d_f16_cpu_wrapper as *const () as usize,
9514                ],
9515            ),
9516            (
9517                FusedOps::CONV_TRANSPOSE2D,
9518                [
9519                    conv_transpose2d_f32_cpu_wrapper as *const () as usize,
9520                    conv_transpose2d_f64_cpu_wrapper as *const () as usize,
9521                    conv_transpose2d_bf16_cpu_wrapper as *const () as usize,
9522                    conv_transpose2d_f16_cpu_wrapper as *const () as usize,
9523                ],
9524            ),
9525        ];
9526        for (id, wrappers) in conv {
9527            for (dt, expected) in dts.iter().zip(wrappers) {
9528                for key in [vec![*dt, *dt, *dt], vec![*dt, *dt, *dt, *dt]] {
9529                    let with_bias = key.len() == 4;
9530                    let got = r
9531                        .lookup_by_dtypes(id, BackendId::Cpu, &key)
9532                        .unwrap_or_else(|| {
9533                            panic!("{id:?} {dt:?} (with_bias={with_bias}) migrated impl present")
9534                        });
9535                    assert_eq!(got.kernel as usize, expected);
9536                    assert_ne!(
9537                        got.revision,
9538                        KernelRevisionHash::UNTRACKED,
9539                        "{id:?} {dt:?} (with_bias={with_bias}) real revision",
9540                    );
9541                    assert!(
9542                        got.precision.bit_stable_on_same_hardware,
9543                        "audited:true rode through bit-stable for {id:?} {dt:?} (with_bias={with_bias})",
9544                    );
9545                }
9546            }
9547        }
9548
9549        // CAUSAL_CONV1D — key [T, T, T, T] (x, weight, bias + out).
9550        let cc1d_w = [
9551            causal_conv1d_f32_cpu_wrapper as *const () as usize,
9552            causal_conv1d_f64_cpu_wrapper as *const () as usize,
9553            causal_conv1d_bf16_cpu_wrapper as *const () as usize,
9554            causal_conv1d_f16_cpu_wrapper as *const () as usize,
9555        ];
9556        for (dt, expected) in dts.iter().zip(cc1d_w) {
9557            let got = r
9558                .lookup_by_dtypes(
9559                    FusedOps::CAUSAL_CONV1D,
9560                    BackendId::Cpu,
9561                    &[*dt, *dt, *dt, *dt],
9562                )
9563                .unwrap_or_else(|| panic!("CAUSAL_CONV1D {dt:?} migrated impl present"));
9564            assert_eq!(got.kernel as usize, expected);
9565            assert_ne!(got.revision, KernelRevisionHash::UNTRACKED);
9566            assert!(got.precision.bit_stable_on_same_hardware);
9567        }
9568
9569        // SELECTIVE_SCAN / SSD_CHUNK_SCAN — return.bundle ⇒ key [T; 6]
9570        // (5 inputs + the bundled primary output slot).
9571        let scan = [
9572            (
9573                FusedOps::SELECTIVE_SCAN,
9574                [
9575                    selective_scan_f32_cpu_wrapper as *const () as usize,
9576                    selective_scan_f64_cpu_wrapper as *const () as usize,
9577                    selective_scan_bf16_cpu_wrapper as *const () as usize,
9578                    selective_scan_f16_cpu_wrapper as *const () as usize,
9579                ],
9580            ),
9581            (
9582                FusedOps::SSD_CHUNK_SCAN,
9583                [
9584                    ssd_chunk_scan_f32_cpu_wrapper as *const () as usize,
9585                    ssd_chunk_scan_f64_cpu_wrapper as *const () as usize,
9586                    ssd_chunk_scan_bf16_cpu_wrapper as *const () as usize,
9587                    ssd_chunk_scan_f16_cpu_wrapper as *const () as usize,
9588                ],
9589            ),
9590        ];
9591        for (id, wrappers) in scan {
9592            for (dt, expected) in dts.iter().zip(wrappers) {
9593                let got = r
9594                    .lookup_by_dtypes(id, BackendId::Cpu, &[*dt; 6])
9595                    .unwrap_or_else(|| panic!("{id:?} {dt:?} migrated impl present"));
9596                assert_eq!(got.kernel as usize, expected);
9597                assert_ne!(
9598                    got.revision,
9599                    KernelRevisionHash::UNTRACKED,
9600                    "{id:?} {dt:?} real revision",
9601                );
9602                assert!(
9603                    got.precision.bit_stable_on_same_hardware,
9604                    "audited:true rode through bit-stable for {id:?} {dt:?}",
9605                );
9606            }
9607        }
9608
9609        // GUARD: the DEFERRED NF4_MATMUL (linear-quant `registrable: false`) stays
9610        // hand-written at UNTRACKED — proves this migration is scoped to conv-rope.
9611        let nf4 = r
9612            .lookup_by_dtypes(
9613                FusedOps::NF4_MATMUL,
9614                BackendId::Cpu,
9615                &[DType::F32, DType::U8, DType::F32, DType::F32],
9616            )
9617            .expect("NF4_MATMUL hand-written impl present");
9618        assert_eq!(
9619            nf4.revision,
9620            KernelRevisionHash::UNTRACKED,
9621            "deferred NF4_MATMUL keeps its hand-written UNTRACKED revision",
9622        );
9623    }
9624
9625    /// Phase 7.6 step 7b — the architecture v1.0 §05 "always-built
9626    /// backend bit-stable coverage commitment" lint, extended from
9627    /// the fused-op half (step 7a) to **primitive** ops.
9628    ///
9629    /// Every `OpKind` variant that flows through `KernelBindingTable`
9630    /// MUST have at least one CPU registration with
9631    /// `precision.bit_stable_on_same_hardware == true`. The
9632    /// architecture's correctness anchor is the always-built backend
9633    /// giving every downstream consumer a deterministic
9634    /// implementation to fall back on, so cross-backend equivalence
9635    /// tests have a fixed reference.
9636    ///
9637    /// The lint runs as a unit test so violations surface in CI
9638    /// rather than at runtime. Adding a new `OpKind` variant without
9639    /// a matching CPU registration fails this test immediately.
9640    ///
9641    /// As of step 7b (2026-05-11), every `OpKind` variant has CPU
9642    /// coverage via `register_cpu_kernels` + the
9643    /// `fill_unset_cpu_precision` pass at the end of that function.
9644    /// `KNOWN_GAPS` is empty.
9645    ///
9646    /// Note on the OpKind enumeration: there's no `strum`-style
9647    /// derive on the enum, so the test hardcodes the variant list.
9648    /// New OpKind variants must be added here AND to a matching
9649    /// CPU registration in `register_cpu_kernels`. The two-touch
9650    /// requirement is a feature — the test becomes the canonical
9651    /// "all kernels accounted for" reference.
9652    #[test]
9653    /// FKC-CLAUSE: FKC-4.8-0001 — the always-built coverage commitment. This is a
9654    /// CORPUS property (>=1 bit-stable CPU kernel per primitive op), not a
9655    /// per-contract rule, so it raises no FkcError and is invisible to the
9656    /// variant-anchored gate in tests/fkc_clause_coverage.rs.
9657    fn precision_guarantee_lint_bit_stable_cpu_coverage_primitives() {
9658        use fuel_ir::dispatch::OpKind;
9659        use fuel_ir::probe::BackendId;
9660
9661        // Allowlist for OpKind variants that *can't* have bit-stable
9662        // CPU coverage. Empty as of step 7b (every variant routes
9663        // through deterministic kernels). New entries must come with
9664        // a documented reason — and a follow-up to close the gap.
9665        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
9666
9667        // The canonical list of every OpKind variant. Mirrors the
9668        // enum definition in fuel-core-types::dispatch. Adding a
9669        // new variant requires adding it here; that's the explicit
9670        // contract for "this OpKind exists and is expected to have
9671        // CPU coverage."
9672        const ALL_OP_KINDS: &[OpKind] = &[
9673            OpKind::MatMul,
9674            OpKind::AddElementwise,
9675            OpKind::SubElementwise,
9676            OpKind::MulElementwise,
9677            OpKind::DivElementwise,
9678            OpKind::ReluElementwise,
9679            OpKind::NegElementwise,
9680            OpKind::SqrElementwise,
9681            OpKind::SqrtElementwise,
9682            OpKind::RecipElementwise,
9683            OpKind::AbsElementwise,
9684            OpKind::TanhElementwise,
9685            OpKind::ExpElementwise,
9686            OpKind::LogElementwise,
9687            OpKind::SinElementwise,
9688            OpKind::CosElementwise,
9689            OpKind::SigmoidElementwise,
9690            OpKind::SiluElementwise,
9691            OpKind::GeluTanhElementwise,
9692            OpKind::StepElementwise,
9693            OpKind::SumReduce,
9694            OpKind::MaxReduce,
9695            OpKind::MinReduce,
9696            OpKind::MeanReduce,
9697            OpKind::Cast,
9698            OpKind::Conv2D,
9699            OpKind::ConvTranspose2D,
9700            OpKind::ReduceSumTo,
9701            OpKind::ReduceMaxTo,
9702            OpKind::FusedLinear,
9703            OpKind::FlashAttn,
9704            OpKind::PagedAttn,
9705            OpKind::Affine,
9706            OpKind::ClampElementwise,
9707            OpKind::PowIElementwise,
9708            OpKind::MaximumElementwise,
9709            OpKind::MinimumElementwise,
9710            OpKind::EqualElementwise,
9711            OpKind::NotEqualElementwise,
9712            OpKind::LessElementwise,
9713            OpKind::LessEqualElementwise,
9714            OpKind::GreaterElementwise,
9715            OpKind::GreaterEqualElementwise,
9716            OpKind::Where,
9717            OpKind::FloorElementwise,
9718            OpKind::CeilElementwise,
9719            OpKind::RoundElementwise,
9720            OpKind::SignElementwise,
9721            OpKind::ErfElementwise,
9722            OpKind::GeluElementwise,
9723            OpKind::PowElementwise,
9724            OpKind::RsqrtElementwise,
9725            OpKind::RemElementwise,
9726            OpKind::Flip,
9727            OpKind::Roll,
9728            OpKind::CumSum,
9729            OpKind::Pad,
9730            OpKind::PadBackward,
9731            OpKind::Triu,
9732            OpKind::Tril,
9733            OpKind::LogSoftmaxLastDim,
9734            OpKind::LogSoftmaxLastDimBackward,
9735            OpKind::MaskedFill,
9736            OpKind::Concat,
9737            OpKind::SoftmaxLastDim,
9738            OpKind::SoftmaxLastDimBackward,
9739            OpKind::RmsNormLastDim,
9740            OpKind::RmsNormLastDimBackward,
9741            OpKind::LayerNormLastDim,
9742            OpKind::LayerNormLastDimBackward,
9743            OpKind::ReduceMaxToBackward,
9744            OpKind::IndexSelect,
9745            OpKind::Gather,
9746            OpKind::Rope,
9747            OpKind::IndexAdd,
9748            OpKind::ScatterAdd,
9749            OpKind::ArgMaxDim,
9750            OpKind::ArgMinDim,
9751            OpKind::QMatMul,
9752            OpKind::Copy,
9753            OpKind::FusedSoftmaxCrossEntropy,
9754            OpKind::CausalConv1d,
9755            OpKind::SelectiveScan,
9756            OpKind::SsdChunkScan,
9757            OpKind::Nf4Matmul,
9758        ];
9759
9760        // Populate the binding table the same way the production
9761        // path does — via register_cpu_kernels including the
9762        // fill_unset_cpu_precision pass at the end.
9763        let mut table = KernelBindingTable::new();
9764        register_cpu_kernels(&mut table);
9765
9766        // Group all CPU registrations by OpKind so we can check
9767        // coverage per variant.
9768        let mut by_op_kind: std::collections::HashMap<
9769            OpKind,
9770            Vec<crate::fused::PrecisionGuarantee>,
9771        > = std::collections::HashMap::new();
9772        for (op, _dtypes, backend, precision) in table.iter_precision() {
9773            if backend == BackendId::Cpu {
9774                by_op_kind.entry(op).or_default().push(precision);
9775            }
9776        }
9777
9778        let mut failures: Vec<String> = Vec::new();
9779        let mut covered = 0usize;
9780        let mut allowlisted = 0usize;
9781
9782        for op in ALL_OP_KINDS.iter().copied() {
9783            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
9784                allowlisted += 1;
9785                if by_op_kind.contains_key(&op) {
9786                    failures.push(format!(
9787                        "OpKind::{op:?} is on the KNOWN_GAPS allowlist but DOES \
9788                         have a CPU registration now. Reason given was: \
9789                         {reason:?}. Remove the allowlist entry to enable the \
9790                         bit-stable lint for this op.",
9791                    ));
9792                }
9793                continue;
9794            }
9795            let precisions = by_op_kind.get(&op);
9796            let has_bit_stable_cpu =
9797                precisions.is_some_and(|ps| ps.iter().any(|p| p.bit_stable_on_same_hardware));
9798            if has_bit_stable_cpu {
9799                covered += 1;
9800            } else {
9801                failures.push(format!(
9802                    "OpKind::{op:?} has no bit-stable CPU registration. \
9803                     Architecture v1.0 §05 requires the always-built backend \
9804                     (fuel-cpu-backend) to provide at least one \
9805                     `bit_stable_on_same_hardware: true` kernel per primitive \
9806                     op. Either add a CPU registration in \
9807                     register_cpu_kernels (the fill_unset_cpu_precision pass \
9808                     at the end will upgrade it to PRIMITIVE_DETERMINISTIC_CPU \
9809                     automatically), or add a line to KNOWN_GAPS above with a \
9810                     documented reason.",
9811                ));
9812            }
9813        }
9814
9815        assert!(
9816            failures.is_empty(),
9817            "Architecture v1.0 bit-stable CPU coverage lint (primitives) failed:\n{}",
9818            failures.join("\n"),
9819        );
9820        assert_eq!(
9821            allowlisted, 0,
9822            "KNOWN_GAPS allowlist is empty by design; saw {allowlisted} allowlisted",
9823        );
9824        // Sanity: ALL_OP_KINDS should match the production
9825        // registration set. If a new variant lands in the enum
9826        // without being added here, the test's value is reduced —
9827        // catch the case by asserting the count.
9828        assert!(covered > 0, "lint covered 0 OpKinds — table appears empty",);
9829        // Sanity: every OpKind we enumerated should have ≥1 dtype
9830        // registration. The fill pass should have populated
9831        // precision for each.
9832        for op in ALL_OP_KINDS {
9833            assert!(
9834                by_op_kind.contains_key(op),
9835                "OpKind::{op:?} has no CPU registration at all — either add \
9836                 one in register_cpu_kernels or document the gap in \
9837                 KNOWN_GAPS.",
9838            );
9839        }
9840    }
9841
9842    /// Phase 7.6 step 8 — the "every OpKind has a real cost
9843    /// function" coverage lint. Companion to step 7b's bit-stable
9844    /// precision lint; the architectural commitment is that every
9845    /// primitive op carries both a `PrecisionGuarantee` and a
9846    /// `CostFn` (Layer-1 cost model: FLOPs + bandwidth + launch
9847    /// overhead) by the time the binding table is consulted at
9848    /// dispatch time.
9849    ///
9850    /// The lint runs as a unit test. Violations surface in CI
9851    /// rather than at runtime — a new `OpKind` variant without a
9852    /// matching arm in
9853    /// [`crate::cost::default_cost_for_op_kind`] fails this test
9854    /// immediately because the fill pass leaves it bound to
9855    /// `unknown_cost`.
9856    ///
9857    /// `KNOWN_GAPS` is empty as of step 8 (2026-05-12). Adding a
9858    /// future variant without immediate cost coverage needs a
9859    /// documented allowlist entry AND a follow-up.
9860    #[test]
9861    fn cost_lint_per_op_kind_cpu_coverage() {
9862        use fuel_ir::dispatch::OpKind;
9863        use fuel_ir::probe::BackendId;
9864
9865        const KNOWN_GAPS: &[(OpKind, &str)] = &[];
9866
9867        const ALL_OP_KINDS: &[OpKind] = &[
9868            OpKind::MatMul,
9869            OpKind::AddElementwise,
9870            OpKind::SubElementwise,
9871            OpKind::MulElementwise,
9872            OpKind::DivElementwise,
9873            OpKind::ReluElementwise,
9874            OpKind::NegElementwise,
9875            OpKind::SqrElementwise,
9876            OpKind::SqrtElementwise,
9877            OpKind::RecipElementwise,
9878            OpKind::AbsElementwise,
9879            OpKind::TanhElementwise,
9880            OpKind::ExpElementwise,
9881            OpKind::LogElementwise,
9882            OpKind::SinElementwise,
9883            OpKind::CosElementwise,
9884            OpKind::SigmoidElementwise,
9885            OpKind::SiluElementwise,
9886            OpKind::GeluTanhElementwise,
9887            OpKind::StepElementwise,
9888            OpKind::SumReduce,
9889            OpKind::MaxReduce,
9890            OpKind::MinReduce,
9891            OpKind::MeanReduce,
9892            OpKind::Cast,
9893            OpKind::Conv2D,
9894            OpKind::ConvTranspose2D,
9895            OpKind::ReduceSumTo,
9896            OpKind::ReduceMaxTo,
9897            OpKind::FusedLinear,
9898            OpKind::FlashAttn,
9899            OpKind::PagedAttn,
9900            OpKind::Affine,
9901            OpKind::ClampElementwise,
9902            OpKind::PowIElementwise,
9903            OpKind::MaximumElementwise,
9904            OpKind::MinimumElementwise,
9905            OpKind::EqualElementwise,
9906            OpKind::NotEqualElementwise,
9907            OpKind::LessElementwise,
9908            OpKind::LessEqualElementwise,
9909            OpKind::GreaterElementwise,
9910            OpKind::GreaterEqualElementwise,
9911            OpKind::Where,
9912            OpKind::FloorElementwise,
9913            OpKind::CeilElementwise,
9914            OpKind::RoundElementwise,
9915            OpKind::SignElementwise,
9916            OpKind::ErfElementwise,
9917            OpKind::GeluElementwise,
9918            OpKind::PowElementwise,
9919            OpKind::RsqrtElementwise,
9920            OpKind::RemElementwise,
9921            OpKind::Flip,
9922            OpKind::Roll,
9923            OpKind::CumSum,
9924            OpKind::Pad,
9925            OpKind::PadBackward,
9926            OpKind::Triu,
9927            OpKind::Tril,
9928            OpKind::LogSoftmaxLastDim,
9929            OpKind::LogSoftmaxLastDimBackward,
9930            OpKind::MaskedFill,
9931            OpKind::Concat,
9932            OpKind::SoftmaxLastDim,
9933            OpKind::SoftmaxLastDimBackward,
9934            OpKind::RmsNormLastDim,
9935            OpKind::RmsNormLastDimBackward,
9936            OpKind::LayerNormLastDim,
9937            OpKind::LayerNormLastDimBackward,
9938            OpKind::ReduceMaxToBackward,
9939            OpKind::IndexSelect,
9940            OpKind::Gather,
9941            OpKind::Rope,
9942            OpKind::IndexAdd,
9943            OpKind::ScatterAdd,
9944            OpKind::ArgMaxDim,
9945            OpKind::ArgMinDim,
9946            OpKind::QMatMul,
9947            OpKind::Copy,
9948            OpKind::FusedSoftmaxCrossEntropy,
9949            OpKind::CausalConv1d,
9950            OpKind::SelectiveScan,
9951            OpKind::SsdChunkScan,
9952            OpKind::Nf4Matmul,
9953        ];
9954
9955        let mut table = KernelBindingTable::new();
9956        register_cpu_kernels(&mut table);
9957
9958        // Group cost functions by OpKind for CPU registrations.
9959        let mut by_op_kind: std::collections::HashMap<OpKind, Vec<crate::kernel::CostFn>> =
9960            std::collections::HashMap::new();
9961        for (op, _dtypes, backend, cost) in table.iter_cost() {
9962            if backend == BackendId::Cpu {
9963                by_op_kind.entry(op).or_default().push(cost);
9964            }
9965        }
9966
9967        let unknown_sentinel = crate::kernel::unknown_cost as *const () as usize;
9968
9969        let mut failures: Vec<String> = Vec::new();
9970        for op in ALL_OP_KINDS.iter().copied() {
9971            if let Some((_, reason)) = KNOWN_GAPS.iter().find(|(g, _)| *g == op) {
9972                if let Some(costs) = by_op_kind.get(&op) {
9973                    let has_real = costs.iter().any(|c| (*c as usize) != unknown_sentinel);
9974                    if has_real {
9975                        failures.push(format!(
9976                            "OpKind::{op:?} is on the cost-lint KNOWN_GAPS \
9977                             allowlist but DOES have a non-default cost fn \
9978                             now. Reason given: {reason:?}. Remove the \
9979                             allowlist entry.",
9980                        ));
9981                    }
9982                }
9983                continue;
9984            }
9985            let costs = by_op_kind.get(&op);
9986            let has_real_cost =
9987                costs.is_some_and(|cs| cs.iter().any(|c| (*c as usize) != unknown_sentinel));
9988            if !has_real_cost {
9989                failures.push(format!(
9990                    "OpKind::{op:?} has no non-default cost fn in any CPU \
9991                     registration. Either add an arm in \
9992                     `crate::cost::default_cost_for_op_kind` (the \
9993                     fill_unset_cpu_cost pass at the end of \
9994                     register_cpu_kernels will pick it up automatically), \
9995                     register an explicit cost via `register_full(...)`, \
9996                     or add a line to KNOWN_GAPS with a documented reason.",
9997                ));
9998            }
9999        }
10000
10001        assert!(
10002            failures.is_empty(),
10003            "Phase 7.6 step 8 cost-coverage lint failed:\n{}",
10004            failures.join("\n"),
10005        );
10006        // Sanity: every OpKind we enumerated should have ≥1 CPU
10007        // registration (asserted separately by the step-7b lint,
10008        // but re-checked here for symmetry).
10009        for op in ALL_OP_KINDS {
10010            assert!(
10011                by_op_kind.contains_key(op),
10012                "OpKind::{op:?} has no CPU registration at all.",
10013            );
10014        }
10015    }
10016
10017    fn cpu_caps() -> BackendCapabilities {
10018        BackendCapabilities {
10019            backend_id: BackendId::Cpu,
10020            device_location: DeviceLocation::Cpu,
10021            op_dtype_support: [
10022                (OpKind::MatMul, DType::F32),
10023                (OpKind::MatMul, DType::F64),
10024                (OpKind::AddElementwise, DType::F32),
10025                (OpKind::AddElementwise, DType::F64),
10026            ]
10027            .into_iter()
10028            .collect(),
10029            required_alignment: 64,
10030            access_granularity_bits: 8,
10031            transfer_paths: vec![(DeviceLocation::Cpu, TransferPath::SameDevice)],
10032            storage_substrate: SubstrateClass::HostBytes,
10033            compute_throughput_flops_per_ns: 1.0,
10034            mem_bandwidth_bytes_per_ns: 4.0,
10035        }
10036    }
10037
10038    fn cuda_caps() -> BackendCapabilities {
10039        BackendCapabilities {
10040            backend_id: BackendId::Cuda,
10041            device_location: DeviceLocation::Cuda { gpu_id: 0 },
10042            op_dtype_support: [
10043                (OpKind::MatMul, DType::F32),
10044                (OpKind::MatMul, DType::F16),
10045                (OpKind::AddElementwise, DType::F32),
10046            ]
10047            .into_iter()
10048            .collect(),
10049            required_alignment: 256,
10050            access_granularity_bits: 8,
10051            transfer_paths: vec![
10052                (DeviceLocation::Cpu, TransferPath::DeviceCopy),
10053                (DeviceLocation::Cuda { gpu_id: 0 }, TransferPath::SameDevice),
10054            ],
10055            storage_substrate: SubstrateClass::CudaUntyped,
10056            compute_throughput_flops_per_ns: 30.0,
10057            mem_bandwidth_bytes_per_ns: 40.0,
10058        }
10059    }
10060
10061    /// Smoke: empty registry has nothing.
10062    #[test]
10063    fn empty_registry() {
10064        let r = CapabilityRegistry::new();
10065        assert!(r.backends().is_empty());
10066        let result = r.find_backend_for(OpKind::MatMul, DType::F32);
10067        assert!(result.is_err());
10068    }
10069
10070    /// Find_backends returns matching backends in registration order.
10071    #[test]
10072    fn find_backends_order_preserved() {
10073        let mut r = CapabilityRegistry::new();
10074        r.register(cuda_caps()); // registered first → wins ties
10075        r.register(cpu_caps());
10076
10077        let backends = r.find_backends(OpKind::MatMul, DType::F32);
10078        assert_eq!(backends.len(), 2);
10079        assert_eq!(backends[0].backend_id, BackendId::Cuda);
10080        assert_eq!(backends[1].backend_id, BackendId::Cpu);
10081    }
10082
10083    /// Find_backend_for picks first match.
10084    #[test]
10085    fn find_backend_first_wins() {
10086        let mut r = CapabilityRegistry::new();
10087        r.register(cuda_caps());
10088        r.register(cpu_caps());
10089
10090        let chosen = r.find_backend_for(OpKind::MatMul, DType::F32).unwrap();
10091        assert_eq!(chosen.backend_id, BackendId::Cuda);
10092    }
10093
10094    /// CPU-only registry falls back when GPU dtypes aren't supported.
10095    #[test]
10096    fn cpu_handles_what_gpu_doesnt() {
10097        let mut r = CapabilityRegistry::new();
10098        r.register(cuda_caps());
10099        r.register(cpu_caps());
10100
10101        // CUDA doesn't support F64; CPU does.
10102        let chosen = r.find_backend_for(OpKind::MatMul, DType::F64).unwrap();
10103        assert_eq!(chosen.backend_id, BackendId::Cpu);
10104    }
10105
10106    /// Unsupported (op, dtype) returns NoBackendForOp with diagnostic data.
10107    #[test]
10108    fn unsupported_combo_errors_with_diagnostic() {
10109        let mut r = CapabilityRegistry::new();
10110        r.register(cpu_caps());
10111
10112        let err = match r.find_backend_for(OpKind::MatMul, DType::BF16) {
10113            Ok(_) => panic!("expected error"),
10114            Err(e) => e,
10115        };
10116        let msg = err.to_string();
10117        assert!(
10118            msg.contains("MatMul") || msg.contains("matmul"),
10119            "error names op: {msg}"
10120        );
10121        assert!(msg.contains("BF16"), "error names dtype: {msg}");
10122        assert!(msg.contains("Cpu"), "error names available backends: {msg}");
10123    }
10124
10125    /// TransferMatrix preserves SameDevice for src == dst always.
10126    #[test]
10127    fn transfer_matrix_same_device() {
10128        let r = CapabilityRegistry::new();
10129        let m = r.build_transfer_matrix();
10130        assert_eq!(
10131            m.path(DeviceLocation::Cpu, DeviceLocation::Cpu),
10132            Some(TransferPath::SameDevice)
10133        );
10134    }
10135
10136    /// TransferMatrix entries from registered backends.
10137    #[test]
10138    fn transfer_matrix_built_from_caps() {
10139        let mut r = CapabilityRegistry::new();
10140        r.register(cuda_caps());
10141        let m = r.build_transfer_matrix();
10142
10143        // CUDA → CPU is DeviceCopy (advertised).
10144        assert_eq!(
10145            m.path(DeviceLocation::Cuda { gpu_id: 0 }, DeviceLocation::Cpu),
10146            Some(TransferPath::DeviceCopy)
10147        );
10148    }
10149
10150    /// path_or_staging falls back to HostStaging for unadvertised
10151    /// pairs.
10152    #[test]
10153    fn host_staging_fallback() {
10154        let r = CapabilityRegistry::new();
10155        let m = r.build_transfer_matrix();
10156        // No CPU registered; CPU→Cuda has no entry; staging fallback.
10157        assert_eq!(
10158            m.path_or_staging(DeviceLocation::Cpu, DeviceLocation::Cuda { gpu_id: 0 }),
10159            TransferPath::HostStaging
10160        );
10161    }
10162
10163    /// resolve_target_backend picks the first registered backend
10164    /// supporting (op, dtype).
10165    #[test]
10166    fn resolve_picks_first_match() {
10167        let mut r = CapabilityRegistry::new();
10168        r.register(cuda_caps());
10169        r.register(cpu_caps());
10170        assert_eq!(
10171            resolve_target_backend(&r, OpKind::MatMul, DType::F32).unwrap(),
10172            BackendId::Cuda
10173        );
10174    }
10175
10176    /// resolve_target_backend falls back to CPU for dtypes GPU doesn't support.
10177    #[test]
10178    fn resolve_falls_back_to_cpu() {
10179        let mut r = CapabilityRegistry::new();
10180        r.register(cuda_caps());
10181        r.register(cpu_caps());
10182        assert_eq!(
10183            resolve_target_backend(&r, OpKind::MatMul, DType::F64).unwrap(),
10184            BackendId::Cpu
10185        );
10186    }
10187
10188    /// resolve_target_backend errors with NoBackendForOp on miss.
10189    #[test]
10190    fn resolve_errors_on_unsupported() {
10191        let mut r = CapabilityRegistry::new();
10192        r.register(cpu_caps());
10193        let result = resolve_target_backend(&r, OpKind::MatMul, DType::BF16);
10194        assert!(result.is_err());
10195    }
10196
10197    /// Residency-aware resolver picks a backend with input-local
10198    /// residency when available.
10199    #[test]
10200    fn resolve_residency_aware_prefers_local() {
10201        let mut r = CapabilityRegistry::new();
10202        // CUDA registered first (would normally win ties for f32).
10203        r.register(cuda_caps());
10204        r.register(cpu_caps());
10205
10206        // Inputs live on CPU; residency-aware prefers CPU even
10207        // though CUDA also supports (MatMul, F32).
10208        let chosen = resolve_target_backend_residency_aware(
10209            &r,
10210            OpKind::MatMul,
10211            DType::F32,
10212            &[DeviceLocation::Cpu],
10213        )
10214        .unwrap();
10215        assert_eq!(chosen, BackendId::Cpu);
10216    }
10217
10218    /// Residency-aware falls back to first match when no residency
10219    /// match exists.
10220    #[test]
10221    fn resolve_residency_aware_no_local_falls_back() {
10222        let mut r = CapabilityRegistry::new();
10223        r.register(cuda_caps());
10224        r.register(cpu_caps());
10225
10226        // Inputs on a Vulkan device — no candidate matches; falls
10227        // back to first (CUDA).
10228        let chosen = resolve_target_backend_residency_aware(
10229            &r,
10230            OpKind::MatMul,
10231            DType::F32,
10232            &[DeviceLocation::Vulkan { gpu_id: 0 }],
10233        )
10234        .unwrap();
10235        assert_eq!(chosen, BackendId::Cuda);
10236    }
10237
10238    // -------- B5: kernel binding table + CPU dispatch wrappers --------
10239
10240    /// Smoke: register_cpu_kernels populates the binding table.
10241    #[test]
10242    fn register_cpu_kernels_populates_table() {
10243        let mut table = KernelBindingTable::new();
10244        assert!(table.is_empty());
10245        register_cpu_kernels(&mut table);
10246        assert!(!table.is_empty());
10247        // The (AddElementwise, F32, Cpu) binding lands.
10248        let _kernel = table
10249            .lookup(
10250                OpKind::AddElementwise,
10251                &[DType::F32, DType::F32, DType::F32],
10252                BackendId::Cpu,
10253            )
10254            .expect("registered");
10255    }
10256
10257    /// FIRST PRODUCTION FKC CONSUMER (born-red gate). `global_bindings()`
10258    /// registers the CPU elementwise-binary family (8 ops × 4 dtypes = 32
10259    /// bindings) FROM ITS KERNEL CONTRACT
10260    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-binary.fkc.md`) — the sole
10261    /// registration path, now that the hand-written `table.register(...)`
10262    /// calls for this family are DELETED.
10263    ///
10264    /// For each of the 32 `(op, [dt; 3], Cpu)` keys this asserts:
10265    ///  - the binding resolves to the EXACT production wrapper fn-pointer
10266    ///    (behavior-preserving execution),
10267    ///  - `kernel_source == "portable-cpu"` — the contract's provenance tag
10268    ///    (the deleted hand-written path stamped `""`). THIS is the
10269    ///    discriminator that makes the test go red without the import wired:
10270    ///    with the hand-written binary regs removed and the import absent, the
10271    ///    family is simply missing from `global_bindings()`,
10272    ///  - caps stay empty (`strided_input == false`) and the contract's
10273    ///    audited bit-stable precision claim rode through.
10274    #[test]
10275    fn global_bindings_registers_binary_family_from_contract() {
10276        let table = global_bindings();
10277
10278        // (op, [f32, f64, bf16, f16] production wrappers) for all 8 ops.
10279        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10280            (
10281                OpKind::AddElementwise,
10282                [
10283                    add_elementwise_f32_cpu_wrapper,
10284                    add_elementwise_f64_cpu_wrapper,
10285                    add_elementwise_bf16_cpu_wrapper,
10286                    add_elementwise_f16_cpu_wrapper,
10287                ],
10288            ),
10289            (
10290                OpKind::SubElementwise,
10291                [
10292                    sub_elementwise_f32_cpu_wrapper,
10293                    sub_elementwise_f64_cpu_wrapper,
10294                    sub_elementwise_bf16_cpu_wrapper,
10295                    sub_elementwise_f16_cpu_wrapper,
10296                ],
10297            ),
10298            (
10299                OpKind::MulElementwise,
10300                [
10301                    mul_elementwise_f32_cpu_wrapper,
10302                    mul_elementwise_f64_cpu_wrapper,
10303                    mul_elementwise_bf16_cpu_wrapper,
10304                    mul_elementwise_f16_cpu_wrapper,
10305                ],
10306            ),
10307            (
10308                OpKind::DivElementwise,
10309                [
10310                    div_elementwise_f32_cpu_wrapper,
10311                    div_elementwise_f64_cpu_wrapper,
10312                    div_elementwise_bf16_cpu_wrapper,
10313                    div_elementwise_f16_cpu_wrapper,
10314                ],
10315            ),
10316            (
10317                OpKind::MaximumElementwise,
10318                [
10319                    maximum_elementwise_f32_cpu_wrapper,
10320                    maximum_elementwise_f64_cpu_wrapper,
10321                    maximum_elementwise_bf16_cpu_wrapper,
10322                    maximum_elementwise_f16_cpu_wrapper,
10323                ],
10324            ),
10325            (
10326                OpKind::MinimumElementwise,
10327                [
10328                    minimum_elementwise_f32_cpu_wrapper,
10329                    minimum_elementwise_f64_cpu_wrapper,
10330                    minimum_elementwise_bf16_cpu_wrapper,
10331                    minimum_elementwise_f16_cpu_wrapper,
10332                ],
10333            ),
10334            (
10335                OpKind::PowElementwise,
10336                [
10337                    pow_elementwise_f32_cpu_wrapper,
10338                    pow_elementwise_f64_cpu_wrapper,
10339                    pow_elementwise_bf16_cpu_wrapper,
10340                    pow_elementwise_f16_cpu_wrapper,
10341                ],
10342            ),
10343            (
10344                OpKind::RemElementwise,
10345                [
10346                    rem_elementwise_f32_cpu_wrapper,
10347                    rem_elementwise_f64_cpu_wrapper,
10348                    rem_elementwise_bf16_cpu_wrapper,
10349                    rem_elementwise_f16_cpu_wrapper,
10350                ],
10351            ),
10352        ];
10353        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10354
10355        let mut checked = 0usize;
10356        for (op, wrappers) in families {
10357            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10358                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
10359                let entry = alts
10360                    .iter()
10361                    .find(|e| e.kernel as usize == *expected as usize)
10362                    .unwrap_or_else(|| {
10363                        panic!(
10364                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10365                             FROM the elementwise-binary contract in global_bindings() \
10366                             — found {} alternative(s) with sources {:?}",
10367                            alts.len(),
10368                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10369                        )
10370                    });
10371                assert_eq!(
10372                    entry.kernel_source, "portable-cpu",
10373                    "{op:?}/{dt:?}: binary family must be contract-sourced \
10374                     (kernel_source=\"portable-cpu\"); got {:?}",
10375                    entry.kernel_source,
10376                );
10377                assert!(
10378                    !entry.caps.strided_input,
10379                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10380                );
10381                assert!(
10382                    entry.precision.bit_stable_on_same_hardware,
10383                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10384                );
10385                checked += 1;
10386            }
10387        }
10388        assert_eq!(checked, 32, "all 8 ops × 4 dtypes checked");
10389    }
10390
10391    /// FKC born-red gate for the CPU affine / clamp / powi family.
10392    /// `global_bindings()` registers the out-of-place scalar-param family
10393    /// (affine/clamp/powi × 4 dtypes + powi_backward × 4 = 16 bindings) FROM
10394    /// ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/affine-clamp-powi.fkc.md`)
10395    /// — the sole registration path, now that the hand-written
10396    /// `table.register(...)` calls are DELETED. Asserts each (op, dtype, Cpu)
10397    /// key resolves to the EXACT production wrapper fn-pointer, is
10398    /// contract-sourced (`kernel_source == "portable-cpu"`), caps stayed
10399    /// contiguous-only, and the audited bit-stable precision claim rode through.
10400    #[test]
10401    fn global_bindings_registers_affine_clamp_powi_family_from_contract() {
10402        let table = global_bindings();
10403        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10404
10405        // Single-input forward ops → key [dt, dt].
10406        let forward: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10407            (
10408                OpKind::Affine,
10409                [
10410                    affine_f32_cpu_wrapper,
10411                    affine_f64_cpu_wrapper,
10412                    affine_bf16_cpu_wrapper,
10413                    affine_f16_cpu_wrapper,
10414                ],
10415            ),
10416            (
10417                OpKind::ClampElementwise,
10418                [
10419                    clamp_elementwise_f32_cpu_wrapper,
10420                    clamp_f64_cpu_wrapper,
10421                    clamp_bf16_cpu_wrapper,
10422                    clamp_f16_cpu_wrapper,
10423                ],
10424            ),
10425            (
10426                OpKind::PowIElementwise,
10427                [
10428                    powi_elementwise_f32_cpu_wrapper,
10429                    powi_f64_cpu_wrapper,
10430                    powi_bf16_cpu_wrapper,
10431                    powi_f16_cpu_wrapper,
10432                ],
10433            ),
10434        ];
10435
10436        let mut checked = 0usize;
10437        for (op, wrappers) in forward {
10438            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10439                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10440                let entry = alts
10441                    .iter()
10442                    .find(|e| e.kernel as usize == *expected as usize)
10443                    .unwrap_or_else(|| {
10444                        panic!(
10445                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10446                             FROM the affine-clamp-powi contract in global_bindings() \
10447                             — found {} alternative(s) with sources {:?}",
10448                            alts.len(),
10449                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10450                        )
10451                    });
10452                assert_eq!(
10453                    entry.kernel_source, "portable-cpu",
10454                    "{op:?}/{dt:?}: family must be contract-sourced \
10455                     (kernel_source=\"portable-cpu\"); got {:?}",
10456                    entry.kernel_source,
10457                );
10458                assert!(
10459                    !entry.caps.strided_input,
10460                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10461                );
10462                assert!(
10463                    entry.precision.bit_stable_on_same_hardware,
10464                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10465                );
10466                checked += 1;
10467            }
10468        }
10469
10470        // Two-input backward op → key [dt, dt, dt].
10471        let bw: [crate::kernel::KernelRef; 4] = [
10472            powi_backward_f32_cpu_wrapper,
10473            powi_backward_f64_cpu_wrapper,
10474            powi_backward_bf16_cpu_wrapper,
10475            powi_backward_f16_cpu_wrapper,
10476        ];
10477        for (dt, expected) in dts.iter().zip(bw.iter()) {
10478            let alts = table.lookup_alternatives(
10479                OpKind::PowIElementwiseBackward,
10480                &[*dt, *dt, *dt],
10481                BackendId::Cpu,
10482            );
10483            let entry = alts
10484                .iter()
10485                .find(|e| e.kernel as usize == *expected as usize)
10486                .unwrap_or_else(|| {
10487                    panic!(
10488                        "PowIElementwiseBackward/{dt:?}/Cpu: the production wrapper must \
10489                         be bound FROM the affine-clamp-powi contract in global_bindings() \
10490                         — found {} alternative(s) with sources {:?}",
10491                        alts.len(),
10492                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10493                    )
10494                });
10495            assert_eq!(
10496                entry.kernel_source, "portable-cpu",
10497                "PowIElementwiseBackward/{dt:?}: must be contract-sourced; got {:?}",
10498                entry.kernel_source,
10499            );
10500            assert!(
10501                !entry.caps.strided_input,
10502                "PowIElementwiseBackward/{dt:?}: caps preserved (contiguous-only)",
10503            );
10504            assert!(
10505                entry.precision.bit_stable_on_same_hardware,
10506                "PowIElementwiseBackward/{dt:?}: the audited bit-stable claim rode through",
10507            );
10508            checked += 1;
10509        }
10510
10511        assert_eq!(checked, 16, "3 forward ops × 4 dtypes + powi_backward × 4");
10512    }
10513
10514    /// FKC born-red gate for the CPU elementwise-unary family.
10515    /// `global_bindings()` registers the elementwise-unary family (22 ops × 4
10516    /// dtypes = 88 bindings) FROM ITS KERNEL CONTRACT
10517    /// (`fuel-dispatch/kernel-contracts/cpu/elementwise-unary.fkc.md`) via the §3.4
10518    /// multi-dtype fan-out (each per-op section declares a BASE `entry_point`
10519    /// that the importer expands to `<base>_<dtype>`) — the sole registration
10520    /// path, now that the hand-written `table.register(...)` calls are DELETED.
10521    /// Asserts each (op, dtype, Cpu) key resolves to the EXACT production
10522    /// wrapper fn-pointer, is contract-sourced (`kernel_source == "portable-cpu"`),
10523    /// caps stayed contiguous-only, and the audited bit-stable precision claim
10524    /// rode through. `gelu_tanh` (`GeluTanhElementwise`, base `gelu_tanh`) and `gelu`
10525    /// (`GeluElementwise`, base `gelu`) are kept DISTINCT.
10526    #[test]
10527    fn global_bindings_registers_unary_family_from_contract() {
10528        let table = global_bindings();
10529        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10530
10531        // (op, [f32, f64, bf16, f16] production wrappers) for all 22 ops.
10532        let families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10533            (
10534                OpKind::ReluElementwise,
10535                [
10536                    relu_elementwise_f32_cpu_wrapper,
10537                    relu_elementwise_f64_cpu_wrapper,
10538                    relu_elementwise_bf16_cpu_wrapper,
10539                    relu_elementwise_f16_cpu_wrapper,
10540                ],
10541            ),
10542            (
10543                OpKind::NegElementwise,
10544                [
10545                    neg_elementwise_f32_cpu_wrapper,
10546                    neg_elementwise_f64_cpu_wrapper,
10547                    neg_elementwise_bf16_cpu_wrapper,
10548                    neg_elementwise_f16_cpu_wrapper,
10549                ],
10550            ),
10551            (
10552                OpKind::SqrElementwise,
10553                [
10554                    sqr_elementwise_f32_cpu_wrapper,
10555                    sqr_elementwise_f64_cpu_wrapper,
10556                    sqr_elementwise_bf16_cpu_wrapper,
10557                    sqr_elementwise_f16_cpu_wrapper,
10558                ],
10559            ),
10560            (
10561                OpKind::SqrtElementwise,
10562                [
10563                    sqrt_elementwise_f32_cpu_wrapper,
10564                    sqrt_elementwise_f64_cpu_wrapper,
10565                    sqrt_elementwise_bf16_cpu_wrapper,
10566                    sqrt_elementwise_f16_cpu_wrapper,
10567                ],
10568            ),
10569            (
10570                OpKind::RecipElementwise,
10571                [
10572                    recip_elementwise_f32_cpu_wrapper,
10573                    recip_elementwise_f64_cpu_wrapper,
10574                    recip_elementwise_bf16_cpu_wrapper,
10575                    recip_elementwise_f16_cpu_wrapper,
10576                ],
10577            ),
10578            (
10579                OpKind::AbsElementwise,
10580                [
10581                    abs_elementwise_f32_cpu_wrapper,
10582                    abs_elementwise_f64_cpu_wrapper,
10583                    abs_elementwise_bf16_cpu_wrapper,
10584                    abs_elementwise_f16_cpu_wrapper,
10585                ],
10586            ),
10587            (
10588                OpKind::TanhElementwise,
10589                [
10590                    tanh_elementwise_f32_cpu_wrapper,
10591                    tanh_elementwise_f64_cpu_wrapper,
10592                    tanh_elementwise_bf16_cpu_wrapper,
10593                    tanh_elementwise_f16_cpu_wrapper,
10594                ],
10595            ),
10596            (
10597                OpKind::ExpElementwise,
10598                [
10599                    exp_elementwise_f32_cpu_wrapper,
10600                    exp_elementwise_f64_cpu_wrapper,
10601                    exp_elementwise_bf16_cpu_wrapper,
10602                    exp_elementwise_f16_cpu_wrapper,
10603                ],
10604            ),
10605            (
10606                OpKind::LogElementwise,
10607                [
10608                    log_elementwise_f32_cpu_wrapper,
10609                    log_elementwise_f64_cpu_wrapper,
10610                    log_elementwise_bf16_cpu_wrapper,
10611                    log_elementwise_f16_cpu_wrapper,
10612                ],
10613            ),
10614            (
10615                OpKind::SinElementwise,
10616                [
10617                    sin_elementwise_f32_cpu_wrapper,
10618                    sin_elementwise_f64_cpu_wrapper,
10619                    sin_elementwise_bf16_cpu_wrapper,
10620                    sin_elementwise_f16_cpu_wrapper,
10621                ],
10622            ),
10623            (
10624                OpKind::CosElementwise,
10625                [
10626                    cos_elementwise_f32_cpu_wrapper,
10627                    cos_elementwise_f64_cpu_wrapper,
10628                    cos_elementwise_bf16_cpu_wrapper,
10629                    cos_elementwise_f16_cpu_wrapper,
10630                ],
10631            ),
10632            (
10633                OpKind::SigmoidElementwise,
10634                [
10635                    sigmoid_elementwise_f32_cpu_wrapper,
10636                    sigmoid_elementwise_f64_cpu_wrapper,
10637                    sigmoid_elementwise_bf16_cpu_wrapper,
10638                    sigmoid_elementwise_f16_cpu_wrapper,
10639                ],
10640            ),
10641            (
10642                OpKind::SiluElementwise,
10643                [
10644                    silu_elementwise_f32_cpu_wrapper,
10645                    silu_elementwise_f64_cpu_wrapper,
10646                    silu_elementwise_bf16_cpu_wrapper,
10647                    silu_elementwise_f16_cpu_wrapper,
10648                ],
10649            ),
10650            (
10651                OpKind::StepElementwise,
10652                [
10653                    step_elementwise_f32_cpu_wrapper,
10654                    step_elementwise_f64_cpu_wrapper,
10655                    step_elementwise_bf16_cpu_wrapper,
10656                    step_elementwise_f16_cpu_wrapper,
10657                ],
10658            ),
10659            (
10660                OpKind::GeluTanhElementwise,
10661                [
10662                    gelu_elementwise_f32_cpu_wrapper,
10663                    gelu_elementwise_f64_cpu_wrapper,
10664                    gelu_elementwise_bf16_cpu_wrapper,
10665                    gelu_elementwise_f16_cpu_wrapper,
10666                ],
10667            ),
10668            (
10669                OpKind::FloorElementwise,
10670                [
10671                    floor_elementwise_f32_cpu_wrapper,
10672                    floor_elementwise_f64_cpu_wrapper,
10673                    floor_elementwise_bf16_cpu_wrapper,
10674                    floor_elementwise_f16_cpu_wrapper,
10675                ],
10676            ),
10677            (
10678                OpKind::CeilElementwise,
10679                [
10680                    ceil_elementwise_f32_cpu_wrapper,
10681                    ceil_elementwise_f64_cpu_wrapper,
10682                    ceil_elementwise_bf16_cpu_wrapper,
10683                    ceil_elementwise_f16_cpu_wrapper,
10684                ],
10685            ),
10686            (
10687                OpKind::RoundElementwise,
10688                [
10689                    round_elementwise_f32_cpu_wrapper,
10690                    round_elementwise_f64_cpu_wrapper,
10691                    round_elementwise_bf16_cpu_wrapper,
10692                    round_elementwise_f16_cpu_wrapper,
10693                ],
10694            ),
10695            (
10696                OpKind::SignElementwise,
10697                [
10698                    sign_elementwise_f32_cpu_wrapper,
10699                    sign_elementwise_f64_cpu_wrapper,
10700                    sign_elementwise_bf16_cpu_wrapper,
10701                    sign_elementwise_f16_cpu_wrapper,
10702                ],
10703            ),
10704            (
10705                OpKind::ErfElementwise,
10706                [
10707                    erf_elementwise_f32_cpu_wrapper,
10708                    erf_elementwise_f64_cpu_wrapper,
10709                    erf_elementwise_bf16_cpu_wrapper,
10710                    erf_elementwise_f16_cpu_wrapper,
10711                ],
10712            ),
10713            (
10714                OpKind::GeluElementwise,
10715                [
10716                    gelu_erf_elementwise_f32_cpu_wrapper,
10717                    gelu_erf_elementwise_f64_cpu_wrapper,
10718                    gelu_erf_elementwise_bf16_cpu_wrapper,
10719                    gelu_erf_elementwise_f16_cpu_wrapper,
10720                ],
10721            ),
10722            (
10723                OpKind::RsqrtElementwise,
10724                [
10725                    rsqrt_elementwise_f32_cpu_wrapper,
10726                    rsqrt_elementwise_f64_cpu_wrapper,
10727                    rsqrt_elementwise_bf16_cpu_wrapper,
10728                    rsqrt_elementwise_f16_cpu_wrapper,
10729                ],
10730            ),
10731        ];
10732
10733        let mut checked = 0usize;
10734        for (op, wrappers) in families {
10735            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10736                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10737                let entry = alts
10738                    .iter()
10739                    .find(|e| e.kernel as usize == *expected as usize)
10740                    .unwrap_or_else(|| {
10741                        panic!(
10742                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10743                             FROM the elementwise-unary contract in global_bindings() \
10744                             — found {} alternative(s) with sources {:?}",
10745                            alts.len(),
10746                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10747                        )
10748                    });
10749                assert_eq!(
10750                    entry.kernel_source, "portable-cpu",
10751                    "{op:?}/{dt:?}: unary family must be contract-sourced \
10752                     (kernel_source=\"portable-cpu\"); got {:?}",
10753                    entry.kernel_source,
10754                );
10755                assert!(
10756                    !entry.caps.strided_input,
10757                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10758                );
10759                assert!(
10760                    entry.precision.bit_stable_on_same_hardware,
10761                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10762                );
10763                checked += 1;
10764            }
10765        }
10766        assert_eq!(checked, 88, "all 22 ops × 4 dtypes checked");
10767    }
10768
10769    /// FKC production consumer (born-red gate). `global_bindings()` registers
10770    /// the CPU compare + where family FROM ITS KERNEL CONTRACT
10771    /// (`fuel-dispatch/kernel-contracts/cpu/compare-where.fkc.md`) — the sole path now
10772    /// that the hand-written `table.register(...)` calls for this family are
10773    /// DELETED.
10774    ///
10775    /// Two key shapes, and getting them right IS the point of the test:
10776    ///  - COMPARE (6 ops × 4 dtypes = 24): the U8-mask operand-dtype list
10777    ///    `[T, T, U8]` (`return.out` is always `fixed(U8)`), NOT `[T, T, T]`.
10778    ///  - WHERE (1 op × 4 dtypes = 4): the ternary-select list `[U8, T, T, T]`
10779    ///    (cond U8 + a/b/out share T). `where` exercises BOTH the §3.4
10780    ///    multi-dtype fan-out (one contract section → 4 per-dtype bindings) AND
10781    ///    the `passthrough(a)` fix (output mirrors `a`=T, not the U8 cond).
10782    ///
10783    /// For each key: resolves to the EXACT production wrapper fn-pointer and
10784    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
10785    /// deleted hand-written path stamped `""`; THIS is the discriminator that
10786    /// goes red until the import is wired) — with caps contiguous and the
10787    /// audited bit-stable precision riding through.
10788    #[test]
10789    fn global_bindings_registers_compare_where_family_from_contract() {
10790        let table = global_bindings();
10791        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10792
10793        // -- COMPARE: 6 ops × 4 dtypes, key [T, T, BOOL] (GAP-168c) --
10794        let compare_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10795            (
10796                OpKind::EqualElementwise,
10797                [
10798                    eq_elementwise_f32_cpu_wrapper,
10799                    eq_elementwise_f64_cpu_wrapper,
10800                    eq_elementwise_bf16_cpu_wrapper,
10801                    eq_elementwise_f16_cpu_wrapper,
10802                ],
10803            ),
10804            (
10805                OpKind::NotEqualElementwise,
10806                [
10807                    ne_elementwise_f32_cpu_wrapper,
10808                    ne_elementwise_f64_cpu_wrapper,
10809                    ne_elementwise_bf16_cpu_wrapper,
10810                    ne_elementwise_f16_cpu_wrapper,
10811                ],
10812            ),
10813            (
10814                OpKind::LessElementwise,
10815                [
10816                    lt_elementwise_f32_cpu_wrapper,
10817                    lt_elementwise_f64_cpu_wrapper,
10818                    lt_elementwise_bf16_cpu_wrapper,
10819                    lt_elementwise_f16_cpu_wrapper,
10820                ],
10821            ),
10822            (
10823                OpKind::LessEqualElementwise,
10824                [
10825                    le_elementwise_f32_cpu_wrapper,
10826                    le_elementwise_f64_cpu_wrapper,
10827                    le_elementwise_bf16_cpu_wrapper,
10828                    le_elementwise_f16_cpu_wrapper,
10829                ],
10830            ),
10831            (
10832                OpKind::GreaterElementwise,
10833                [
10834                    gt_elementwise_f32_cpu_wrapper,
10835                    gt_elementwise_f64_cpu_wrapper,
10836                    gt_elementwise_bf16_cpu_wrapper,
10837                    gt_elementwise_f16_cpu_wrapper,
10838                ],
10839            ),
10840            (
10841                OpKind::GreaterEqualElementwise,
10842                [
10843                    ge_elementwise_f32_cpu_wrapper,
10844                    ge_elementwise_f64_cpu_wrapper,
10845                    ge_elementwise_bf16_cpu_wrapper,
10846                    ge_elementwise_f16_cpu_wrapper,
10847                ],
10848            ),
10849        ];
10850
10851        let mut checked = 0usize;
10852        for (op, wrappers) in compare_families {
10853            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10854                // Bool-mask operand-dtype list: [T, T, Bool] — NOT [T, T, T].
10855                // GAP-168(c): comparisons key on Bool, not the retired U8 mask.
10856                let alts = table.lookup_alternatives(*op, &[*dt, *dt, DType::Bool], BackendId::Cpu);
10857                let entry = alts
10858                    .iter()
10859                    .find(|e| e.kernel as usize == *expected as usize)
10860                    .unwrap_or_else(|| {
10861                        panic!(
10862                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
10863                             FROM the compare-where contract in global_bindings() \
10864                             — found {} alternative(s) with sources {:?}",
10865                            alts.len(),
10866                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10867                        )
10868                    });
10869                assert_eq!(
10870                    entry.kernel_source, "portable-cpu",
10871                    "{op:?}/{dt:?}: compare family must be contract-sourced \
10872                     (kernel_source=\"portable-cpu\"); got {:?}",
10873                    entry.kernel_source,
10874                );
10875                assert!(
10876                    !entry.caps.strided_input,
10877                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10878                );
10879                assert!(
10880                    entry.precision.bit_stable_on_same_hardware,
10881                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
10882                );
10883                checked += 1;
10884            }
10885        }
10886
10887        // -- WHERE: 1 op × 4 dtypes, key [U8, T, T, T] (fan-out + passthrough(a)) --
10888        let where_wrappers: [crate::kernel::KernelRef; 4] = [
10889            where_f32_cpu_wrapper,
10890            where_f64_cpu_wrapper,
10891            where_bf16_cpu_wrapper,
10892            where_f16_cpu_wrapper,
10893        ];
10894        for (dt, expected) in dts.iter().zip(where_wrappers.iter()) {
10895            // Ternary-select list: [U8 cond, T a, T b, T out].
10896            let alts = table.lookup_alternatives(
10897                OpKind::Where,
10898                &[DType::Bool, *dt, *dt, *dt],
10899                BackendId::Cpu,
10900            );
10901            let entry = alts
10902                .iter()
10903                .find(|e| e.kernel as usize == *expected as usize)
10904                .unwrap_or_else(|| {
10905                    panic!(
10906                        "Where/{dt:?}/Cpu: the production wrapper must be bound FROM \
10907                         the compare-where contract (where fans to [U8,T,T,T]) in \
10908                         global_bindings() — found {} alternative(s) with sources {:?}",
10909                        alts.len(),
10910                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
10911                    )
10912                });
10913            assert_eq!(
10914                entry.kernel_source, "portable-cpu",
10915                "Where/{dt:?}: where must be contract-sourced \
10916                 (kernel_source=\"portable-cpu\"); got {:?}",
10917                entry.kernel_source,
10918            );
10919            assert!(
10920                !entry.caps.strided_input,
10921                "Where/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
10922            );
10923            checked += 1;
10924        }
10925
10926        assert_eq!(checked, 28, "24 compare (6×4) + 4 where keys checked");
10927    }
10928
10929    /// FKC production consumer (born-red gate). `global_bindings()` registers
10930    /// the CPU per-axis reduce family (Sum/Mean/Max/Min × F32/F64/BF16/F16 = 16)
10931    /// FROM ITS KERNEL CONTRACT (`fuel-dispatch/kernel-contracts/cpu/reduce.fkc.md`) — the
10932    /// sole path now that the hand-written `table.register(...)` calls for this
10933    /// family are DELETED.
10934    ///
10935    /// The binding key is the `[T, T]` operand-dtype list (input +
10936    /// `passthrough(input)` output; the reduce axes + keepdim ride in
10937    /// `OpParams::Reduce`, NOT the dtype-list). Each per-(op,dtype) section
10938    /// carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no fan-out).
10939    ///
10940    /// For each key: resolves to the EXACT production wrapper fn-pointer and
10941    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
10942    /// deleted hand-written path stamped `""`; THIS is the discriminator that
10943    /// goes red until the import is wired) — with caps contiguous and the audited
10944    /// bit-stable precision riding through.
10945    #[test]
10946    fn global_bindings_registers_reduce_family_from_contract() {
10947        let table = global_bindings();
10948        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
10949
10950        // Sum/Mean/Max/Min × {f32,f64,bf16,f16}, key [T, T].
10951        let reduce_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
10952            (
10953                OpKind::SumReduce,
10954                [
10955                    sum_reduce_f32_cpu_wrapper,
10956                    sum_reduce_f64_cpu_wrapper,
10957                    sum_reduce_bf16_cpu_wrapper,
10958                    sum_reduce_f16_cpu_wrapper,
10959                ],
10960            ),
10961            (
10962                OpKind::MeanReduce,
10963                [
10964                    mean_reduce_f32_cpu_wrapper,
10965                    mean_reduce_f64_cpu_wrapper,
10966                    mean_reduce_bf16_cpu_wrapper,
10967                    mean_reduce_f16_cpu_wrapper,
10968                ],
10969            ),
10970            (
10971                OpKind::MaxReduce,
10972                [
10973                    max_reduce_f32_cpu_wrapper,
10974                    max_reduce_f64_cpu_wrapper,
10975                    max_reduce_bf16_cpu_wrapper,
10976                    max_reduce_f16_cpu_wrapper,
10977                ],
10978            ),
10979            (
10980                OpKind::MinReduce,
10981                [
10982                    min_reduce_f32_cpu_wrapper,
10983                    min_reduce_f64_cpu_wrapper,
10984                    min_reduce_bf16_cpu_wrapper,
10985                    min_reduce_f16_cpu_wrapper,
10986                ],
10987            ),
10988        ];
10989
10990        let mut checked = 0usize;
10991        for (op, wrappers) in reduce_families {
10992            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
10993                // [T, T] operand-dtype list (input + passthrough output).
10994                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
10995                let entry = alts
10996                    .iter()
10997                    .find(|e| e.kernel as usize == *expected as usize)
10998                    .unwrap_or_else(|| {
10999                        panic!(
11000                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11001                             FROM the reduce contract in global_bindings() \
11002                             — found {} alternative(s) with sources {:?}",
11003                            alts.len(),
11004                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11005                        )
11006                    });
11007                assert_eq!(
11008                    entry.kernel_source, "portable-cpu",
11009                    "{op:?}/{dt:?}: reduce family must be contract-sourced \
11010                     (kernel_source=\"portable-cpu\"); got {:?}",
11011                    entry.kernel_source,
11012                );
11013                assert!(
11014                    !entry.caps.strided_input,
11015                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11016                );
11017                assert!(
11018                    entry.precision.bit_stable_on_same_hardware,
11019                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11020                );
11021                checked += 1;
11022            }
11023        }
11024        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11025    }
11026
11027    /// Born-red guard for the CPU reduce-to family FKC migration. Mirrors the
11028    /// reduce-family test across the two key shapes this family carries:
11029    /// `ReduceSumTo` / `ReduceMaxTo` are single input → `passthrough` output,
11030    /// key `[T, T]`; `ReduceMaxToBackward` is two inputs (x, upstream) +
11031    /// `passthrough(x)` output, key `[T, T, T]`. Each × {f32,f64,bf16,f16}.
11032    ///
11033    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11034    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11035    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11036    /// goes red until the import is wired) — caps contiguous, and the audited
11037    /// bit-stable precision riding through.
11038    #[test]
11039    fn global_bindings_registers_reduce_to_family_from_contract() {
11040        let table = global_bindings();
11041        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11042
11043        // ReduceSumTo / ReduceMaxTo — single input + passthrough output, key [T, T].
11044        let unary_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11045            (
11046                OpKind::ReduceSumTo,
11047                [
11048                    reduce_sum_to_f32_cpu_wrapper,
11049                    reduce_sum_to_f64_cpu_wrapper,
11050                    reduce_sum_to_bf16_cpu_wrapper,
11051                    reduce_sum_to_f16_cpu_wrapper,
11052                ],
11053            ),
11054            (
11055                OpKind::ReduceMaxTo,
11056                [
11057                    reduce_max_to_f32_cpu_wrapper,
11058                    reduce_max_to_f64_cpu_wrapper,
11059                    reduce_max_to_bf16_cpu_wrapper,
11060                    reduce_max_to_f16_cpu_wrapper,
11061                ],
11062            ),
11063        ];
11064        // ReduceMaxToBackward — two inputs (x, upstream) + passthrough(x)
11065        // output, key [T, T, T].
11066        let backward_family: (OpKind, [crate::kernel::KernelRef; 4]) = (
11067            OpKind::ReduceMaxToBackward,
11068            [
11069                reduce_max_to_backward_f32_cpu_wrapper,
11070                reduce_max_to_backward_f64_cpu_wrapper,
11071                reduce_max_to_backward_bf16_cpu_wrapper,
11072                reduce_max_to_backward_f16_cpu_wrapper,
11073            ],
11074        );
11075
11076        // Assert one (op, key, expected-wrapper) is bound FROM the contract.
11077        let assert_contract_bound =
11078            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef| {
11079                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11080                let entry = alts
11081                    .iter()
11082                    .find(|e| e.kernel as usize == expected as usize)
11083                    .unwrap_or_else(|| {
11084                        panic!(
11085                            "{op:?}/{key:?}/Cpu: the production wrapper must be bound \
11086                             FROM the reduce-to contract in global_bindings() \
11087                             — found {} alternative(s) with sources {:?}",
11088                            alts.len(),
11089                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11090                        )
11091                    });
11092                assert_eq!(
11093                    entry.kernel_source, "portable-cpu",
11094                    "{op:?}/{key:?}: reduce-to family must be contract-sourced \
11095                     (kernel_source=\"portable-cpu\"); got {:?}",
11096                    entry.kernel_source,
11097                );
11098                assert!(
11099                    !entry.caps.strided_input,
11100                    "{op:?}/{key:?}: caps preserved (contiguous-only, strided_input=false)",
11101                );
11102                assert!(
11103                    entry.precision.bit_stable_on_same_hardware,
11104                    "{op:?}/{key:?}: the contract's audited bit-stable claim rode through",
11105                );
11106            };
11107
11108        let mut checked = 0usize;
11109        for (op, wrappers) in unary_families {
11110            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11111                assert_contract_bound(*op, &[*dt, *dt], *expected);
11112                checked += 1;
11113            }
11114        }
11115        let (op, wrappers) = backward_family;
11116        for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11117            assert_contract_bound(op, &[*dt, *dt, *dt], *expected);
11118            checked += 1;
11119        }
11120        assert_eq!(checked, 12, "3 ops × 4 dtypes checked");
11121    }
11122
11123    /// Born-red guard for the CPU last-dim NORM (forward) family FKC migration.
11124    /// Softmax / LogSoftmax / RmsNorm / LayerNorm are each a SINGLE input →
11125    /// `passthrough` output, key `[T, T]` — the RMS/LayerNorm kernels carry NO
11126    /// affine gamma/beta operand (bare normalization), and outer_count/last_dim/
11127    /// eps ride in `OpParams`, so the key stays `[T, T]` (not a 3- or 4-operand
11128    /// key). Each × {f32,f64,bf16,f16} = 16 bindings.
11129    ///
11130    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11131    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11132    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11133    /// goes red until the import is wired) — caps contiguous, and the audited
11134    /// bit-stable precision riding through.
11135    #[test]
11136    fn global_bindings_registers_norm_family_from_contract() {
11137        let table = global_bindings();
11138        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11139
11140        // Softmax / LogSoftmax / RmsNorm / LayerNorm — single input +
11141        // passthrough output, key [T, T]. Wrapper order matches `dts`.
11142        let norm_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11143            (
11144                OpKind::SoftmaxLastDim,
11145                [
11146                    softmax_last_dim_f32_cpu_wrapper,
11147                    softmax_last_dim_f64_cpu_wrapper,
11148                    softmax_last_dim_bf16_cpu_wrapper,
11149                    softmax_last_dim_f16_cpu_wrapper,
11150                ],
11151            ),
11152            (
11153                OpKind::LogSoftmaxLastDim,
11154                [
11155                    log_softmax_f32_cpu_wrapper,
11156                    log_softmax_f64_cpu_wrapper,
11157                    log_softmax_bf16_cpu_wrapper,
11158                    log_softmax_f16_cpu_wrapper,
11159                ],
11160            ),
11161            (
11162                OpKind::RmsNormLastDim,
11163                [
11164                    rms_norm_last_dim_f32_cpu_wrapper,
11165                    rms_norm_last_dim_f64_cpu_wrapper,
11166                    rms_norm_last_dim_bf16_cpu_wrapper,
11167                    rms_norm_last_dim_f16_cpu_wrapper,
11168                ],
11169            ),
11170            (
11171                OpKind::LayerNormLastDim,
11172                [
11173                    layer_norm_last_dim_f32_cpu_wrapper,
11174                    layer_norm_last_dim_f64_cpu_wrapper,
11175                    layer_norm_last_dim_bf16_cpu_wrapper,
11176                    layer_norm_last_dim_f16_cpu_wrapper,
11177                ],
11178            ),
11179        ];
11180
11181        let mut checked = 0usize;
11182        for (op, wrappers) in norm_families {
11183            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11184                // [T, T] operand-dtype list (input + passthrough output).
11185                let alts = table.lookup_alternatives(*op, &[*dt, *dt], BackendId::Cpu);
11186                let entry = alts
11187                    .iter()
11188                    .find(|e| e.kernel as usize == *expected as usize)
11189                    .unwrap_or_else(|| {
11190                        panic!(
11191                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11192                             FROM the norm contract in global_bindings() \
11193                             — found {} alternative(s) with sources {:?}",
11194                            alts.len(),
11195                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11196                        )
11197                    });
11198                assert_eq!(
11199                    entry.kernel_source, "portable-cpu",
11200                    "{op:?}/{dt:?}: norm family must be contract-sourced \
11201                     (kernel_source=\"portable-cpu\"); got {:?}",
11202                    entry.kernel_source,
11203                );
11204                assert!(
11205                    !entry.caps.strided_input,
11206                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11207                );
11208                assert!(
11209                    entry.precision.bit_stable_on_same_hardware,
11210                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11211                );
11212                checked += 1;
11213            }
11214        }
11215        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11216    }
11217
11218    /// Born-red guard for the CPU last-dim NORM-BACKWARD family FKC migration.
11219    /// Softmax / LogSoftmax / LayerNorm / RmsNorm backward are each TWO inputs
11220    /// (the forward output-or-input `y`/`x` + the upstream gradient `g`) → ONE
11221    /// `passthrough` output — the BARE backward (no affine gamma/beta grad
11222    /// operand and no saved-stats operand; the norm kernels recompute mean/var
11223    /// or mean-square from `x` + `eps`), so the binding key is `[T, T, T]`
11224    /// (in, in, out) and outer_count / last_dim / eps ride in `OpParams`, NOT
11225    /// the dtype-list. Each × {f32,f64,bf16,f16} = 16 bindings.
11226    ///
11227    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11228    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11229    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11230    /// goes red until the import is wired) — caps contiguous, and the audited
11231    /// bit-stable precision riding through.
11232    #[test]
11233    fn global_bindings_registers_norm_backward_family_from_contract() {
11234        let table = global_bindings();
11235        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11236
11237        // Softmax / LogSoftmax / LayerNorm / RmsNorm backward — two inputs
11238        // (y/x, g) + passthrough output, key [T, T, T]. Wrapper order matches
11239        // `dts`. (LogSoftmax's wrapper fn-name `log_softmax_backward_*` differs
11240        // from its `log_softmax_last_dim_backward_*` contract symbol — the same
11241        // fn-vs-symbol split as the forward `log_softmax` case.)
11242        let backward_families: &[(OpKind, [crate::kernel::KernelRef; 4])] = &[
11243            (
11244                OpKind::SoftmaxLastDimBackward,
11245                [
11246                    softmax_last_dim_backward_f32_cpu_wrapper,
11247                    softmax_last_dim_backward_f64_cpu_wrapper,
11248                    softmax_last_dim_backward_bf16_cpu_wrapper,
11249                    softmax_last_dim_backward_f16_cpu_wrapper,
11250                ],
11251            ),
11252            (
11253                OpKind::LogSoftmaxLastDimBackward,
11254                [
11255                    log_softmax_backward_f32_cpu_wrapper,
11256                    log_softmax_backward_f64_cpu_wrapper,
11257                    log_softmax_backward_bf16_cpu_wrapper,
11258                    log_softmax_backward_f16_cpu_wrapper,
11259                ],
11260            ),
11261            (
11262                OpKind::LayerNormLastDimBackward,
11263                [
11264                    layer_norm_last_dim_backward_f32_cpu_wrapper,
11265                    layer_norm_last_dim_backward_f64_cpu_wrapper,
11266                    layer_norm_last_dim_backward_bf16_cpu_wrapper,
11267                    layer_norm_last_dim_backward_f16_cpu_wrapper,
11268                ],
11269            ),
11270            (
11271                OpKind::RmsNormLastDimBackward,
11272                [
11273                    rms_norm_last_dim_backward_f32_cpu_wrapper,
11274                    rms_norm_last_dim_backward_f64_cpu_wrapper,
11275                    rms_norm_last_dim_backward_bf16_cpu_wrapper,
11276                    rms_norm_last_dim_backward_f16_cpu_wrapper,
11277                ],
11278            ),
11279        ];
11280
11281        let mut checked = 0usize;
11282        for (op, wrappers) in backward_families {
11283            for (dt, expected) in dts.iter().zip(wrappers.iter()) {
11284                // [T, T, T] operand-dtype list (two inputs + passthrough output).
11285                let alts = table.lookup_alternatives(*op, &[*dt, *dt, *dt], BackendId::Cpu);
11286                let entry = alts
11287                    .iter()
11288                    .find(|e| e.kernel as usize == *expected as usize)
11289                    .unwrap_or_else(|| {
11290                        panic!(
11291                            "{op:?}/{dt:?}/Cpu: the production wrapper must be bound \
11292                             FROM the norm-backward contract in global_bindings() \
11293                             — found {} alternative(s) with sources {:?}",
11294                            alts.len(),
11295                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11296                        )
11297                    });
11298                assert_eq!(
11299                    entry.kernel_source, "portable-cpu",
11300                    "{op:?}/{dt:?}: norm-backward family must be contract-sourced \
11301                     (kernel_source=\"portable-cpu\"); got {:?}",
11302                    entry.kernel_source,
11303                );
11304                assert!(
11305                    !entry.caps.strided_input,
11306                    "{op:?}/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11307                );
11308                assert!(
11309                    entry.precision.bit_stable_on_same_hardware,
11310                    "{op:?}/{dt:?}: the contract's audited bit-stable claim rode through",
11311                );
11312                checked += 1;
11313            }
11314        }
11315        assert_eq!(checked, 16, "4 ops × 4 dtypes checked");
11316    }
11317
11318    /// RoPE (rotary position embedding) is ONE primitive op (`OpKind::Rope`)
11319    /// monomorphized over the four float dtypes {F32, F64, BF16, F16}. Each
11320    /// dtype is a distinct single-dtype contract section (`## rope_f32`, …) with
11321    /// a concrete `entry_point` (`fuel_cpu_backend::byte_kernels::rope_f32`), so
11322    /// none of them fan — the importer resolves each declared symbol AS-IS. RoPE
11323    /// takes THREE inputs (`x` + the precomputed `cos`/`sin` tables, all one
11324    /// dtype; the tables broadcast over the outer axis by re-indexing, NOT a
11325    /// stride-0 view) and writes ONE `passthrough(x)` output, so the binding key
11326    /// is `[T, T, T, T]` (x, cos, sin, out); outer_count / seq / head_dim ride in
11327    /// `OpParams::Rope`, NOT the dtype-list — identical to the deleted
11328    /// `rope_dts(t)` regs.
11329    ///
11330    /// For each key: resolves to the EXACT production wrapper fn-pointer with
11331    /// `kernel_source == "portable-cpu"` — the contract provenance tag (the
11332    /// deleted hand-written path stamped `""`; THIS is the discriminator that
11333    /// goes red until the import is wired) — caps contiguous, and the audited
11334    /// bit-stable precision riding through.
11335    #[test]
11336    fn global_bindings_registers_rope_family_from_contract() {
11337        let table = global_bindings();
11338        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11339        // Wrapper order matches `dts`.
11340        let expected_wrappers: [crate::kernel::KernelRef; 4] = [
11341            rope_f32_cpu_wrapper,
11342            rope_f64_cpu_wrapper,
11343            rope_bf16_cpu_wrapper,
11344            rope_f16_cpu_wrapper,
11345        ];
11346
11347        let mut checked = 0usize;
11348        for (dt, expected) in dts.iter().zip(expected_wrappers.iter()) {
11349            // [T, T, T, T] operand-dtype list (x, cos, sin + passthrough output).
11350            let alts =
11351                table.lookup_alternatives(OpKind::Rope, &[*dt, *dt, *dt, *dt], BackendId::Cpu);
11352            let entry = alts
11353                .iter()
11354                .find(|e| e.kernel as usize == *expected as usize)
11355                .unwrap_or_else(|| {
11356                    panic!(
11357                        "Rope/{dt:?}/Cpu: the production wrapper must be bound \
11358                         FROM the rope contract in global_bindings() \
11359                         — found {} alternative(s) with sources {:?}",
11360                        alts.len(),
11361                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11362                    )
11363                });
11364            assert_eq!(
11365                entry.kernel_source, "portable-cpu",
11366                "Rope/{dt:?}: rope family must be contract-sourced \
11367                 (kernel_source=\"portable-cpu\"); got {:?}",
11368                entry.kernel_source,
11369            );
11370            assert!(
11371                !entry.caps.strided_input,
11372                "Rope/{dt:?}: caps preserved (contiguous-only, strided_input=false)",
11373            );
11374            assert!(
11375                entry.precision.bit_stable_on_same_hardware,
11376                "Rope/{dt:?}: the contract's audited bit-stable claim rode through",
11377            );
11378            checked += 1;
11379        }
11380        assert_eq!(checked, 4, "1 op × 4 dtypes checked");
11381    }
11382
11383    /// Gate for the CPU SSM / Mamba family FULLY migrated to FKC-contract
11384    /// registration. The WHOLE family — FusedSoftmaxCrossEntropy (key
11385    /// `[T, I64, F32]` — logits T + I64 targets → fixed(F32) output),
11386    /// CausalConv1d (key `[T, T, T, T]` — x, weight, bias + passthrough(x)
11387    /// output), and the two SCAN ops SelectiveScan / SsdChunkScan (key `[T; 6]`
11388    /// — 5 inputs + the ONE bundled output slot), 4 ops × 4 dtypes = 16
11389    /// bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/ssm.fkc.md`.
11390    ///
11391    /// The scans' `[T; 6]` keys are now contract-sourced too: their sections
11392    /// return a `return.bundle` multi-output (Option C, one buffer
11393    /// `[y ; last_state]`), and the importer's key-builder appends the bundle's
11394    /// PRIMARY-slot dtype (`passthrough(u)` / `passthrough(x)` → T) to the key
11395    /// tail — byte-for-byte the deleted hand-written `&[dt; 6]` regs.
11396    ///
11397    /// For each of the 16 keys: resolves to the EXACT production wrapper
11398    /// fn-pointer with `kernel_source == "portable-cpu"` (the contract
11399    /// provenance tag; the deleted hand-written path stamped `""`), caps
11400    /// contiguous, and the contract's bit-stable precision riding through.
11401    #[test]
11402    fn global_bindings_registers_ssm_family_from_contract() {
11403        let table = global_bindings();
11404        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11405
11406        // Assert one (op, key) binds `expected` FROM the contract (portable-cpu,
11407        // contiguous caps, bit-stable precision). `key` is the full binding key.
11408        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11409            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11410            let entry = alts
11411                .iter()
11412                .find(|e| e.kernel as usize == expected as usize)
11413                .unwrap_or_else(|| {
11414                    panic!(
11415                        "{label}/Cpu (key {key:?}): the production wrapper must be bound \
11416                         FROM the ssm contract in global_bindings() — found {} \
11417                         alternative(s) with sources {:?}",
11418                        alts.len(),
11419                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11420                    )
11421                });
11422            assert_eq!(
11423                entry.kernel_source, "portable-cpu",
11424                "{label}: family must be contract-sourced (kernel_source=\"portable-cpu\"); \
11425                 got {:?}",
11426                entry.kernel_source,
11427            );
11428            assert!(
11429                !entry.caps.strided_input,
11430                "{label}: caps preserved (contiguous-only)"
11431            );
11432            assert!(
11433                entry.precision.bit_stable_on_same_hardware,
11434                "{label}: contract's bit-stable claim rode through",
11435            );
11436        };
11437
11438        // Per-op wrappers, indexed to match `dts` order.
11439        let fsce: [crate::kernel::KernelRef; 4] = [
11440            fused_softmax_cross_entropy_f32_cpu_wrapper,
11441            fused_softmax_cross_entropy_f64_cpu_wrapper,
11442            fused_softmax_cross_entropy_bf16_cpu_wrapper,
11443            fused_softmax_cross_entropy_f16_cpu_wrapper,
11444        ];
11445        let conv: [crate::kernel::KernelRef; 4] = [
11446            causal_conv1d_f32_cpu_wrapper,
11447            causal_conv1d_f64_cpu_wrapper,
11448            causal_conv1d_bf16_cpu_wrapper,
11449            causal_conv1d_f16_cpu_wrapper,
11450        ];
11451        let sscan: [crate::kernel::KernelRef; 4] = [
11452            selective_scan_f32_cpu_wrapper,
11453            selective_scan_f64_cpu_wrapper,
11454            selective_scan_bf16_cpu_wrapper,
11455            selective_scan_f16_cpu_wrapper,
11456        ];
11457        let ssd: [crate::kernel::KernelRef; 4] = [
11458            ssd_chunk_scan_f32_cpu_wrapper,
11459            ssd_chunk_scan_f64_cpu_wrapper,
11460            ssd_chunk_scan_bf16_cpu_wrapper,
11461            ssd_chunk_scan_f16_cpu_wrapper,
11462        ];
11463
11464        let mut checked = 0usize;
11465        for (i, dt) in dts.iter().enumerate() {
11466            // FSCE: [logits T, targets I64, out F32].
11467            check(
11468                OpKind::FusedSoftmaxCrossEntropy,
11469                &[*dt, DType::I64, DType::F32],
11470                fsce[i],
11471                "FusedSoftmaxCrossEntropy",
11472            );
11473            // CausalConv1d: [x, weight, bias, out] all T.
11474            check(OpKind::CausalConv1d, &[*dt; 4], conv[i], "CausalConv1d");
11475            // SelectiveScan: [u, delta, a, b, c, out] = [T; 6] (5 inputs + the
11476            // ONE bundled output slot, `passthrough(u)` → T).
11477            check(OpKind::SelectiveScan, &[*dt; 6], sscan[i], "SelectiveScan");
11478            // SsdChunkScan: [x, dt, a, b, c, out] = [T; 6] (5 inputs + the ONE
11479            // bundled output slot, `passthrough(x)` → T).
11480            check(OpKind::SsdChunkScan, &[*dt; 6], ssd[i], "SsdChunkScan");
11481
11482            checked += 1;
11483        }
11484        assert_eq!(
11485            checked, 4,
11486            "4 ops × 4 dtypes checked (16 contract-sourced bindings)"
11487        );
11488    }
11489
11490    /// Gate for the CPU conv family FULLY migrated to FKC-contract registration.
11491    /// The whole family — BOTH the no-bias keys (`[T, T, T]` — x, weight + out)
11492    /// AND the with-bias keys (`[T, T, T, T]` — x, weight, bias + passthrough(x)
11493    /// output) of Conv2D and ConvTranspose2D, 2 ops × 4 dtypes × 2 operand-counts
11494    /// = 16 bindings — is IMPORTED from `fuel-dispatch/kernel-contracts/cpu/conv.fkc.md`.
11495    ///
11496    /// The no-bias keys are now contract-sourced too: the conv contract declares
11497    /// `bias` as `optional: true`, and the importer's key-builder
11498    /// (`fkc/lower.rs` `assemble_dtype_variants`) now fans an optional LAST input
11499    /// into BOTH the with- and without-operand keys, both resolving the SAME
11500    /// wrapper. The former hand-written no-bias `table.register(...)` regs are
11501    /// DELETED (deferral closed).
11502    ///
11503    /// For each of the 16 keys: resolves to the EXACT production wrapper
11504    /// fn-pointer with `kernel_source == "portable-cpu"` — the contract
11505    /// provenance tag — caps contiguous, and the contract's bit-stable precision
11506    /// riding through.
11507    #[test]
11508    fn global_bindings_registers_conv_family_from_contract() {
11509        let table = global_bindings();
11510        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11511
11512        // Conv2D wrappers (order matches `dts`); the same wrapper serves both the
11513        // no-bias [x, weight, out] and with-bias [x, weight, bias, out] keys.
11514        let conv2d_wrappers: [crate::kernel::KernelRef; 4] = [
11515            conv2d_f32_cpu_wrapper,
11516            conv2d_f64_cpu_wrapper,
11517            conv2d_bf16_cpu_wrapper,
11518            conv2d_f16_cpu_wrapper,
11519        ];
11520        // ConvTranspose2D wrappers (order matches `dts`).
11521        let convt_wrappers: [crate::kernel::KernelRef; 4] = [
11522            conv_transpose2d_f32_cpu_wrapper,
11523            conv_transpose2d_f64_cpu_wrapper,
11524            conv_transpose2d_bf16_cpu_wrapper,
11525            conv_transpose2d_f16_cpu_wrapper,
11526        ];
11527
11528        let mut checked = 0usize;
11529        for (i, dt) in dts.iter().enumerate() {
11530            for (op, expected) in [
11531                (OpKind::Conv2D, conv2d_wrappers[i]),
11532                (OpKind::ConvTranspose2D, convt_wrappers[i]),
11533            ] {
11534                // BOTH operand-count keys: no-bias [x, weight, out] AND with-bias
11535                // [x, weight, bias, out] — all T, both bound to the SAME wrapper
11536                // from the contract's optional-operand fan.
11537                let no_bias: &[DType] = &[*dt, *dt, *dt];
11538                let with_bias: &[DType] = &[*dt, *dt, *dt, *dt];
11539                for (key, label) in [(no_bias, "no-bias"), (with_bias, "with-bias")] {
11540                    let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11541                    let entry = alts
11542                        .iter()
11543                        .find(|e| e.kernel as usize == expected as usize)
11544                        .unwrap_or_else(|| {
11545                            panic!(
11546                                "{op:?}/{dt:?}/Cpu ({label}): the production wrapper must be \
11547                                 bound FROM the conv contract in global_bindings() — found {} \
11548                                 alternative(s) with sources {:?}",
11549                                alts.len(),
11550                                alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11551                            )
11552                        });
11553                    assert_eq!(
11554                        entry.kernel_source, "portable-cpu",
11555                        "{op:?}/{dt:?} ({label}): family must be contract-sourced \
11556                         (kernel_source=\"portable-cpu\"); got {:?}",
11557                        entry.kernel_source,
11558                    );
11559                    assert!(
11560                        !entry.caps.strided_input,
11561                        "{op:?}/{dt:?} ({label}): caps preserved (contiguous-only)",
11562                    );
11563                    assert!(
11564                        entry.precision.bit_stable_on_same_hardware,
11565                        "{op:?}/{dt:?} ({label}): contract's bit-stable claim rode through",
11566                    );
11567                    checked += 1;
11568                }
11569            }
11570        }
11571        assert_eq!(
11572            checked, 16,
11573            "2 ops × 4 dtypes × 2 operand-counts checked (16 contract-sourced bindings)"
11574        );
11575    }
11576
11577    /// Gate for the CPU **padding** family's BACKWARD half migrated to
11578    /// FKC-contract registration. The four `PadBackward` per-dtype kernels
11579    /// (key `[T, T]` — grad_out + `passthrough(grad_out)` grad_in, T ∈
11580    /// {F32,F64,BF16,F16}) are IMPORTED from
11581    /// `fuel-dispatch/kernel-contracts/cpu/padding.fkc.md` — the `pad_backward_<dt>`
11582    /// single-dtype sections, each resolved AS-IS (no dtype fan-out) through the
11583    /// production `CpuLinkRegistry` (chaining `CPU_PADDING_ENTRY_POINTS`).
11584    ///
11585    /// The FORWARD `Pad` half (Constant/Reflect/Replicate) is ALSO migrated:
11586    /// the three runtime modes collapse to ONE mode-unified `(Pad, [T, T])`
11587    /// binding per dtype served by the single dtype-agnostic `pad_cpu_wrapper`
11588    /// (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
11589    /// section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
11590    /// resolving `pad_cpu_wrapper` (the fabricated `pad_cpu_<dt>` symbol → the one
11591    /// wrapper, like Flip/Roll/Concat); the three per-mode sections
11592    /// (`pad_const_cpu`/`pad_reflect_cpu`/`pad_replicate_cpu`) and the
11593    /// `pad_walk_cpu` helper stay `registrable: false` describe-only mode docs.
11594    /// See `register_cpu_padding_from_contract`.
11595    ///
11596    /// For each of the 4 backward + 6 forward keys: resolves to the EXACT
11597    /// production wrapper with `kernel_source == "portable-cpu"` (the contract
11598    /// provenance tag), caps contiguous, and the contract's bit-stable precision
11599    /// riding through.
11600    #[test]
11601    fn global_bindings_registers_padding_family_from_contract() {
11602        let table = global_bindings();
11603        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11604        // PadBackward wrappers, indexed to match `dts` order.
11605        let pad_backward: [crate::kernel::KernelRef; 4] = [
11606            pad_backward_f32_cpu_wrapper,
11607            pad_backward_f64_cpu_wrapper,
11608            pad_backward_bf16_cpu_wrapper,
11609            pad_backward_f16_cpu_wrapper,
11610        ];
11611
11612        let mut checked = 0usize;
11613        for (i, dt) in dts.iter().enumerate() {
11614            // PadBackward: [grad_out T, grad_in T] = [T, T] (passthrough(grad_out)).
11615            let key: &[DType] = &[*dt, *dt];
11616            let expected = pad_backward[i];
11617            let alts = table.lookup_alternatives(OpKind::PadBackward, key, BackendId::Cpu);
11618            let entry = alts
11619                .iter()
11620                .find(|e| e.kernel as usize == expected as usize)
11621                .unwrap_or_else(|| {
11622                    panic!(
11623                        "PadBackward/{dt:?}/Cpu: the production wrapper must be bound \
11624                         FROM the padding contract in global_bindings() — found {} \
11625                         alternative(s) with sources {:?}",
11626                        alts.len(),
11627                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11628                    )
11629                });
11630            assert_eq!(
11631                entry.kernel_source, "portable-cpu",
11632                "PadBackward/{dt:?}: family must be contract-sourced \
11633                 (kernel_source=\"portable-cpu\"); got {:?}",
11634                entry.kernel_source,
11635            );
11636            assert!(
11637                !entry.caps.strided_input,
11638                "PadBackward/{dt:?}: caps preserved (contiguous-only)",
11639            );
11640            assert!(
11641                entry.precision.bit_stable_on_same_hardware,
11642                "PadBackward/{dt:?}: contract's bit-stable claim rode through",
11643            );
11644            checked += 1;
11645        }
11646
11647        // Forward Pad (Constant/Reflect/Replicate) — ONE mode-unified `(Pad, [T, T])`
11648        // binding per dtype served by the SINGLE dtype-agnostic `pad_cpu_wrapper`
11649        // (mode chosen at runtime via `mode_tag`). The contract's unified `## pad`
11650        // section fans its 6 production dtypes (U8/U32/BF16/F16/F32/F64), ALL
11651        // resolving `pad_cpu_wrapper` (fabricated `pad_cpu_<dt>` symbol → the one
11652        // wrapper, like Flip/Roll/Concat). in_shape/out_shape/padding/mode_tag/
11653        // fill_bytes ride in OpParams::Pad, NOT the dtype-list.
11654        let pad_forward_dts = [
11655            DType::U8,
11656            DType::U32,
11657            DType::BF16,
11658            DType::F16,
11659            DType::F32,
11660            DType::F64,
11661        ];
11662        for dt in pad_forward_dts {
11663            let key: &[DType] = &[dt, dt];
11664            let alts = table.lookup_alternatives(OpKind::Pad, key, BackendId::Cpu);
11665            let entry = alts
11666                .iter()
11667                .find(|e| e.kernel as usize == pad_cpu_wrapper as *const () as usize)
11668                .unwrap_or_else(|| {
11669                    panic!(
11670                        "Pad/{dt:?}/Cpu: the production wrapper must be bound \
11671                         FROM the padding contract in global_bindings() — found {} \
11672                         alternative(s) with sources {:?}",
11673                        alts.len(),
11674                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11675                    )
11676                });
11677            assert_eq!(
11678                entry.kernel_source, "portable-cpu",
11679                "Pad/{dt:?}: forward family must be contract-sourced \
11680                 (kernel_source=\"portable-cpu\"); got {:?}",
11681                entry.kernel_source,
11682            );
11683            assert!(
11684                !entry.caps.strided_input,
11685                "Pad/{dt:?}: caps preserved (contiguous-only)",
11686            );
11687            assert!(
11688                entry.precision.bit_stable_on_same_hardware,
11689                "Pad/{dt:?}: contract's bit-stable claim rode through",
11690            );
11691            checked += 1;
11692        }
11693
11694        assert_eq!(
11695            checked, 10,
11696            "4 PadBackward + 6 forward Pad dtypes checked (contract-sourced bindings)"
11697        );
11698    }
11699
11700    /// Gate for the CPU **shape-ops** family's migratable subset moved to
11701    /// FKC-contract registration. IMPORTED from
11702    /// `fuel-dispatch/kernel-contracts/cpu/shape-ops.fkc.md` via the production
11703    /// `CpuLinkRegistry` (chaining `CPU_SHAPE_OPS_ENTRY_POINTS`):
11704    /// - **Flip** / **Roll** — dtype-agnostic byte reorder, key `[T, T]`, one
11705    ///   `flip_cpu_wrapper` / `roll_cpu_wrapper` per dtype (fan over the 6
11706    ///   production dtypes F32/F64/BF16/F16/U32/U8; the contract's dtype list is
11707    ///   trimmed to match production, NOT the kernel's full byte-agnostic set).
11708    /// - **CumSum** — per-dtype typed accumulation (f32/f64 native, bf16/f16 with
11709    ///   an f32 accumulator), key `[T, T]`, its SPECIFIC `cumsum_<dt>` symbol
11710    ///   resolved AS-IS (no fan), 4 dtypes.
11711    /// - **MaskedFill** — dtype-agnostic data + U8 mask, key `[T, U8, T]`, one
11712    ///   `masked_fill_cpu_wrapper` per dtype (fan over the same 6 dtypes).
11713    /// - **Concat** — variadic uniform-dtype join collapsed to the `[T, T]`
11714    ///   shorthand key, one `concat_cpu_wrapper` per dtype (fan over the 9
11715    ///   production dtypes F32/F64/BF16/F16/U32/U8/I16/I32/I64).
11716    /// - **WriteSlice** / **WriteSliceRotating** — in-place rectangular / ring
11717    ///   scatter, key `[T, T]`, one dtype-agnostic wrapper each (fan over the same
11718    ///   6 dtypes). `dest` is the in-place OUTPUT slot (not a key input); for the
11719    ///   rotating op the U32 `position` is a NON-KEY runtime operand — so the
11720    ///   contract's source-only + `out: passthrough(source)` section keys
11721    ///   `[T_source, T_out]` = `[T, T]`, matching `build_lookup_dtypes` exactly.
11722    ///
11723    /// DEFERRED (hand-written / describe-only, NOT checked here): `Contiguize`
11724    /// (no `OpKind` — an executor materialize pass) and `Triu`/`Tril` (the contract
11725    /// carries only the `triangular` chassis umbrella, `registrable: false`, not
11726    /// two per-OpKind sections). See `register_cpu_shape_ops_from_contract`.
11727    ///
11728    /// For each migrated key: resolves to the EXACT production wrapper with
11729    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
11730    /// contiguous, and the contract's bit-stable precision riding through.
11731    #[test]
11732    fn global_bindings_registers_shape_ops_family_from_contract() {
11733        let table = global_bindings();
11734        let mut checked = 0usize;
11735
11736        // Assert a (op, key) resolves to `expected` with the contract provenance.
11737        let mut check =
11738            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11739                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11740                let entry = alts
11741                    .iter()
11742                    .find(|e| e.kernel as usize == expected as usize)
11743                    .unwrap_or_else(|| {
11744                        panic!(
11745                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
11746                         FROM the shape-ops contract in global_bindings() — found {} \
11747                         alternative(s) with sources {:?}",
11748                            alts.len(),
11749                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11750                        )
11751                    });
11752                assert_eq!(
11753                    entry.kernel_source, "portable-cpu",
11754                    "{op:?}/{label}: family must be contract-sourced \
11755                 (kernel_source=\"portable-cpu\"); got {:?}",
11756                    entry.kernel_source,
11757                );
11758                assert!(
11759                    !entry.caps.strided_input,
11760                    "{op:?}/{label}: caps preserved (contiguous-only)",
11761                );
11762                assert!(
11763                    entry.precision.bit_stable_on_same_hardware,
11764                    "{op:?}/{label}: contract's bit-stable claim rode through",
11765                );
11766                checked += 1;
11767            };
11768
11769        // Flip / Roll — key [T, T], one dtype-agnostic wrapper fanned per dtype.
11770        let byte_dts = [
11771            DType::F32,
11772            DType::F64,
11773            DType::BF16,
11774            DType::F16,
11775            DType::U32,
11776            DType::U8,
11777        ];
11778        for dt in byte_dts {
11779            check(OpKind::Flip, &[dt, dt], flip_cpu_wrapper, "flip");
11780            check(OpKind::Roll, &[dt, dt], roll_cpu_wrapper, "roll");
11781            // MaskedFill — key [T, U8, T].
11782            check(
11783                OpKind::MaskedFill,
11784                &[dt, DType::Bool, dt], // GAP-168(c): mask slot is Bool; the outer dt list is DATA dtypes
11785                masked_fill_cpu_wrapper,
11786                "masked_fill",
11787            );
11788        }
11789
11790        // CumSum — per-dtype typed wrappers, key [T, T], resolved AS-IS.
11791        let cumsum_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11792        let cumsum_wrappers: [crate::kernel::KernelRef; 4] = [
11793            cumsum_f32_cpu_wrapper,
11794            cumsum_f64_cpu_wrapper,
11795            cumsum_bf16_cpu_wrapper,
11796            cumsum_f16_cpu_wrapper,
11797        ];
11798        for (i, dt) in cumsum_dts.iter().enumerate() {
11799            check(OpKind::CumSum, &[*dt, *dt], cumsum_wrappers[i], "cumsum");
11800        }
11801
11802        // Concat — variadic uniform-dtype collapsed to [T, T], 9 dtypes.
11803        let concat_dts = [
11804            DType::F32,
11805            DType::F64,
11806            DType::BF16,
11807            DType::F16,
11808            DType::U32,
11809            DType::U8,
11810            DType::I16,
11811            DType::I32,
11812            DType::I64,
11813        ];
11814        for dt in concat_dts {
11815            check(OpKind::Concat, &[dt, dt], concat_cpu_wrapper, "concat");
11816        }
11817
11818        // WriteSlice / WriteSliceRotating — in-place rectangular / ring-buffer
11819        // scatter, key [T, T] (dest IS the output slot via in-place adoption;
11820        // WriteSliceRotating's `position` is a NON-KEY runtime U32 operand — see
11821        // `build_lookup_dtypes`). One dtype-agnostic wrapper each, fanned over the
11822        // 6 production dtypes (F32/F64/BF16/F16/U32/U8). The offset/modulus/axis/
11823        // ranges ride in OpParams::{WriteSlice,WriteSliceRotating}.
11824        let scatter_dts = [
11825            DType::F32,
11826            DType::F64,
11827            DType::BF16,
11828            DType::F16,
11829            DType::U32,
11830            DType::U8,
11831        ];
11832        for dt in scatter_dts {
11833            check(
11834                OpKind::WriteSlice,
11835                &[dt, dt],
11836                write_slice_cpu_wrapper,
11837                "write_slice",
11838            );
11839            check(
11840                OpKind::WriteSliceRotating,
11841                &[dt, dt],
11842                write_slice_rotating_cpu_wrapper,
11843                "write_slice_rotating",
11844            );
11845            // WriteSliceDoff — like WriteSliceRotating but the runtime operand is a
11846            // NON-KEY I64 `offset` (device-resident under CUDA), no wrap.
11847            check(
11848                OpKind::WriteSliceDoff,
11849                &[dt, dt],
11850                write_slice_doff_cpu_wrapper,
11851                "write_slice_doff",
11852            );
11853        }
11854
11855        assert_eq!(
11856            checked,
11857            6 + 6 + 6 + 4 + 9 + 6 + 6 + 6,
11858            "flip(6) + roll(6) + masked_fill(6) + cumsum(4) + concat(9) + \
11859             write_slice(6) + write_slice_rotating(6) + write_slice_doff(6) contract-sourced bindings",
11860        );
11861    }
11862
11863    /// Gate for the CPU **indexing / gather / scatter** family moved to
11864    /// FKC-contract registration. IMPORTED from
11865    /// `fuel-dispatch/kernel-contracts/cpu/indexing.fkc.md` via the production
11866    /// `CpuLinkRegistry` (chaining `CPU_INDEXING_ENTRY_POINTS`):
11867    /// - **IndexSelect** / **Gather** — dtype-agnostic byte copy, key
11868    ///   `[T, U32, T]` (`source`, fixed-U32 `indices`, `passthrough(source)`
11869    ///   output). One `index_select_cpu_wrapper` / `gather_cpu_wrapper` per dtype
11870    ///   (the contract's ONE section declares a BASE `entry_point`
11871    ///   (`…::index_select_cpu` / `…::gather_cpu`) fanned over its dtype list, the
11872    ///   fabricated `<base>_<dt>` symbol resolving to the ONE wrapper — the
11873    ///   pad/flip umbrella precedent). The contract's dtype list is trimmed to
11874    ///   production's 9 wired dtypes (F32/F64/BF16/F16/U32/U8/I16/I32/I64); I8 is
11875    ///   describable (byte-agnostic) but NOT wired in production, so it is dropped
11876    ///   from the contract, NOT the kernel's full byte-agnostic set.
11877    /// - **IndexAdd** / **ScatterAdd** — per-dtype typed accumulation (f32/f64
11878    ///   native, bf16/f16 via an f32 accumulator; out seeded from `base` then
11879    ///   `+= src`), key `[T, U32, T, T]` (`base`, fixed-U32 `indices`, `src`,
11880    ///   `passthrough(base)` output). Each `index_add_<dt>` / `scatter_add_<dt>`
11881    ///   section carries a SPECIFIC single-dtype `entry_point` resolved AS-IS (no
11882    ///   fan), 4 dtypes each, mapping to its OWN typed wrapper.
11883    ///
11884    /// The `indices` operand is a FIXED single-dtype (U32) slot in every section
11885    /// (like compare's U8 mask / paged's U32 block-table), so there is NO
11886    /// independent index-dtype axis and no multi-axis `FanoutDtypeMismatch`
11887    /// deferral — the whole family migrates.
11888    ///
11889    /// For each migrated key: resolves to the EXACT production wrapper with
11890    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
11891    /// contiguous, and the contract's bit-stable precision riding through.
11892    #[test]
11893    fn global_bindings_registers_indexing_family_from_contract() {
11894        let table = global_bindings();
11895        let mut checked = 0usize;
11896
11897        // Assert a (op, key) resolves to `expected` with the contract provenance.
11898        let mut check =
11899            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
11900                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
11901                let entry = alts
11902                    .iter()
11903                    .find(|e| e.kernel as usize == expected as usize)
11904                    .unwrap_or_else(|| {
11905                        panic!(
11906                            "{op:?}/{label}/Cpu: the production wrapper must be bound \
11907                         FROM the indexing contract in global_bindings() — found {} \
11908                         alternative(s) with sources {:?}",
11909                            alts.len(),
11910                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
11911                        )
11912                    });
11913                assert_eq!(
11914                    entry.kernel_source, "portable-cpu",
11915                    "{op:?}/{label}: family must be contract-sourced \
11916                 (kernel_source=\"portable-cpu\"); got {:?}",
11917                    entry.kernel_source,
11918                );
11919                assert!(
11920                    !entry.caps.strided_input,
11921                    "{op:?}/{label}: caps preserved (contiguous-only)",
11922                );
11923                assert!(
11924                    entry.precision.bit_stable_on_same_hardware,
11925                    "{op:?}/{label}: contract's bit-stable claim rode through",
11926                );
11927                checked += 1;
11928            };
11929
11930        // IndexSelect / Gather — dtype-agnostic byte copy, key [T, U32, T], one
11931        // wrapper fanned per dtype (9 production dtypes; I8 trimmed).
11932        let byte_dts = [
11933            DType::F32,
11934            DType::F64,
11935            DType::BF16,
11936            DType::F16,
11937            DType::U32,
11938            DType::U8,
11939            DType::I16,
11940            DType::I32,
11941            DType::I64,
11942        ];
11943        for dt in byte_dts {
11944            check(
11945                OpKind::IndexSelect,
11946                &[dt, DType::U32, dt],
11947                index_select_cpu_wrapper,
11948                "index_select",
11949            );
11950            check(
11951                OpKind::Gather,
11952                &[dt, DType::U32, dt],
11953                gather_cpu_wrapper,
11954                "gather",
11955            );
11956        }
11957
11958        // IndexAdd / ScatterAdd — per-dtype typed accumulation, key
11959        // [T, U32, T, T], each `<op>_<dt>` symbol resolved AS-IS (no fan).
11960        let acc_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
11961        let index_add_wrappers: [crate::kernel::KernelRef; 4] = [
11962            index_add_f32_cpu_wrapper,
11963            index_add_f64_cpu_wrapper,
11964            index_add_bf16_cpu_wrapper,
11965            index_add_f16_cpu_wrapper,
11966        ];
11967        let scatter_add_wrappers: [crate::kernel::KernelRef; 4] = [
11968            scatter_add_f32_cpu_wrapper,
11969            scatter_add_f64_cpu_wrapper,
11970            scatter_add_bf16_cpu_wrapper,
11971            scatter_add_f16_cpu_wrapper,
11972        ];
11973        for (i, dt) in acc_dts.iter().enumerate() {
11974            check(
11975                OpKind::IndexAdd,
11976                &[*dt, DType::U32, *dt, *dt],
11977                index_add_wrappers[i],
11978                "index_add",
11979            );
11980            check(
11981                OpKind::ScatterAdd,
11982                &[*dt, DType::U32, *dt, *dt],
11983                scatter_add_wrappers[i],
11984                "scatter_add",
11985            );
11986        }
11987
11988        assert_eq!(
11989            checked,
11990            9 + 9 + 4 + 4,
11991            "index_select(9) + gather(9) + index_add(4) + scatter_add(4) \
11992             contract-sourced bindings",
11993        );
11994    }
11995
11996    /// Gate for the CPU **matmul** family moved to FKC-contract registration.
11997    /// IMPORTED from `fuel-dispatch/kernel-contracts/cpu/matmul.fkc.md` via the production
11998    /// `CpuLinkRegistry` (chaining `CPU_MATMUL_ENTRY_POINTS`):
11999    /// - **MatMul** — bare batched matmul (`OpKind::MatMul`), key `[T, T, T]`
12000    ///   (lhs, rhs + `passthrough(lhs)` output). Each per-dtype section
12001    ///   (`## matmul_f32`, …) carries a SPECIFIC single-dtype `entry_point`
12002    ///   resolved AS-IS (no fan), 6 dtypes (F32/F64/BF16/F16 with an f32/native
12003    ///   accumulator + I8/U8 with an i32 accumulator + saturating store).
12004    /// - **FusedLinear** — fused matmul + bias-add (`OpKind::FusedLinear`), key
12005    ///   `[T, T, T, T]` (a, b, bias + `passthrough(a)` output). Reuses
12006    ///   `OpParams::Matmul` for shape; bias is a REQUIRED 1-D `[N]` operand (no
12007    ///   optional fan). 4 dtypes (F32/F64/BF16/F16).
12008    ///
12009    /// This family exercises the CRITICAL alternatives-at-the-same-key path: the
12010    /// binding table supports MULTIPLE ranked kernels per `(op, dtypes, backend)`
12011    /// key, and the MKL/AOCL BLAS siblings (external `fuel-mkl-cpu-backend` /
12012    /// `fuel-aocl-cpu-backend` crates, registered through the exported dispatch
12013    /// helpers with their own `"mkl"`/`"aocl"` `kernel_source` tags) may register
12014    /// at these SAME keys — SEPARATE and out of scope here. So this gate does NOT
12015    /// assert the portable wrapper is the SOLE alternative; it `find`s the
12016    /// portable `"portable-cpu"`-sourced entry among the alternatives.
12017    ///
12018    /// SEPARATE seams left untouched: the `FusedKernelRegistry`
12019    /// `FusedOps::FUSED_LINEAR` registration (`register_default_fused_kernels`) is
12020    /// hand-written and not FKC-imported (the matmul contract declares NO
12021    /// `fused_op` sections); the quant `QMatMul` / `Nf4Matmul` OpKinds have their
12022    /// own contracts and stay hand-written.
12023    ///
12024    /// For each migrated key: the portable wrapper is bound with
12025    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12026    /// contiguous, and the contract's bit-stable precision riding through.
12027    #[test]
12028    fn global_bindings_registers_matmul_family_from_contract() {
12029        let table = global_bindings();
12030        let mut checked = 0usize;
12031
12032        // Assert a (op, key) resolves to `expected` (the portable wrapper) with
12033        // the contract provenance — `find`ing it among any BLAS-sibling
12034        // alternatives at the same key (never asserting single-alternative).
12035        let mut check =
12036            |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12037                let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12038                let entry = alts
12039                    .iter()
12040                    .find(|e| e.kernel as usize == expected as usize)
12041                    .unwrap_or_else(|| {
12042                        panic!(
12043                            "{op:?}/{label}/Cpu: the portable wrapper must be bound \
12044                         FROM the matmul contract in global_bindings() — found {} \
12045                         alternative(s) with sources {:?}",
12046                            alts.len(),
12047                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12048                        )
12049                    });
12050                assert_eq!(
12051                    entry.kernel_source, "portable-cpu",
12052                    "{op:?}/{label}: portable kernel must be contract-sourced \
12053                 (kernel_source=\"portable-cpu\"); got {:?}",
12054                    entry.kernel_source,
12055                );
12056                assert!(
12057                    !entry.caps.strided_input,
12058                    "{op:?}/{label}: caps preserved (contiguous-only)",
12059                );
12060                assert!(
12061                    entry.precision.bit_stable_on_same_hardware,
12062                    "{op:?}/{label}: contract's bit-stable claim rode through",
12063                );
12064                checked += 1;
12065            };
12066
12067        // MatMul — key [T, T, T], per-dtype wrapper resolved AS-IS. 6 dtypes.
12068        let mm_dts = [
12069            DType::F32,
12070            DType::F64,
12071            DType::BF16,
12072            DType::F16,
12073            DType::I8,
12074            DType::U8,
12075        ];
12076        let mm_wrappers: [crate::kernel::KernelRef; 6] = [
12077            matmul_f32_cpu_wrapper,
12078            matmul_f64_cpu_wrapper,
12079            matmul_bf16_cpu_wrapper,
12080            matmul_f16_cpu_wrapper,
12081            matmul_i8_cpu_wrapper,
12082            matmul_u8_cpu_wrapper,
12083        ];
12084        for (i, dt) in mm_dts.iter().enumerate() {
12085            check(OpKind::MatMul, &[*dt, *dt, *dt], mm_wrappers[i], "matmul");
12086        }
12087
12088        // FusedLinear — key [T, T, T, T], per-dtype wrapper resolved AS-IS. 4 dtypes.
12089        let fl_dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12090        let fl_wrappers: [crate::kernel::KernelRef; 4] = [
12091            fused_linear_f32_cpu_wrapper,
12092            fused_linear_f64_cpu_wrapper,
12093            fused_linear_bf16_cpu_wrapper,
12094            fused_linear_f16_cpu_wrapper,
12095        ];
12096        for (i, dt) in fl_dts.iter().enumerate() {
12097            check(
12098                OpKind::FusedLinear,
12099                &[*dt, *dt, *dt, *dt],
12100                fl_wrappers[i],
12101                "fused_linear",
12102            );
12103        }
12104
12105        assert_eq!(
12106            checked,
12107            6 + 4,
12108            "matmul(6) + fused_linear(4) contract-sourced bindings",
12109        );
12110    }
12111
12112    /// Gate for the CPU **attention** family's `KernelBindingTable` path migrated
12113    /// to FKC-contract registration. FlashAttn (forward) + the three
12114    /// FlashAttnBackward{Q,K,V} selectors + PagedAttn — 5 ops × 4 dtypes ×
12115    /// {no-alibi, with-alibi} = 40 bindings — are IMPORTED from
12116    /// `fuel-dispatch/kernel-contracts/cpu/attention.fkc.md` (the `op_kind:` sections).
12117    /// Each section declares `alibi_slopes` as an `optional: true` LAST input, so
12118    /// the importer's optional-operand fan registers BOTH the no-alibi key
12119    /// (`[q,k,v(,do),out]` / `[q,kc,vc,bt,cl,out]`) and the with-alibi key
12120    /// (`+alibi`), both resolving the SAME wrapper — byte-for-byte the deleted
12121    /// hand-written `no_alibi`/`with_alibi` regs. Forward FlashAttn and the three
12122    /// backward selectors share the single `OpParams::FlashAttn` carrier (no
12123    /// dedicated backward variant); PagedAttn uses `OpParams::PagedAttn`.
12124    ///
12125    /// **PagedAttn is now REGISTRABLE + contract-sourced (FDX gather-sidecar arc,
12126    /// slice A).** Its `fdx.gather: paged_blocks` pool is import METADATA (§3.9.1):
12127    /// the block_table / context_lens ride as ordinary U32 operands +
12128    /// `OpParams::PagedAttn`, so registration does not depend on the FDX gather
12129    /// VIEW (which stays [consumer-ahead]). Its bindings are asserted
12130    /// contract-sourced alongside FlashAttn below — BORN-RED discriminator: the
12131    /// deleted hand-written regs stamped an empty `kernel_source`, so the
12132    /// `kernel_source == "portable-cpu"` assertion failed until the four paged
12133    /// sections were flipped `registrable: true` + wired into
12134    /// `CPU_ATTENTION_ENTRY_POINTS`. The SEPARATE `FusedKernelRegistry`
12135    /// FLASH_ATTN* / PAGED_ATTN seam (`register_default_fused_kernels`) is
12136    /// untouched (stays hand-written, exactly as before).
12137    ///
12138    /// For each of the 40 keys: resolves to the EXACT production wrapper with
12139    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12140    /// contiguous, and the contract's bit-stable precision riding through.
12141    #[test]
12142    fn global_bindings_registers_attention_family_from_contract() {
12143        let table = global_bindings();
12144        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12145
12146        // Forward FlashAttn wrappers (order matches `dts`); the same wrapper
12147        // serves both the no-alibi [q,k,v,out] and with-alibi [q,k,v,alibi,out] keys.
12148        let fa_wrappers: [crate::kernel::KernelRef; 4] = [
12149            flash_attn_f32_cpu_wrapper,
12150            flash_attn_f64_cpu_wrapper,
12151            flash_attn_bf16_cpu_wrapper,
12152            flash_attn_f16_cpu_wrapper,
12153        ];
12154        // FlashAttnBackward{Q,K,V} wrappers (order matches `dts`).
12155        let fabq: [crate::kernel::KernelRef; 4] = [
12156            flash_attn_backward_q_f32_cpu_wrapper,
12157            flash_attn_backward_q_f64_cpu_wrapper,
12158            flash_attn_backward_q_bf16_cpu_wrapper,
12159            flash_attn_backward_q_f16_cpu_wrapper,
12160        ];
12161        let fabk: [crate::kernel::KernelRef; 4] = [
12162            flash_attn_backward_k_f32_cpu_wrapper,
12163            flash_attn_backward_k_f64_cpu_wrapper,
12164            flash_attn_backward_k_bf16_cpu_wrapper,
12165            flash_attn_backward_k_f16_cpu_wrapper,
12166        ];
12167        let fabv: [crate::kernel::KernelRef; 4] = [
12168            flash_attn_backward_v_f32_cpu_wrapper,
12169            flash_attn_backward_v_f64_cpu_wrapper,
12170            flash_attn_backward_v_bf16_cpu_wrapper,
12171            flash_attn_backward_v_f16_cpu_wrapper,
12172        ];
12173        // PagedAttn wrappers (order matches `dts`); the same wrapper serves both
12174        // the no-alibi [q,kc,vc,bt,cl,out] and with-alibi (+alibi) keys.
12175        let pa_wrappers: [crate::kernel::KernelRef; 4] = [
12176            paged_attn_f32_cpu_wrapper,
12177            paged_attn_f64_cpu_wrapper,
12178            paged_attn_bf16_cpu_wrapper,
12179            paged_attn_f16_cpu_wrapper,
12180        ];
12181
12182        // Assert `op`/`key` resolves to `expected` with the contract provenance,
12183        // FINDING it among any alternatives at the key (never single-alternative).
12184        let check = |op: OpKind, key: &[DType], expected: crate::kernel::KernelRef, label: &str| {
12185            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12186            let entry = alts
12187                .iter()
12188                .find(|e| e.kernel as usize == expected as usize)
12189                .unwrap_or_else(|| {
12190                    panic!(
12191                        "{op:?}/{label}/Cpu: the production wrapper must be bound \
12192                         FROM the attention contract in global_bindings() — found {} \
12193                         alternative(s) with sources {:?}",
12194                        alts.len(),
12195                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12196                    )
12197                });
12198            assert_eq!(
12199                entry.kernel_source, "portable-cpu",
12200                "{op:?}/{label}: family must be contract-sourced \
12201                 (kernel_source=\"portable-cpu\"); got {:?}",
12202                entry.kernel_source,
12203            );
12204            assert!(
12205                !entry.caps.strided_input,
12206                "{op:?}/{label}: caps preserved (contiguous-only)",
12207            );
12208            assert!(
12209                entry.precision.bit_stable_on_same_hardware,
12210                "{op:?}/{label}: contract's bit-stable claim rode through",
12211            );
12212        };
12213
12214        let mut checked = 0usize;
12215        for (i, dt) in dts.iter().enumerate() {
12216            // Forward: no-alibi [q,k,v,out] + with-alibi [q,k,v,alibi,out].
12217            let fa_noa: &[DType] = &[*dt, *dt, *dt, *dt];
12218            let fa_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12219            check(OpKind::FlashAttn, fa_noa, fa_wrappers[i], "flash no-alibi");
12220            check(OpKind::FlashAttn, fa_a, fa_wrappers[i], "flash with-alibi");
12221            checked += 2;
12222
12223            // Backward Q/K/V: no-alibi [q,k,v,do,out] + with-alibi [q,k,v,do,alibi,out].
12224            let bw_noa: &[DType] = &[*dt, *dt, *dt, *dt, *dt];
12225            let bw_a: &[DType] = &[*dt, *dt, *dt, *dt, *dt, *dt];
12226            for (op, ws) in [
12227                (OpKind::FlashAttnBackwardQ, &fabq),
12228                (OpKind::FlashAttnBackwardK, &fabk),
12229                (OpKind::FlashAttnBackwardV, &fabv),
12230            ] {
12231                check(op, bw_noa, ws[i], "backward no-alibi");
12232                check(op, bw_a, ws[i], "backward with-alibi");
12233                checked += 2;
12234            }
12235
12236            // PagedAttn (FDX gather-sidecar arc, slice A): now CONTRACT-SOURCED
12237            // like FlashAttn. no-alibi [q,kc,vc,bt:U32,cl:U32,out] + with-alibi
12238            // (+alibi). BORN-RED discriminator: before the migration the paged
12239            // bindings were hand-written (`kernel_source == ""`); `check` requires
12240            // `kernel_source == "portable-cpu"`, so it fails until the four paged
12241            // sections are flipped `registrable: true` + resolved via
12242            // CPU_ATTENTION_ENTRY_POINTS. Proves the gather block is import
12243            // metadata, not a registration blocker.
12244            let pa_noa: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt];
12245            let pa_a: &[DType] = &[*dt, *dt, *dt, DType::U32, DType::U32, *dt, *dt];
12246            check(OpKind::PagedAttn, pa_noa, pa_wrappers[i], "paged no-alibi");
12247            check(OpKind::PagedAttn, pa_a, pa_wrappers[i], "paged with-alibi");
12248            checked += 2;
12249        }
12250        assert_eq!(
12251            checked, 40,
12252            "FlashAttn(8) + FlashAttnBackward{{Q,K,V}}(24) + PagedAttn(8) = 40 \
12253             contract-sourced bindings",
12254        );
12255    }
12256
12257    /// The CPU **in-place scalar-param** family is registered FROM its FKC
12258    /// contract (`fuel-dispatch/kernel-contracts/cpu/inplace-unary-affine.fkc.md`) via
12259    /// `register_cpu_inplace_from_contract`, NOT the deleted hand-written
12260    /// `table.register(<Op>Inplace / InplaceAffine / ClampInplace / PowIInplace,
12261    /// &unary(dt), …)` regs. 21 in-place unary ops (each fanning `[F32,F64,BF16,
12262    /// F16]` = 84) + `InplaceAffine` / `ClampInplace` / `PowIInplace` (4 dtypes
12263    /// each = 12) = 96 bindings, all keyed `[T, T]` (the single `out` operand +
12264    /// its `passthrough(out)` mirror; the executor's `InplaceKernel` arm passes
12265    /// the target as `outputs[0]`, so the wrapper takes 0 inputs + 1 output, but
12266    /// the binding-table KEY is `[T, T]`).
12267    ///
12268    /// For each of the 96 keys: resolves to the EXACT production wrapper with
12269    /// `kernel_source == "portable-cpu"` (the contract provenance tag), caps
12270    /// contiguous, and the contract's bit-stable precision riding through.
12271    #[test]
12272    fn global_bindings_registers_inplace_family_from_contract() {
12273        let table = global_bindings();
12274        let dts = [DType::F32, DType::F64, DType::BF16, DType::F16];
12275
12276        // Assert `op`/`[dt,dt]` resolves to `expected` with the contract
12277        // provenance, FINDING it among any alternatives at the key.
12278        let check = |op: OpKind, dt: DType, expected: crate::kernel::KernelRef, label: &str| {
12279            let key: &[DType] = &[dt, dt];
12280            let alts = table.lookup_alternatives(op, key, BackendId::Cpu);
12281            let entry = alts
12282                .iter()
12283                .find(|e| e.kernel as usize == expected as usize)
12284                .unwrap_or_else(|| {
12285                    panic!(
12286                        "{op:?}/{label}/{dt:?}/Cpu: the production wrapper must be bound \
12287                         FROM the in-place contract in global_bindings() — found {} \
12288                         alternative(s) with sources {:?}",
12289                        alts.len(),
12290                        alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12291                    )
12292                });
12293            assert_eq!(
12294                entry.kernel_source, "portable-cpu",
12295                "{op:?}/{label}/{dt:?}: family must be contract-sourced \
12296                 (kernel_source=\"portable-cpu\"); got {:?}",
12297                entry.kernel_source,
12298            );
12299            assert!(
12300                !entry.caps.strided_input,
12301                "{op:?}/{label}/{dt:?}: caps preserved (contiguous-only)",
12302            );
12303            assert!(
12304                entry.precision.bit_stable_on_same_hardware,
12305                "{op:?}/{label}/{dt:?}: contract's bit-stable claim rode through",
12306            );
12307        };
12308
12309        // 21 in-place unary ops × 4 dtypes (wrapper order matches `dts`).
12310        // Each row: (OpKind, label, [f32, f64, bf16, f16] wrappers).
12311        let unary_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12312            (
12313                OpKind::ReluInplace,
12314                "relu",
12315                [
12316                    relu_inplace_f32_cpu_wrapper,
12317                    relu_inplace_f64_cpu_wrapper,
12318                    relu_inplace_bf16_cpu_wrapper,
12319                    relu_inplace_f16_cpu_wrapper,
12320                ],
12321            ),
12322            (
12323                OpKind::SiluInplace,
12324                "silu",
12325                [
12326                    silu_inplace_f32_cpu_wrapper,
12327                    silu_inplace_f64_cpu_wrapper,
12328                    silu_inplace_bf16_cpu_wrapper,
12329                    silu_inplace_f16_cpu_wrapper,
12330                ],
12331            ),
12332            (
12333                OpKind::GeluTanhInplace,
12334                "gelu_tanh",
12335                [
12336                    gelu_inplace_f32_cpu_wrapper,
12337                    gelu_inplace_f64_cpu_wrapper,
12338                    gelu_inplace_bf16_cpu_wrapper,
12339                    gelu_inplace_f16_cpu_wrapper,
12340                ],
12341            ),
12342            (
12343                OpKind::TanhInplace,
12344                "tanh",
12345                [
12346                    tanh_inplace_f32_cpu_wrapper,
12347                    tanh_inplace_f64_cpu_wrapper,
12348                    tanh_inplace_bf16_cpu_wrapper,
12349                    tanh_inplace_f16_cpu_wrapper,
12350                ],
12351            ),
12352            (
12353                OpKind::SigmoidInplace,
12354                "sigmoid",
12355                [
12356                    sigmoid_inplace_f32_cpu_wrapper,
12357                    sigmoid_inplace_f64_cpu_wrapper,
12358                    sigmoid_inplace_bf16_cpu_wrapper,
12359                    sigmoid_inplace_f16_cpu_wrapper,
12360                ],
12361            ),
12362            (
12363                OpKind::NegInplace,
12364                "neg",
12365                [
12366                    neg_inplace_f32_cpu_wrapper,
12367                    neg_inplace_f64_cpu_wrapper,
12368                    neg_inplace_bf16_cpu_wrapper,
12369                    neg_inplace_f16_cpu_wrapper,
12370                ],
12371            ),
12372            (
12373                OpKind::AbsInplace,
12374                "abs",
12375                [
12376                    abs_inplace_f32_cpu_wrapper,
12377                    abs_inplace_f64_cpu_wrapper,
12378                    abs_inplace_bf16_cpu_wrapper,
12379                    abs_inplace_f16_cpu_wrapper,
12380                ],
12381            ),
12382            (
12383                OpKind::SqrInplace,
12384                "sqr",
12385                [
12386                    sqr_inplace_f32_cpu_wrapper,
12387                    sqr_inplace_f64_cpu_wrapper,
12388                    sqr_inplace_bf16_cpu_wrapper,
12389                    sqr_inplace_f16_cpu_wrapper,
12390                ],
12391            ),
12392            (
12393                OpKind::SqrtInplace,
12394                "sqrt",
12395                [
12396                    sqrt_inplace_f32_cpu_wrapper,
12397                    sqrt_inplace_f64_cpu_wrapper,
12398                    sqrt_inplace_bf16_cpu_wrapper,
12399                    sqrt_inplace_f16_cpu_wrapper,
12400                ],
12401            ),
12402            (
12403                OpKind::RsqrtInplace,
12404                "rsqrt",
12405                [
12406                    rsqrt_inplace_f32_cpu_wrapper,
12407                    rsqrt_inplace_f64_cpu_wrapper,
12408                    rsqrt_inplace_bf16_cpu_wrapper,
12409                    rsqrt_inplace_f16_cpu_wrapper,
12410                ],
12411            ),
12412            (
12413                OpKind::RecipInplace,
12414                "recip",
12415                [
12416                    recip_inplace_f32_cpu_wrapper,
12417                    recip_inplace_f64_cpu_wrapper,
12418                    recip_inplace_bf16_cpu_wrapper,
12419                    recip_inplace_f16_cpu_wrapper,
12420                ],
12421            ),
12422            (
12423                OpKind::ExpInplace,
12424                "exp",
12425                [
12426                    exp_inplace_f32_cpu_wrapper,
12427                    exp_inplace_f64_cpu_wrapper,
12428                    exp_inplace_bf16_cpu_wrapper,
12429                    exp_inplace_f16_cpu_wrapper,
12430                ],
12431            ),
12432            (
12433                OpKind::LogInplace,
12434                "log",
12435                [
12436                    log_inplace_f32_cpu_wrapper,
12437                    log_inplace_f64_cpu_wrapper,
12438                    log_inplace_bf16_cpu_wrapper,
12439                    log_inplace_f16_cpu_wrapper,
12440                ],
12441            ),
12442            (
12443                OpKind::SinInplace,
12444                "sin",
12445                [
12446                    sin_inplace_f32_cpu_wrapper,
12447                    sin_inplace_f64_cpu_wrapper,
12448                    sin_inplace_bf16_cpu_wrapper,
12449                    sin_inplace_f16_cpu_wrapper,
12450                ],
12451            ),
12452            (
12453                OpKind::CosInplace,
12454                "cos",
12455                [
12456                    cos_inplace_f32_cpu_wrapper,
12457                    cos_inplace_f64_cpu_wrapper,
12458                    cos_inplace_bf16_cpu_wrapper,
12459                    cos_inplace_f16_cpu_wrapper,
12460                ],
12461            ),
12462            (
12463                OpKind::SignInplace,
12464                "sign",
12465                [
12466                    sign_inplace_f32_cpu_wrapper,
12467                    sign_inplace_f64_cpu_wrapper,
12468                    sign_inplace_bf16_cpu_wrapper,
12469                    sign_inplace_f16_cpu_wrapper,
12470                ],
12471            ),
12472            (
12473                OpKind::FloorInplace,
12474                "floor",
12475                [
12476                    floor_inplace_f32_cpu_wrapper,
12477                    floor_inplace_f64_cpu_wrapper,
12478                    floor_inplace_bf16_cpu_wrapper,
12479                    floor_inplace_f16_cpu_wrapper,
12480                ],
12481            ),
12482            (
12483                OpKind::CeilInplace,
12484                "ceil",
12485                [
12486                    ceil_inplace_f32_cpu_wrapper,
12487                    ceil_inplace_f64_cpu_wrapper,
12488                    ceil_inplace_bf16_cpu_wrapper,
12489                    ceil_inplace_f16_cpu_wrapper,
12490                ],
12491            ),
12492            (
12493                OpKind::RoundInplace,
12494                "round",
12495                [
12496                    round_inplace_f32_cpu_wrapper,
12497                    round_inplace_f64_cpu_wrapper,
12498                    round_inplace_bf16_cpu_wrapper,
12499                    round_inplace_f16_cpu_wrapper,
12500                ],
12501            ),
12502            (
12503                OpKind::ErfInplace,
12504                "erf",
12505                [
12506                    erf_inplace_f32_cpu_wrapper,
12507                    erf_inplace_f64_cpu_wrapper,
12508                    erf_inplace_bf16_cpu_wrapper,
12509                    erf_inplace_f16_cpu_wrapper,
12510                ],
12511            ),
12512            (
12513                OpKind::GeluInplace,
12514                "gelu",
12515                [
12516                    gelu_erf_inplace_f32_cpu_wrapper,
12517                    gelu_erf_inplace_f64_cpu_wrapper,
12518                    gelu_erf_inplace_bf16_cpu_wrapper,
12519                    gelu_erf_inplace_f16_cpu_wrapper,
12520                ],
12521            ),
12522        ];
12523
12524        // Affine / clamp / powi — scalar-param single sections. Note the affine
12525        // wrapper name is `inplace_affine_<dt>_cpu_wrapper` (words swapped vs the
12526        // `affine_inplace_<dt>` symbol).
12527        let scalar_family: &[(OpKind, &str, [crate::kernel::KernelRef; 4])] = &[
12528            (
12529                OpKind::InplaceAffine,
12530                "affine",
12531                [
12532                    inplace_affine_f32_cpu_wrapper,
12533                    inplace_affine_f64_cpu_wrapper,
12534                    inplace_affine_bf16_cpu_wrapper,
12535                    inplace_affine_f16_cpu_wrapper,
12536                ],
12537            ),
12538            (
12539                OpKind::ClampInplace,
12540                "clamp",
12541                [
12542                    clamp_inplace_f32_cpu_wrapper,
12543                    clamp_inplace_f64_cpu_wrapper,
12544                    clamp_inplace_bf16_cpu_wrapper,
12545                    clamp_inplace_f16_cpu_wrapper,
12546                ],
12547            ),
12548            (
12549                OpKind::PowIInplace,
12550                "powi",
12551                [
12552                    powi_inplace_f32_cpu_wrapper,
12553                    powi_inplace_f64_cpu_wrapper,
12554                    powi_inplace_bf16_cpu_wrapper,
12555                    powi_inplace_f16_cpu_wrapper,
12556                ],
12557            ),
12558        ];
12559
12560        let mut checked = 0usize;
12561        for (op, label, ws) in unary_family.iter().chain(scalar_family.iter()) {
12562            for (i, dt) in dts.iter().enumerate() {
12563                check(*op, *dt, ws[i], label);
12564                checked += 1;
12565            }
12566        }
12567        assert_eq!(
12568            checked, 96,
12569            "21 in-place unary (×4) + InplaceAffine/ClampInplace/PowIInplace (×4) = 96 \
12570             contract-sourced bindings",
12571        );
12572    }
12573
12574    /// Gate for the CPU **cast** family migrated to FKC-contract registration.
12575    /// The FULL directed-pair matrix — every ordered pair of the 11 real numeric
12576    /// dtypes {F32,F64,F16,BF16,F8E4M3,U8,I8,U32,I16,I32,I64}, identity excluded =
12577    /// 11 × 10 = 110 pairs — is IMPORTED from
12578    /// `fuel-dispatch/kernel-contracts/cpu/cast.fkc.md` (see
12579    /// `register_cpu_cast_from_contract`). Each per-pair section declares a
12580    /// single-dtype `src` input + `fixed(DST)` output, so it does NOT dtype-fan —
12581    /// the importer keys `[SRC, DST]` (byte-for-byte the deleted hand-written
12582    /// `table.register(Cast, &[SRC, DST], …)` regs) and resolves the SPECIFIC
12583    /// `cast_<src>_to_<dst>` byte-kernel symbol AS-IS through the production
12584    /// `CpuLinkRegistry` (chaining `CPU_CAST_ENTRY_POINTS`). Because the binding
12585    /// lookup is keyed on the TARGET dtype, every one of a target's 10 source
12586    /// pairs resolves to the SAME per-target `cast_to_<dst>_cpu_wrapper` (which
12587    /// dispatches on source internally) — the fanned byte-kernel symbols are the
12588    /// synthetic-umbrella precedent (10 distinct entry_points → 1 wrapper).
12589    ///
12590    /// For each of the 110 pairs: resolves to the EXACT production per-target
12591    /// wrapper with `kernel_source == "portable-cpu"` (the contract provenance
12592    /// tag), caps contiguous-only, and the contract's bit-stable precision riding
12593    /// through. FKC is the SOLE registration path for the whole family.
12594    #[test]
12595    fn global_bindings_registers_cast_family_from_contract() {
12596        let table = global_bindings();
12597
12598        // Per-target wrapper (the binding-table key is keyed on the TARGET dtype;
12599        // each wrapper dispatches on the source dtype internally).
12600        let targets: [(DType, crate::kernel::KernelRef); 11] = [
12601            (DType::F32, cast_to_f32_cpu_wrapper),
12602            (DType::F64, cast_to_f64_cpu_wrapper),
12603            (DType::F16, cast_to_f16_cpu_wrapper),
12604            (DType::BF16, cast_to_bf16_cpu_wrapper),
12605            (DType::F8E4M3, cast_to_f8e4m3_cpu_wrapper),
12606            (DType::U8, cast_to_u8_cpu_wrapper),
12607            (DType::I8, cast_to_i8_cpu_wrapper),
12608            (DType::U32, cast_to_u32_cpu_wrapper),
12609            (DType::I16, cast_to_i16_cpu_wrapper),
12610            (DType::I32, cast_to_i32_cpu_wrapper),
12611            (DType::I64, cast_to_i64_cpu_wrapper),
12612        ];
12613        let all_dts: [DType; 11] = [
12614            DType::F32,
12615            DType::F64,
12616            DType::F16,
12617            DType::BF16,
12618            DType::F8E4M3,
12619            DType::U8,
12620            DType::I8,
12621            DType::U32,
12622            DType::I16,
12623            DType::I32,
12624            DType::I64,
12625        ];
12626
12627        let mut checked = 0usize;
12628        for (dst, expected) in targets {
12629            for src in all_dts {
12630                if src == dst {
12631                    continue; // identity pairs are elided by the optimizer, not registered
12632                }
12633                let key: &[DType] = &[src, dst];
12634                let alts = table.lookup_alternatives(OpKind::Cast, key, BackendId::Cpu);
12635                let entry = alts
12636                    .iter()
12637                    .find(|e| e.kernel as usize == expected as usize)
12638                    .unwrap_or_else(|| {
12639                        panic!(
12640                            "Cast {src:?}->{dst:?}/Cpu: the production per-target wrapper must be \
12641                             bound FROM the cast contract in global_bindings() — found {} \
12642                             alternative(s) with sources {:?}",
12643                            alts.len(),
12644                            alts.iter().map(|e| e.kernel_source).collect::<Vec<_>>(),
12645                        )
12646                    });
12647                assert_eq!(
12648                    entry.kernel_source, "portable-cpu",
12649                    "Cast {src:?}->{dst:?}: family must be contract-sourced \
12650                     (kernel_source=\"portable-cpu\"); got {:?}",
12651                    entry.kernel_source,
12652                );
12653                assert!(
12654                    !entry.caps.strided_input,
12655                    "Cast {src:?}->{dst:?}: caps preserved (contiguous-only)",
12656                );
12657                assert!(
12658                    entry.precision.bit_stable_on_same_hardware,
12659                    "Cast {src:?}->{dst:?}: contract's bit-stable claim rode through",
12660                );
12661                checked += 1;
12662            }
12663        }
12664        assert_eq!(
12665            checked, 110,
12666            "11 target dtypes × 10 sources each = 110 directed cast pairs (identity excluded)"
12667        );
12668    }
12669
12670    /// Lookup miss returns NoBackendForOp with diagnostic data.
12671    #[test]
12672    fn binding_table_lookup_miss_errors() {
12673        let mut table = KernelBindingTable::new();
12674        register_cpu_kernels(&mut table);
12675        // I64 isn't registered for any elementwise op — must error.
12676        // (BF16/F16/F32/F64 all have AddElementwise wrappers as of
12677        // Phase C's multi-dtype expansion.)
12678        let result = table.lookup(
12679            OpKind::AddElementwise,
12680            &[DType::I64, DType::I64, DType::I64],
12681            BackendId::Cpu,
12682        );
12683        assert!(result.is_err());
12684    }
12685
12686    /// F8E4M3 ↔ {F32, F16, BF16} casts (alpha.29 CastSubBytePlan sibling
12687    /// on the CPU side) are all reachable through the binding table.
12688    #[test]
12689    fn cpu_f8e4m3_cast_pairs_registered() {
12690        let mut table = KernelBindingTable::new();
12691        register_cpu_kernels(&mut table);
12692        for other in [DType::F32, DType::F16, DType::BF16] {
12693            for (src, dst) in [(DType::F8E4M3, other), (other, DType::F8E4M3)] {
12694                table
12695                    .lookup(OpKind::Cast, &[src, dst], BackendId::Cpu)
12696                    .unwrap_or_else(|e| panic!("Cast {src:?} → {dst:?} (CPU) not registered: {e}"));
12697            }
12698        }
12699    }
12700
12701    /// Integer MatMul (i8 / u8) registrations land under the same
12702    /// `(MatMul, [T, T, T], Cpu)` key shape as the float variants.
12703    #[test]
12704    fn cpu_int_matmul_registered() {
12705        let mut table = KernelBindingTable::new();
12706        register_cpu_kernels(&mut table);
12707        for t in [DType::I8, DType::U8] {
12708            table
12709                .lookup(OpKind::MatMul, &[t, t, t], BackendId::Cpu)
12710                .unwrap_or_else(|e| panic!("MatMul {t:?} (CPU) not registered: {e}"));
12711        }
12712    }
12713
12714    /// End-to-end: register, resolve target backend, look up the
12715    /// kernel, allocate input/output Storages, call the kernel,
12716    /// verify output bytes match the elementwise sum. This is the
12717    /// proof-of-concept for the entire B-phase dispatch path.
12718    #[test]
12719    fn b5_end_to_end_add_elementwise_f32() {
12720        // 1. Build registry + capability advertisement.
12721        let mut registry = CapabilityRegistry::new();
12722        registry.register(cpu_caps());
12723
12724        // 2. Resolve which backend handles (AddElementwise, F32).
12725        let backend =
12726            resolve_target_backend(&registry, OpKind::AddElementwise, DType::F32).expect("resolve");
12727        assert_eq!(backend, BackendId::Cpu);
12728
12729        // 3. Build binding table + register CPU wrappers.
12730        let mut bindings = KernelBindingTable::new();
12731        register_cpu_kernels(&mut bindings);
12732
12733        // 4. Look up the kernel for (op, dtypes, backend).
12734        let kernel = bindings
12735            .lookup(
12736                OpKind::AddElementwise,
12737                &[DType::F32, DType::F32, DType::F32],
12738                backend,
12739            )
12740            .expect("lookup");
12741
12742        // 5. Allocate input + output Storages.
12743        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12744        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0]);
12745        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
12746
12747        let inputs = vec![Arc::new(RwLock::new(lhs)), Arc::new(RwLock::new(rhs))];
12748        let mut outputs = vec![Arc::new(RwLock::new(out))];
12749
12750        // 6. Call the dispatch wrapper.
12751        kernel(&inputs, &mut outputs, &[], &OpParams::None).expect("kernel");
12752
12753        // 7. Verify output bytes match elementwise sum.
12754        let out_guard = outputs[0].read().unwrap();
12755        if let BackendStorage::Cpu(c) = &out_guard.inner {
12756            let typed: &[f32] = c.as_slice().expect("cast");
12757            assert_eq!(typed, &[11.0, 22.0, 33.0, 44.0]);
12758        } else {
12759            panic!("expected CPU output");
12760        }
12761    }
12762
12763    /// E2E: wrong number of inputs surfaces a typed error.
12764    #[test]
12765    fn b5_wrapper_arity_check() {
12766        let mut bindings = KernelBindingTable::new();
12767        register_cpu_kernels(&mut bindings);
12768        let kernel = bindings
12769            .lookup(
12770                OpKind::AddElementwise,
12771                &[DType::F32, DType::F32, DType::F32],
12772                BackendId::Cpu,
12773            )
12774            .unwrap();
12775
12776        // Only one input — should error, not panic.
12777        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12778        let out = fuel_memory::alloc_cpu_zeroed(DType::F32, 2).unwrap();
12779        let inputs = vec![Arc::new(RwLock::new(lhs))];
12780        let mut outputs = vec![Arc::new(RwLock::new(out))];
12781
12782        let result = kernel(&inputs, &mut outputs, &[], &OpParams::None);
12783        assert!(result.is_err());
12784    }
12785
12786    /// GAP-015 regression: a held binding-table snapshot must not block a
12787    /// writer, and must not block the holder's own later reads.
12788    ///
12789    /// This is the deadlock reduced to ONE thread, which is what makes it a
12790    /// usable test. The suite-level reproducer needed `--test-threads=24+`
12791    /// to get a writer to queue against readers; here the same cycle is
12792    /// forced deterministically, because under the old
12793    /// `RwLock<KernelBindingTable>` the sequence below is a *self*-deadlock:
12794    /// `global_bindings()` returned a live `RwLockReadGuard`, so asking for
12795    /// the write lock while still holding it waited on a lock this very
12796    /// thread was blocking, forever. Under copy-on-write there is no guard
12797    /// to hold, so it just runs.
12798    ///
12799    /// Watchdog rather than a bare call, because the failure mode is a hang,
12800    /// not a panic: without the timeout this test would wedge the whole
12801    /// binary instead of reporting. Verified born-red — see the commit.
12802    #[test]
12803    fn held_snapshot_does_not_block_a_concurrent_write() {
12804        use std::sync::mpsc;
12805        use std::time::Duration;
12806
12807        let (tx, rx) = mpsc::channel();
12808        std::thread::spawn(move || {
12809            // 1. Take a snapshot and KEEP it across the write below.
12810            let snap = global_bindings();
12811            let before = snap
12812                .lookup(
12813                    OpKind::AddElementwise,
12814                    &[DType::F32, DType::F32, DType::F32],
12815                    BackendId::Cpu,
12816                )
12817                .is_ok();
12818
12819            // 2. Write while that snapshot is still alive. This is the step
12820            //    that deadlocked. The extender is intentionally a no-op —
12821            //    the hazard is the lock transition, not what gets written.
12822            extend_global_bindings(|_t| {});
12823
12824            // 3. Read again while STILL holding the original snapshot. Under
12825            //    std's anti-writer-starvation policy this is the second read
12826            //    that a queued writer would have blocked.
12827            let _snap2 = global_bindings();
12828
12829            // 4. The original snapshot stays usable — it is an owned Arc, so
12830            //    the swap in step 2 cannot invalidate it.
12831            let after = snap
12832                .lookup(
12833                    OpKind::AddElementwise,
12834                    &[DType::F32, DType::F32, DType::F32],
12835                    BackendId::Cpu,
12836                )
12837                .is_ok();
12838
12839            tx.send((before, after)).ok();
12840        });
12841
12842        match rx.recv_timeout(Duration::from_secs(30)) {
12843            Ok((before, after)) => {
12844                assert!(
12845                    before,
12846                    "CPU AddElementwise+F32 should resolve in the snapshot"
12847                );
12848                assert!(
12849                    after,
12850                    "snapshot must stay readable after a concurrent table swap"
12851                );
12852            }
12853            Err(_) => panic!(
12854                "GAP-015 regression: holding a binding-table snapshot across \
12855                 extend_global_bindings() deadlocked (30s watchdog). The read \
12856                 path must hand out an owned snapshot, not a lock guard."
12857            ),
12858        }
12859    }
12860
12861    /// Global registry auto-registers CPU on first access.
12862    #[test]
12863    fn global_registry_auto_registers_cpu() {
12864        // First access initializes the registry with CPU caps.
12865        let r = global_registry();
12866        assert!(!r.backends().is_empty());
12867        // CPU is registered.
12868        let cpu = r.backends().iter().find(|c| c.backend_id == BackendId::Cpu);
12869        assert!(cpu.is_some(), "CPU should be auto-registered");
12870    }
12871
12872    /// Global bindings auto-registers the CPU AddElementwise+F32
12873    /// wrapper on first access.
12874    #[test]
12875    fn global_bindings_auto_registers_cpu_wrappers() {
12876        let b = global_bindings();
12877        let result = b.lookup(
12878            OpKind::AddElementwise,
12879            &[DType::F32, DType::F32, DType::F32],
12880            BackendId::Cpu,
12881        );
12882        assert!(
12883            result.is_ok(),
12884            "CPU AddElementwise+F32 should be registered"
12885        );
12886    }
12887
12888    /// When the `cuda` feature is on, `register_cuda_kernels` (the
12889    /// post-retirement residue: cuBLAS MatMul / ReduceTo / Copy /
12890    /// CausalConv1d) AND `register_baracuda_cuda_kernels` are both
12891    /// auto-registered into the global table. The PTX-duplicate
12892    /// unary/binary registrations were stripped in the
12893    /// fuel-cuda-kernels retirement (commit d9898fec), so elementwise
12894    /// keys carry exactly ONE alternative — baracuda's.
12895    #[cfg(feature = "cuda")]
12896    #[test]
12897    fn global_bindings_auto_registers_cuda_paths() {
12898        let b = global_bindings();
12899        // register_cuda_kernels residue: F32 MatMul via cuBLAS.
12900        let cublas = b.lookup(
12901            OpKind::MatMul,
12902            &[DType::F32, DType::F32, DType::F32],
12903            BackendId::Cuda,
12904        );
12905        assert!(
12906            cublas.is_ok(),
12907            "cuBLAS F32 MatMul should be auto-registered on Cuda"
12908        );
12909
12910        // Baracuda path: int8 MatMul exists only via baracuda. If this
12911        // resolves, both paths fired.
12912        let baracuda_int8 = b.lookup(
12913            OpKind::MatMul,
12914            &[DType::I8, DType::I8, DType::I8],
12915            BackendId::Cuda,
12916        );
12917        assert!(
12918            baracuda_int8.is_ok(),
12919            "baracuda int8 MatMul should be auto-registered on Cuda",
12920        );
12921
12922        // Post-strip invariant: F32 unary Neg resolves with exactly
12923        // one alternative (baracuda is the single source of truth for
12924        // CUDA elementwise; a second entry would mean a duplicate
12925        // registration crept back in).
12926        let alts = b.lookup_alternatives(
12927            OpKind::NegElementwise,
12928            &[DType::F32, DType::F32],
12929            BackendId::Cuda,
12930        );
12931        assert!(
12932            alts.len() == 1,
12933            "expected exactly 1 CUDA Neg F32 alternative (baracuda); got {}",
12934            alts.len(),
12935        );
12936    }
12937
12938    /// Picker-alternatives audit harness: enumerates the global binding
12939    /// table and prints every `(op, dtypes)` key with `>1` registered
12940    /// alternative (multi-backend or multi-impl within one backend). Read the
12941    /// table with `--nocapture`; the only assertion is that the table is
12942    /// non-empty, so a registry that silently emptied cannot pass as an
12943    /// empty audit.
12944    ///
12945    /// Run: `cargo test -p fuel-dispatch --features cuda,vulkan     ///     audit_multi_backend_coverage -- --nocapture`
12946    #[test]
12947    fn audit_multi_backend_coverage() {
12948        let b = global_bindings();
12949        assert!(
12950            !b.is_empty(),
12951            "the global binding table is empty, so this audit would report nothing"
12952        );
12953
12954        // Group by (op_kind, dtypes); each entry maps to the list of
12955        // (backend, n_alts_within_backend). Iterates via iter_precision
12956        // because that already exposes per-alternative tuples.
12957        // OpKind/DType aren't Ord, so we use Vec-based group lookup.
12958        /// `((op, dtypes), [(backend, count)])` -- one coverage group.
12959        type CoverageGroup = ((OpKind, Vec<DType>), Vec<(BackendId, usize)>);
12960        let mut grouped: Vec<CoverageGroup> = Vec::new();
12961        for (op, dtypes, backend, _precision) in b.iter_precision() {
12962            let key = (op, dtypes.to_vec());
12963            if let Some((_, entry)) = grouped.iter_mut().find(|(k, _)| *k == key) {
12964                if let Some(slot) = entry.iter_mut().find(|(be, _)| *be == backend) {
12965                    slot.1 += 1;
12966                } else {
12967                    entry.push((backend, 1));
12968                }
12969            } else {
12970                grouped.push((key, vec![(backend, 1)]));
12971            }
12972        }
12973        // Sort by op debug-string, then dtype list, for stable output.
12974        grouped.sort_by(|a, b| {
12975            let oa = format!("{:?}", a.0.0);
12976            let ob = format!("{:?}", b.0.0);
12977            oa.cmp(&ob).then_with(|| {
12978                let da = format!("{:?}", a.0.1);
12979                let db = format!("{:?}", b.0.1);
12980                da.cmp(&db)
12981            })
12982        });
12983
12984        let total_keys = grouped.len();
12985        let mut multi_backend = 0;
12986        let mut multi_impl_single_backend = 0;
12987        let mut single_alt = 0;
12988
12989        println!("\n=== Picker-alternatives audit ===");
12990        println!("Total unique (op, dtypes) keys: {total_keys}");
12991        println!("Total alternatives (sum):       {}", b.len());
12992        println!();
12993        println!("Keys with >1 alternative (per Judge-picking working set):");
12994        for ((op, dtypes), backends) in &grouped {
12995            let total_alts: usize = backends.iter().map(|(_, n)| *n).sum();
12996            if total_alts <= 1 {
12997                single_alt += 1;
12998                continue;
12999            }
13000            if backends.len() > 1 {
13001                multi_backend += 1;
13002            } else {
13003                multi_impl_single_backend += 1;
13004            }
13005            let backend_summary: Vec<String> = backends
13006                .iter()
13007                .map(|(be, n)| {
13008                    if *n == 1 {
13009                        format!("{be:?}")
13010                    } else {
13011                        format!("{be:?}×{n}")
13012                    }
13013                })
13014                .collect();
13015            println!(
13016                "  {op:?} {dtypes:?} → {} alts: [{}]",
13017                total_alts,
13018                backend_summary.join(", "),
13019            );
13020        }
13021        println!();
13022        println!("--- summary ---");
13023        println!("Single-alternative keys (no pick to make): {single_alt}");
13024        println!("Multi-backend keys (cross-backend pick):   {multi_backend}");
13025        println!("Multi-impl single-backend keys:            {multi_impl_single_backend}");
13026    }
13027
13028    // =========================================================================
13029    // Step E Phase C / B1 — DEVICE_INFLIGHT counter (the BALANCE gate)
13030    // =========================================================================
13031    //
13032    // The counter is PROCESS-WIDE, so these tests use sentinel `gpu_id`s no
13033    // real device uses (and that no other test in this binary touches) to stay
13034    // independent of any concurrent counter activity.
13035
13036    /// The crux of B1: after a balanced sequence of `inc`/`dec`, the per-device
13037    /// count returns to its baseline. Mirrors the executor's invariant — every
13038    /// async submit (`inc`) is matched by exactly one completion-handle `Drop`
13039    /// (`dec`), so after a realize fully drains the counter is back where it
13040    /// started (the `drain_handles` empty-map assert, in counter form).
13041    #[test]
13042    fn inflight_inc_dec_balances_to_baseline() {
13043        let loc = DeviceLocation::Cuda { gpu_id: 99_001 };
13044        let base = inflight_count(loc);
13045
13046        // N submits in flight → count rises by N.
13047        const N: u32 = 7;
13048        for i in 0..N {
13049            inflight_inc(loc);
13050            assert_eq!(
13051                inflight_count(loc),
13052                base + i + 1,
13053                "inc must raise the count"
13054            );
13055        }
13056        assert_eq!(inflight_count(loc), base + N);
13057
13058        // N completions retire → count falls back to baseline.
13059        for i in 0..N {
13060            inflight_dec(loc);
13061            assert_eq!(
13062                inflight_count(loc),
13063                base + N - i - 1,
13064                "dec must lower the count",
13065            );
13066        }
13067        assert_eq!(
13068            inflight_count(loc),
13069            base,
13070            "balanced inc/dec must return the count to its pre-sequence baseline",
13071        );
13072    }
13073
13074    /// `inflight_dec` is underflow-saturating: decrementing a device whose count
13075    /// is already 0 (or that has never been touched) leaves it at 0, never wraps
13076    /// to `u32::MAX`. A stray dec is harmless to scheduling, never a poison.
13077    #[test]
13078    fn inflight_dec_is_underflow_safe() {
13079        let untouched = DeviceLocation::Vulkan { gpu_id: 99_002 };
13080        // Never incremented: dec must not create a wrapped count.
13081        inflight_dec(untouched);
13082        assert_eq!(
13083            inflight_count(untouched),
13084            0,
13085            "dec on an untouched device stays 0"
13086        );
13087
13088        let loc = DeviceLocation::Vulkan { gpu_id: 99_003 };
13089        inflight_inc(loc);
13090        inflight_dec(loc);
13091        assert_eq!(inflight_count(loc), 0);
13092        // One extra dec past zero (the over-drain guard).
13093        inflight_dec(loc);
13094        assert_eq!(
13095            inflight_count(loc),
13096            0,
13097            "extra dec past zero must saturate, not wrap"
13098        );
13099    }
13100
13101    /// Distinct `DeviceLocation`s have independent slots — incrementing one
13102    /// device's count never perturbs another's (the per-device keying the
13103    /// selector relies on to compare CUDA vs Vulkan load).
13104    #[test]
13105    fn inflight_counts_are_per_device_independent() {
13106        let cuda = DeviceLocation::Cuda { gpu_id: 99_004 };
13107        let vulkan = DeviceLocation::Vulkan { gpu_id: 99_004 };
13108        let base_c = inflight_count(cuda);
13109        let base_v = inflight_count(vulkan);
13110
13111        inflight_inc(cuda);
13112        inflight_inc(cuda);
13113        inflight_inc(vulkan);
13114
13115        assert_eq!(inflight_count(cuda), base_c + 2);
13116        assert_eq!(inflight_count(vulkan), base_v + 1);
13117
13118        inflight_dec(cuda);
13119        inflight_dec(cuda);
13120        inflight_dec(vulkan);
13121        assert_eq!(inflight_count(cuda), base_c);
13122        assert_eq!(inflight_count(vulkan), base_v);
13123    }
13124
13125    /// FKC cost unification — Part A. `derive_backend_caps` reads a
13126    /// backend's kernels out of the binding table and advertises the
13127    /// `(OpKind, OUTPUT-dtype)` pairs those kernels cover — the general
13128    /// analogue of the hand-maintained `default_cpu_caps`. Verifies:
13129    /// (1) only the requested backend's keys are picked; (2) the OUTPUT
13130    /// dtype (last operand) is what's advertised for multi-dtype keys;
13131    /// (3) substrate/device match the backend. Feature-independent: it
13132    /// builds a fresh table with synthetic wrappers.
13133    #[test]
13134    fn derive_backend_caps_mirrors_binding_table_output_dtypes() {
13135        fn stub(
13136            _i: &[Arc<RwLock<Storage>>],
13137            _o: &mut [Arc<RwLock<Storage>>],
13138            _l: &[Layout],
13139            _p: &OpParams,
13140        ) -> Result<()> {
13141            Ok(())
13142        }
13143        fn stub_b(
13144            _i: &[Arc<RwLock<Storage>>],
13145            _o: &mut [Arc<RwLock<Storage>>],
13146            _l: &[Layout],
13147            _p: &OpParams,
13148        ) -> Result<()> {
13149            Ok(())
13150        }
13151        fn stub_c(
13152            _i: &[Arc<RwLock<Storage>>],
13153            _o: &mut [Arc<RwLock<Storage>>],
13154            _l: &[Layout],
13155            _p: &OpParams,
13156        ) -> Result<()> {
13157            Ok(())
13158        }
13159
13160        let mut table = KernelBindingTable::new();
13161        // A CPU key that MUST NOT bleed into the Vulkan derivation.
13162        table.register(
13163            OpKind::AddElementwise,
13164            &[DType::F32, DType::F32, DType::F32],
13165            BackendId::Cpu,
13166            stub,
13167        );
13168        // Vulkan: an elementwise key (single output dtype) ...
13169        table.register(
13170            OpKind::MulElementwise,
13171            &[DType::F32, DType::F32, DType::F32],
13172            BackendId::Vulkan,
13173            stub_b,
13174        );
13175        // ... and a MIXED-dtype key: inputs F16/F16, OUTPUT F32. The
13176        // derived pair must key on the OUTPUT dtype (F32), not an input.
13177        table.register(
13178            OpKind::MatMul,
13179            &[DType::F16, DType::F16, DType::F32],
13180            BackendId::Vulkan,
13181            stub_c,
13182        );
13183
13184        let vk0 = DeviceLocation::Vulkan { gpu_id: 0 };
13185        let caps = derive_backend_caps(BackendId::Vulkan, vk0, &table);
13186
13187        assert_eq!(caps.backend_id, BackendId::Vulkan);
13188        assert_eq!(caps.device_location, vk0);
13189        assert_eq!(caps.storage_substrate, SubstrateClass::VulkanBuffer);
13190        // Elementwise output dtype advertised.
13191        assert!(
13192            caps.op_dtype_support
13193                .contains(&(OpKind::MulElementwise, DType::F32))
13194        );
13195        // Multi-dtype key advertises the OUTPUT dtype (F32), not F16.
13196        assert!(
13197            caps.op_dtype_support
13198                .contains(&(OpKind::MatMul, DType::F32))
13199        );
13200        assert!(
13201            !caps
13202                .op_dtype_support
13203                .contains(&(OpKind::MatMul, DType::F16))
13204        );
13205        // The CPU key is NOT attributed to Vulkan.
13206        assert!(
13207            !caps
13208                .op_dtype_support
13209                .contains(&(OpKind::AddElementwise, DType::F32))
13210        );
13211        // A universal host-staging path back to CPU is advertised so the
13212        // transfer matrix can price GPU↔CPU crossings.
13213        assert!(caps
13214            .transfer_paths
13215            .iter()
13216            .any(|&(dst, path)| dst == DeviceLocation::Cpu && path == TransferPath::HostStaging));
13217    }
13218
13219    /// CapturedRun executor build-out (4b-ζ): `copy_from_cuda_wrapper`'s
13220    /// CUDA-output branch converted from allocate-and-replace
13221    /// (`slot_copy_to_new` + `*dst = copied`) to write-into
13222    /// (`CudaStorageBytes::copy_from_device`). Byte-compares the new
13223    /// write-into result against the OLD `slot_copy_to_new`-based behavior
13224    /// for a non-trivial (17-element, mixed-value) case, AND confirms the
13225    /// destination's buffer identity (device address) is preserved — the
13226    /// property capture-safety depends on (allocate-and-replace would swap
13227    /// in a fresh `Arc<DeviceBuffer<u8>>`, changing the address; write-into
13228    /// must not).
13229    #[test]
13230    #[ignore = "requires a live CUDA device"]
13231    #[cfg(feature = "cuda")]
13232    fn copy_from_cuda_wrapper_cuda_output_write_into_matches_old_behavior() {
13233        use fuel_cuda_backend::{CudaDevice, CudaStorageBytes};
13234
13235        let Ok(dev) = CudaDevice::new(0) else {
13236            return fuel_test_support::hardware::skip(
13237                fuel_test_support::hardware::Hardware::Cuda,
13238                fuel_test_support::hardware::Missing::device("CudaDevice::new(0) failed"),
13239            );
13240        };
13241
13242        let src_data: Vec<f32> = (0..17).map(|i| i as f32 * 1.5 - 3.0).collect();
13243        let src_bytes: Vec<u8> = src_data.iter().flat_map(|f| f.to_le_bytes()).collect();
13244        let src_cb = CudaStorageBytes::from_cpu_bytes(&dev, &src_bytes).expect("h2d src");
13245        let src_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13246            BackendStorage::Cuda(src_cb),
13247            DType::F32,
13248        )));
13249
13250        // Pre-allocated output filled with distinguishable garbage — proves
13251        // the write-into path actually overwrites every byte, not just
13252        // reads through stale garbage by luck.
13253        let garbage: Vec<u8> = vec![0xAAu8; src_bytes.len()];
13254        let dst_cb = CudaStorageBytes::from_cpu_bytes(&dev, &garbage).expect("h2d garbage");
13255        let dst_arc: Arc<RwLock<Storage>> = Arc::new(RwLock::new(Storage::new(
13256            BackendStorage::Cuda(dst_cb),
13257            DType::F32,
13258        )));
13259
13260        // Destination buffer identity BEFORE the wrapper runs.
13261        let before_ptr = {
13262            let g = dst_arc.read().unwrap();
13263            let BackendStorage::Cuda(c) = &g.inner else {
13264                panic!("not cuda")
13265            };
13266            c.buffer() as *const _ as usize
13267        };
13268
13269        let inputs = vec![Arc::clone(&src_arc)];
13270        let mut outputs = vec![Arc::clone(&dst_arc)];
13271        copy_from_cuda_wrapper(&inputs, &mut outputs, &[], &OpParams::None)
13272            .expect("copy_from_cuda_wrapper (write-into CUDA branch)");
13273
13274        let after_ptr = {
13275            let g = dst_arc.read().unwrap();
13276            let BackendStorage::Cuda(c) = &g.inner else {
13277                panic!("not cuda")
13278            };
13279            c.buffer() as *const _ as usize
13280        };
13281        assert_eq!(
13282            before_ptr, after_ptr,
13283            "write-into must preserve the output's buffer identity (device address)"
13284        );
13285
13286        let new_bytes = {
13287            let g = dst_arc.read().unwrap();
13288            let BackendStorage::Cuda(c) = &g.inner else {
13289                panic!("not cuda")
13290            };
13291            c.to_cpu_bytes().expect("d2h new")
13292        };
13293
13294        // Independently reproduce the OLD allocate-and-replace behavior
13295        // (`slot_copy_to_new`) from the SAME source, for comparison.
13296        let old_bytes = {
13297            let g = src_arc.read().unwrap();
13298            let BackendStorage::Cuda(c) = &g.inner else {
13299                panic!("not cuda")
13300            };
13301            let copied = c
13302                .slot_copy_to_new(0, c.len_bytes())
13303                .expect("slot_copy_to_new (old allocate-and-replace path)");
13304            copied.to_cpu_bytes().expect("d2h old")
13305        };
13306
13307        assert_eq!(
13308            new_bytes, old_bytes,
13309            "write-into result must byte-match the old slot_copy_to_new result"
13310        );
13311        assert_eq!(new_bytes, src_bytes, "and both must match the source bytes");
13312    }
13313}